"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) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require2() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
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 __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
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);

// ../../node_modules/.pnpm/ci-info@4.4.0/node_modules/ci-info/vendors.json
var require_vendors = __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_info = __commonJS({
  "../../node_modules/.pnpm/ci-info@4.4.0/node_modules/ci-info/index.js"(exports2) {
    "use strict";
    var vendors = require_vendors();
    var env3 = process.env;
    Object.defineProperty(exports2, "_vendors", {
      value: vendors.map(function(v2) {
        return v2.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 isCI = envs.every(function(obj) {
          return checkEnv(obj);
        });
        exports2[vendor.constant] = isCI;
        if (!isCI) {
          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/exit-hook@2.2.1/node_modules/exit-hook/index.js
var require_exit_hook = __commonJS({
  "../../node_modules/.pnpm/exit-hook@2.2.1/node_modules/exit-hook/index.js"(exports2, module2) {
    "use strict";
    var callbacks = /* @__PURE__ */ new Set();
    var isCalled = false;
    var isRegistered = false;
    function exit(exit2, signal) {
      if (isCalled) {
        return;
      }
      isCalled = true;
      for (const callback of callbacks) {
        callback();
      }
      if (exit2 === true) {
        process.exit(128 + signal);
      }
    }
    module2.exports = (callback) => {
      callbacks.add(callback);
      if (!isRegistered) {
        isRegistered = true;
        process.once("exit", exit);
        process.once("SIGINT", exit.bind(null, true, 2));
        process.once("SIGTERM", exit.bind(null, true, 15));
        process.on("message", (message) => {
          if (message === "shutdown") {
            exit(true, -128);
          }
        });
      }
      return () => {
        callbacks.delete(callback);
      };
    };
  }
});

// ../../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 c;
      for (var i = 0, len = str.length; i < len; i++) {
        c = str[i];
        switch (c) {
          case "/":
          case "$":
          case "^":
          case "+":
          case ".":
          case "(":
          case ")":
          case "=":
          case "!":
          case "|":
            reStr += "\\" + c;
            break;
          case "?":
            if (extended) {
              reStr += ".";
              break;
            }
          case "[":
          case "]":
            if (extended) {
              reStr += c;
              break;
            }
          case "{":
            if (extended) {
              inGroup = true;
              reStr += "(";
              break;
            }
          case "}":
            if (extended) {
              inGroup = false;
              reStr += ")";
              break;
            }
          case ",":
            if (inGroup) {
              reStr += "|";
              break;
            }
            reStr += "\\" + c;
            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 += c;
        }
      }
      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 = (object, key, value) => Object.defineProperty(object, 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 `'/**'`
        (_2, 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'
        (_2, 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
      [
        /(\^|\\\/)?\\\*$/,
        (_2, 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, current2) => prev.replace(current2[0], current2[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, regex2) {
        this.origin = origin;
        this.pattern = pattern;
        this.negative = negative;
        this.regex = regex2;
      }
    };
    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 regex2 = makeRegex(pattern, ignoreCase);
      return new IgnoreRule(
        origin,
        pattern,
        negative,
        regex2
      );
    };
    var throwError = (message, Ctor) => {
      throw new Ctor(message);
    };
    var checkPath = (path62, originalPath, doThrow) => {
      if (!isString2(path62)) {
        return doThrow(
          `path must be a string, but got \`${originalPath}\``,
          TypeError
        );
      }
      if (!path62) {
        return doThrow(`path must not be empty`, TypeError);
      }
      if (checkPath.isNotRelative(path62)) {
        const r2 = "`path.relative()`d";
        return doThrow(
          `path should be a ${r2} string, but got "${originalPath}"`,
          RangeError
        );
      }
      return true;
    };
    var isNotRelative = (path62) => REGEX_TEST_INVALID_PATH.test(path62);
    checkPath.isNotRelative = isNotRelative;
    checkPath.convert = (p) => p;
    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(path62, 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(path62);
          if (matched) {
            ignored2 = !negative;
            unignored = negative;
          }
        });
        return {
          ignored: ignored2,
          unignored
        };
      }
      // @returns {TestResult}
      _test(originalPath, cache, checkUnignored, slices) {
        const path62 = originalPath && checkPath.convert(originalPath);
        checkPath(
          path62,
          originalPath,
          this._allowRelativePaths ? RETURN_FALSE : throwError
        );
        return this._t(path62, cache, checkUnignored, slices);
      }
      _t(path62, cache, checkUnignored, slices) {
        if (path62 in cache) {
          return cache[path62];
        }
        if (!slices) {
          slices = path62.split(SLASH2);
        }
        slices.pop();
        if (!slices.length) {
          return cache[path62] = this._testOne(path62, checkUnignored);
        }
        const parent = this._t(
          slices.join(SLASH2) + SLASH2,
          cache,
          checkUnignored,
          slices
        );
        return cache[path62] = parent.ignored ? parent : this._testOne(path62, checkUnignored);
      }
      ignores(path62) {
        return this._test(path62, this._ignoreCache, false).ignored;
      }
      createFilter() {
        return (path62) => !this.ignores(path62);
      }
      filter(paths) {
        return makeArray(paths).filter(this.createFilter());
      }
      // @returns {TestResult}
      test(path62) {
        return this._test(path62, this._testCache, true);
      }
    };
    var factory = (options) => new Ignore(options);
    var isPathValid = (path62) => checkPath(path62 && checkPath.convert(path62), path62, 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 = (path62) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path62) || isNotRelative(path62);
    }
  }
});

// ../../node_modules/.pnpm/acorn-import-phases@1.0.4_acorn@8.14.0/node_modules/acorn-import-phases/src/plugin.cjs
var require_plugin = __commonJS({
  "../../node_modules/.pnpm/acorn-import-phases@1.0.4_acorn@8.14.0/node_modules/acorn-import-phases/src/plugin.cjs"(exports2) {
    "use strict";
    exports2.plugin = function acornImportPhase(options, Parser3, tt) {
      return class extends Parser3 {
        parseImport(node) {
          this._phase = null;
          const result = super.parseImport(node);
          if (this._phase) {
            node.phase = this._phase;
          }
          return result;
        }
        parseImportSpecifiers() {
          let phase = options.defer !== false && this.isContextual("defer") ? "defer" : options.source !== false && this.isContextual("source") ? "source" : null;
          if (!phase) return super.parseImportSpecifiers();
          const phaseId = this.parseIdent();
          if (this.isContextual("from") || this.type === tt.comma) {
            const defaultSpecifier = this.startNodeAt(phaseId.start, phaseId.loc && phaseId.loc.start);
            defaultSpecifier.local = phaseId;
            this.checkLValSimple(
              phaseId,
              /* BIND_LEXICAL */
              2
            );
            const nodes = [this.finishNode(defaultSpecifier, "ImportDefaultSpecifier")];
            if (this.eat(tt.comma)) {
              if (this.type !== tt.star && this.type !== tt.braceL) {
                this.unexpected();
              }
              nodes.push(...super.parseImportSpecifiers());
            }
            return nodes;
          }
          this._phase = phase;
          if (phase === "defer") {
            if (this.type !== tt.star) {
              this.raiseRecoverable(
                phaseId.start,
                "'import defer' can only be used with namespace imports ('import defer * as identifierName from ...')."
              );
            }
          } else if (phase === "source") {
            if (this.type !== tt.name) {
              this.raiseRecoverable(
                phaseId.start,
                "'import source' can only be used with direct identifier specifier imports."
              );
            }
          }
          const specifiers = super.parseImportSpecifiers();
          if (phase === "source" && specifiers.some((s) => s.type !== "ImportDefaultSpecifier")) {
            this.raiseRecoverable(
              phaseId.start,
              `'import source' can only be used with direct identifier specifier imports ('import source identifierName from ...').`
            );
          }
          return specifiers;
        }
        parseExprImport(forNew) {
          const node = super.parseExprImport(forNew);
          if (node.type === "MetaProperty" && (node.property.name === "defer" || node.property.name === "source")) {
            if (this.type === tt.parenL) {
              const dynImport = this.parseDynamicImport(this.startNodeAt(node.start, node.loc && node.loc.start));
              dynImport.phase = node.property.name;
              return dynImport;
            } else {
              this.raiseRecoverable(
                node.start,
                `'import.${node.property.name}' can only be used in a dynamic import.`
              );
            }
          }
          return node;
        }
        parseImportMeta(node) {
          this.next();
          var containsEsc = this.containsEsc;
          node.property = this.parseIdent(true);
          const { name } = node.property;
          if (name !== "meta" && name !== "defer" && name !== "source") {
            this.raiseRecoverable(
              node.property.start,
              "The only valid meta property for import is 'import.meta'"
            );
          }
          if (containsEsc) {
            this.raiseRecoverable(
              node.start,
              `'import.${name}' must not contain escaped characters`
            );
          }
          if (name === "meta" && this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) {
            this.raiseRecoverable(
              node.start,
              "Cannot use 'import.meta' outside a module"
            );
          }
          return this.finishNode(node, "MetaProperty");
        }
      };
    };
  }
});

// ../../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(x2, y) {
        if (!y) return `${CSI}${x2 + 1}G`;
        return `${CSI}${y + 1};${x2 + 1}H`;
      },
      move(x2, y) {
        let ret = "";
        if (x2 < 0) ret += `${CSI}${-x2}D`;
        else if (x2 > 0) ret += `${CSI}${x2}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 process7 = global.process;
    var processOk = function(process8) {
      return process8 && typeof process8 === "object" && typeof process8.removeListener === "function" && typeof process8.emit === "function" && typeof process8.reallyExit === "function" && typeof process8.listeners === "function" && typeof process8.kill === "function" && typeof process8.pid === "number" && typeof process8.on === "function";
    };
    if (!processOk(process7)) {
      module2.exports = function() {
        return function() {
        };
      };
    } else {
      assert24 = require("assert");
      signals = require_signals();
      isWin = /^win/i.test(process7.platform);
      EE = require("events");
      if (typeof EE !== "function") {
        EE = EE.EventEmitter;
      }
      if (process7.__signal_exit_emitter__) {
        emitter = process7.__signal_exit_emitter__;
      } else {
        emitter = process7.__signal_exit_emitter__ = new EE();
        emitter.count = 0;
        emitter.emitted = {};
      }
      if (!emitter.infinite) {
        emitter.setMaxListeners(Infinity);
        emitter.infinite = true;
      }
      module2.exports = function(cb, opts) {
        if (!processOk(global.process)) {
          return function() {
          };
        }
        assert24.equal(typeof cb, "function", "a callback must be provided for exit handler");
        if (loaded === false) {
          load();
        }
        var ev = "exit";
        if (opts && opts.alwaysLast) {
          ev = "afterexit";
        }
        var remove = function() {
          emitter.removeListener(ev, cb);
          if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) {
            unload();
          }
        };
        emitter.on(ev, cb);
        return remove;
      };
      unload = function unload2() {
        if (!loaded || !processOk(global.process)) {
          return;
        }
        loaded = false;
        signals.forEach(function(sig) {
          try {
            process7.removeListener(sig, sigListeners[sig]);
          } catch (er) {
          }
        });
        process7.emit = originalProcessEmit;
        process7.reallyExit = originalProcessReallyExit;
        emitter.count -= 1;
      };
      module2.exports.unload = unload;
      emit = function emit2(event, code, signal) {
        if (emitter.emitted[event]) {
          return;
        }
        emitter.emitted[event] = true;
        emitter.emit(event, code, signal);
      };
      sigListeners = {};
      signals.forEach(function(sig) {
        sigListeners[sig] = function listener() {
          if (!processOk(global.process)) {
            return;
          }
          var listeners = process7.listeners(sig);
          if (listeners.length === emitter.count) {
            unload();
            emit("exit", null, sig);
            emit("afterexit", null, sig);
            if (isWin && sig === "SIGHUP") {
              sig = "SIGINT";
            }
            process7.kill(process7.pid, sig);
          }
        };
      });
      module2.exports.signals = function() {
        return signals;
      };
      loaded = false;
      load = function load2() {
        if (loaded || !processOk(global.process)) {
          return;
        }
        loaded = true;
        emitter.count += 1;
        signals = signals.filter(function(sig) {
          try {
            process7.on(sig, sigListeners[sig]);
            return true;
          } catch (er) {
            return false;
          }
        });
        process7.emit = processEmit;
        process7.reallyExit = processReallyExit;
      };
      module2.exports.load = load;
      originalProcessReallyExit = process7.reallyExit;
      processReallyExit = function processReallyExit2(code) {
        if (!processOk(global.process)) {
          return;
        }
        process7.exitCode = code || /* istanbul ignore next */
        0;
        emit("exit", process7.exitCode, null);
        emit("afterexit", process7.exitCode, null);
        originalProcessReallyExit.call(process7, process7.exitCode);
      };
      originalProcessEmit = process7.emit;
      processEmit = function processEmit2(ev, arg) {
        if (ev === "exit" && processOk(global.process)) {
          if (arg !== void 0) {
            process7.exitCode = arg;
          }
          var ret = originalProcessEmit.apply(this, arguments);
          emit("exit", process7.exitCode, null);
          emit("afterexit", process7.exitCode, null);
          return ret;
        } else {
          return originalProcessEmit.apply(this, arguments);
        }
      };
    }
    var assert24;
    var signals;
    var isWin;
    var EE;
    var emitter;
    var unload;
    var emit;
    var sigListeners;
    var loaded;
    var load;
    var originalProcessReallyExit;
    var processReallyExit;
    var originalProcessEmit;
    var processEmit;
  }
});

// ../../node_modules/.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 x2 = character.charCodeAt(0);
      var y = character.length == 2 ? character.charCodeAt(1) : 0;
      var codePoint = x2;
      if (55296 <= x2 && x2 <= 56319 && (56320 <= y && y <= 57343)) {
        x2 &= 1023;
        y &= 1023;
        codePoint = x2 << 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(string) {
      return string.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g) || [];
    }
    eaw.length = function(string) {
      var characters = stringToArray(string);
      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(version3, options) {
        options = parseOptions(options);
        if (version3 instanceof _SemVer) {
          if (version3.loose === !!options.loose && version3.includePrerelease === !!options.includePrerelease) {
            return version3;
          } else {
            version3 = version3.version;
          }
        } else if (typeof version3 !== "string") {
          throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version3}".`);
        }
        if (version3.length > MAX_LENGTH) {
          throw new TypeError(
            `version is longer than ${MAX_LENGTH} characters`
          );
        }
        debug4("SemVer", version3, options);
        this.options = options;
        this.loose = !!options.loose;
        this.includePrerelease = !!options.includePrerelease;
        const m2 = version3.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
        if (!m2) {
          throw new TypeError(`Invalid Version: ${version3}`);
        }
        this.raw = version3;
        this.major = +m2[1];
        this.minor = +m2[2];
        this.patch = +m2[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 (!m2[4]) {
          this.prerelease = [];
        } else {
          this.prerelease = m2[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 = m2[5] ? m2[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 base2 = Number(identifierBase) ? 1 : 0;
            if (this.prerelease.length === 0) {
              this.prerelease = [base2];
            } 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(base2);
              }
            }
            if (identifier) {
              let prerelease = [identifier, base2];
              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 parse8 = (version3, options, throwErrors = false) => {
      if (version3 instanceof SemVer) {
        return version3;
      }
      try {
        return new SemVer(version3, options);
      } catch (er) {
        if (!throwErrors) {
          return null;
        }
        throw er;
      }
    };
    module2.exports = parse8;
  }
});

// ../../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 parse8 = require_parse();
    var valid = (version3, options) => {
      const v2 = parse8(version3, options);
      return v2 ? v2.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 parse8 = require_parse();
    var clean = (version3, options) => {
      const s = parse8(version3.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 = (version3, release, options, identifier, identifierBase) => {
      if (typeof options === "string") {
        identifierBase = identifier;
        identifier = options;
        options = void 0;
      }
      try {
        return new SemVer(
          version3 instanceof SemVer ? version3.version : version3,
          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 parse8 = require_parse();
    var diff = (version1, version22) => {
      const v1 = parse8(version1, null, true);
      const v2 = parse8(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 parse8 = require_parse();
    var prerelease = (version3, options) => {
      const parsed = parse8(version3, 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 parse8 = require_parse();
    var { safeRe: re, t } = require_re();
    var coerce3 = (version3, options) => {
      if (version3 instanceof SemVer) {
        return version3;
      }
      if (typeof version3 === "number") {
        version3 = String(version3);
      }
      if (typeof version3 !== "string") {
        return null;
      }
      options = options || {};
      let match = null;
      if (!options.rtl) {
        match = version3.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(version3)) && (!match || match.index + match[0].length !== version3.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 parse8(`${major}.${minor}.${patch}${prerelease}${build}`, options);
    };
    module2.exports = coerce3;
  }
});

// ../../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((r2) => this.parseRange(r2.trim())).filter((c) => c.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((c) => !isNullSet(c[0]));
          if (this.set.length === 0) {
            this.set = [first];
          } else if (this.set.length > 1) {
            for (const c of this.set) {
              if (c.length === 1 && isAny(c[0])) {
                this.set = [c];
                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 cached = cache.get(memoKey);
        if (cached) {
          return cached;
        }
        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(version3) {
        if (!version3) {
          return false;
        }
        if (typeof version3 === "string") {
          try {
            version3 = new SemVer(version3, this.options);
          } catch (er) {
            return false;
          }
        }
        for (let i = 0; i < this.set.length; i++) {
          if (testSet(this.set[i], version3, 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 = (c) => c.value === "<0.0.0-0";
    var isAny = (c) => c.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((c) => replaceTilde(c, options)).join(" ");
    };
    var replaceTilde = (comp, options) => {
      const r2 = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
      return comp.replace(r2, (_2, M2, m2, p, pr) => {
        debug4("tilde", comp, _2, M2, m2, p, pr);
        let ret;
        if (isX(M2)) {
          ret = "";
        } else if (isX(m2)) {
          ret = `>=${M2}.0.0 <${+M2 + 1}.0.0-0`;
        } else if (isX(p)) {
          ret = `>=${M2}.${m2}.0 <${M2}.${+m2 + 1}.0-0`;
        } else if (pr) {
          debug4("replaceTilde pr", pr);
          ret = `>=${M2}.${m2}.${p}-${pr} <${M2}.${+m2 + 1}.0-0`;
        } else {
          ret = `>=${M2}.${m2}.${p} <${M2}.${+m2 + 1}.0-0`;
        }
        debug4("tilde return", ret);
        return ret;
      });
    };
    var replaceCarets = (comp, options) => {
      return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" ");
    };
    var replaceCaret = (comp, options) => {
      debug4("caret", comp, options);
      const r2 = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
      const z2 = options.includePrerelease ? "-0" : "";
      return comp.replace(r2, (_2, M2, m2, p, pr) => {
        debug4("caret", comp, _2, M2, m2, p, pr);
        let ret;
        if (isX(M2)) {
          ret = "";
        } else if (isX(m2)) {
          ret = `>=${M2}.0.0${z2} <${+M2 + 1}.0.0-0`;
        } else if (isX(p)) {
          if (M2 === "0") {
            ret = `>=${M2}.${m2}.0${z2} <${M2}.${+m2 + 1}.0-0`;
          } else {
            ret = `>=${M2}.${m2}.0${z2} <${+M2 + 1}.0.0-0`;
          }
        } else if (pr) {
          debug4("replaceCaret pr", pr);
          if (M2 === "0") {
            if (m2 === "0") {
              ret = `>=${M2}.${m2}.${p}-${pr} <${M2}.${m2}.${+p + 1}-0`;
            } else {
              ret = `>=${M2}.${m2}.${p}-${pr} <${M2}.${+m2 + 1}.0-0`;
            }
          } else {
            ret = `>=${M2}.${m2}.${p}-${pr} <${+M2 + 1}.0.0-0`;
          }
        } else {
          debug4("no pr");
          if (M2 === "0") {
            if (m2 === "0") {
              ret = `>=${M2}.${m2}.${p}${z2} <${M2}.${m2}.${+p + 1}-0`;
            } else {
              ret = `>=${M2}.${m2}.${p}${z2} <${M2}.${+m2 + 1}.0-0`;
            }
          } else {
            ret = `>=${M2}.${m2}.${p} <${+M2 + 1}.0.0-0`;
          }
        }
        debug4("caret return", ret);
        return ret;
      });
    };
    var replaceXRanges = (comp, options) => {
      debug4("replaceXRanges", comp, options);
      return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" ");
    };
    var replaceXRange = (comp, options) => {
      comp = comp.trim();
      const r2 = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
      return comp.replace(r2, (ret, gtlt, M2, m2, p, pr) => {
        debug4("xRange", comp, ret, gtlt, M2, m2, p, pr);
        const xM = isX(M2);
        const xm = xM || isX(m2);
        const xp = xm || isX(p);
        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) {
            m2 = 0;
          }
          p = 0;
          if (gtlt === ">") {
            gtlt = ">=";
            if (xm) {
              M2 = +M2 + 1;
              m2 = 0;
              p = 0;
            } else {
              m2 = +m2 + 1;
              p = 0;
            }
          } else if (gtlt === "<=") {
            gtlt = "<";
            if (xm) {
              M2 = +M2 + 1;
            } else {
              m2 = +m2 + 1;
            }
          }
          if (gtlt === "<") {
            pr = "-0";
          }
          ret = `${gtlt + M2}.${m2}.${p}${pr}`;
        } else if (xm) {
          ret = `>=${M2}.0.0${pr} <${+M2 + 1}.0.0-0`;
        } else if (xp) {
          ret = `>=${M2}.${m2}.0${pr} <${M2}.${+m2 + 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 = (set, version3, options) => {
      for (let i = 0; i < set.length; i++) {
        if (!set[i].test(version3)) {
          return false;
        }
      }
      if (version3.prerelease.length && !options.includePrerelease) {
        for (let i = 0; i < set.length; i++) {
          debug4(set[i].semver);
          if (set[i].semver === Comparator.ANY) {
            continue;
          }
          if (set[i].semver.prerelease.length > 0) {
            const allowed = set[i].semver;
            if (allowed.major === version3.major && allowed.minor === version3.minor && allowed.patch === version3.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 r2 = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
        const m2 = comp.match(r2);
        if (!m2) {
          throw new TypeError(`Invalid comparator: ${comp}`);
        }
        this.operator = m2[1] !== void 0 ? m2[1] : "";
        if (this.operator === "=") {
          this.operator = "";
        }
        if (!m2[2]) {
          this.semver = ANY;
        } else {
          this.semver = new SemVer(m2[2], this.options.loose);
        }
      }
      toString() {
        return this.value;
      }
      test(version3) {
        debug4("Comparator.test", version3, this.options.loose);
        if (this.semver === ANY || version3 === ANY) {
          return true;
        }
        if (typeof version3 === "string") {
          try {
            version3 = new SemVer(version3, this.options);
          } catch (er) {
            return false;
          }
        }
        return cmp(version3, 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 = (version3, range, options) => {
      try {
        range = new Range(range, options);
      } catch (er) {
        return false;
      }
      return range.test(version3);
    };
    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((c) => c.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((v2) => {
        if (rangeObj.test(v2)) {
          if (!max || maxSV.compare(v2) === -1) {
            max = v2;
            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((v2) => {
        if (rangeObj.test(v2)) {
          if (!min || minSV.compare(v2) === 1) {
            min = v2;
            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 = (version3, range, hilo, options) => {
      version3 = new SemVer(version3, 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(version3, 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(version3, low.semver)) {
          return false;
        } else if (low.operator === ecomp && ltfn(version3, 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 = (version3, range, options) => outside(version3, 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 = (version3, range, options) => outside(version3, 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 set = [];
      let first = null;
      let prev = null;
      const v2 = versions.sort((a, b) => compare(a, b, options));
      for (const version3 of v2) {
        const included = satisfies(version3, range, options);
        if (included) {
          prev = version3;
          if (!first) {
            first = version3;
          }
        } else {
          if (prev) {
            set.push([first, prev]);
          }
          prev = null;
          first = null;
        }
      }
      if (first) {
        set.push([first, null]);
      }
      const ranges = [];
      for (const [min, max] of set) {
        if (min === max) {
          ranges.push(min);
        } else if (!max && min === v2[0]) {
          ranges.push("*");
        } else if (!max) {
          ranges.push(`>=${min}`);
        } else if (min === v2[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 c of sub) {
        if (c.operator === ">" || c.operator === ">=") {
          gt = higherGT(gt, c, options);
        } else if (c.operator === "<" || c.operator === "<=") {
          lt = lowerLT(lt, c, options);
        } else {
          eqSet.add(c.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 c of dom) {
          if (!satisfies(eq, String(c), 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 c of dom) {
        hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">=";
        hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<=";
        if (gt) {
          if (needDomGTPre) {
            if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) {
              needDomGTPre = false;
            }
          }
          if (c.operator === ">" || c.operator === ">=") {
            higher = higherGT(gt, c, options);
            if (higher === c && higher !== gt) {
              return false;
            }
          } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c), options)) {
            return false;
          }
        }
        if (lt) {
          if (needDomLTPre) {
            if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) {
              needDomLTPre = false;
            }
          }
          if (c.operator === "<" || c.operator === "<=") {
            lower = lowerLT(lt, c, options);
            if (lower === c && lower !== lt) {
              return false;
            }
          } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c), options)) {
            return false;
          }
        }
        if (!c.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 constants = require_constants();
    var SemVer = require_semver();
    var identifiers = require_identifiers();
    var parse8 = 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 coerce3 = 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: parse8,
      valid,
      clean,
      inc,
      diff,
      major,
      minor,
      patch,
      prerelease,
      compare,
      rcompare,
      compareLoose,
      compareBuild,
      sort,
      rsort,
      gt,
      lt,
      eq,
      neq,
      gte,
      lte,
      cmp,
      coerce: coerce3,
      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: constants.SEMVER_SPEC_VERSION,
      RELEASE_TYPES: constants.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, v2, size, sizeCalculation) => {
          if (this.isBackgroundFetch(v2)) {
            return 0;
          }
          if (!isPosInt(size)) {
            if (sizeCalculation) {
              if (typeof sizeCalculation !== "function") {
                throw new TypeError("sizeCalculation must be a function");
              }
              size = sizeCalculation(v2, 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, _size) {
      }
      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, getOptions2) {
        for (const i of this.indexes()) {
          const v2 = this.valList[i];
          const value = this.isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
          if (value === void 0) continue;
          if (fn(value, this.keyList[i], this)) {
            return this.get(this.keyList[i], getOptions2);
          }
        }
      }
      forEach(fn, thisp = this) {
        for (const i of this.indexes()) {
          const v2 = this.valList[i];
          const value = this.isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
          if (value === void 0) continue;
          fn.call(thisp, value, this.keyList[i], this);
        }
      }
      rforEach(fn, thisp = this) {
        for (const i of this.rindexes()) {
          const v2 = this.valList[i];
          const value = this.isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
          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 v2 = this.valList[i];
          const value = this.isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
          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, v2, {
        ttl = this.ttl,
        start,
        noDisposeOnSet = this.noDisposeOnSet,
        size = 0,
        sizeCalculation = this.sizeCalculation,
        noUpdateTTL = this.noUpdateTTL,
        status: status2
      } = {}) {
        size = this.requireSize(k, v2, 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] = v2;
          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 (v2 !== 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] = v2;
            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 v2 = this.valList[head];
        if (this.isBackgroundFetch(v2)) {
          v2.__abortController.abort(new Error("evicted"));
        } else {
          this.dispose(v2, k, "evict");
          if (this.disposeAfter) {
            this.disposed.push([v2, 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 v2 = this.valList[index];
          return this.isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
        }
      }
      backgroundFetch(k, index, options, context) {
        const v2 = index === void 0 ? void 0 : this.valList[index];
        if (this.isBackgroundFetch(v2)) {
          return v2;
        }
        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 = (v3, updateCache = false) => {
          const { aborted } = ac.signal;
          const ignoreAbort = options.ignoreFetchAbort && v3 !== void 0;
          if (options.status) {
            if (aborted && !updateCache) {
              options.status.fetchAborted = true;
              options.status.fetchError = ac.signal.reason;
              if (ignoreAbort) options.status.fetchAbortIgnored = true;
            } else {
              options.status.fetchResolved = true;
            }
          }
          if (aborted && !ignoreAbort && !updateCache) {
            return fetchFail(ac.signal.reason);
          }
          if (this.valList[index] === p) {
            if (v3 === void 0) {
              if (p.__staleWhileFetching) {
                this.valList[index] = p.__staleWhileFetching;
              } else {
                this.delete(k);
              }
            } else {
              if (options.status) options.status.fetchUpdated = true;
              this.set(k, v3, fetchOpts.options);
            }
          }
          return v3;
        };
        const eb = (er) => {
          if (options.status) {
            options.status.fetchRejected = true;
            options.status.fetchError = er;
          }
          return fetchFail(er);
        };
        const fetchFail = (er) => {
          const { aborted } = ac.signal;
          const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
          const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
          const noDelete = allowStale || options.noDeleteOnFetchRejection;
          if (this.valList[index] === p) {
            const del = !noDelete || p.__staleWhileFetching === void 0;
            if (del) {
              this.delete(k);
            } else if (!allowStaleAborted) {
              this.valList[index] = p.__staleWhileFetching;
            }
          }
          if (allowStale) {
            if (options.status && p.__staleWhileFetching !== void 0) {
              options.status.returnedStale = true;
            }
            return p.__staleWhileFetching;
          } else if (p.__returned === p) {
            throw er;
          }
        };
        const pcall = (res, rej) => {
          this.fetchMethod(k, v2, fetchOpts).then((v3) => res(v3), rej);
          ac.signal.addEventListener("abort", () => {
            if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {
              res();
              if (options.allowStaleOnFetchAbort) {
                res = (v3) => cb(v3, true);
              }
            }
          });
        };
        if (options.status) options.status.fetchDispatched = true;
        const p = new Promise(pcall).then(cb, eb);
        p.__abortController = ac;
        p.__staleWhileFetching = v2;
        p.__returned = null;
        if (index === void 0) {
          this.set(k, p, { ...fetchOpts.options, status: void 0 });
          index = this.keyMap.get(k);
        } else {
          this.valList[index] = p;
        }
        return p;
      }
      isBackgroundFetch(p) {
        return p && typeof p === "object" && typeof p.then === "function" && Object.prototype.hasOwnProperty.call(
          p,
          "__staleWhileFetching"
        ) && Object.prototype.hasOwnProperty.call(p, "__returned") && (p.__returned === p || p.__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 p = this.backgroundFetch(k, index, options, fetchContext);
          return p.__returned = p;
        } else {
          const v2 = this.valList[index];
          if (this.isBackgroundFetch(v2)) {
            const stale = allowStale && v2.__staleWhileFetching !== void 0;
            if (status2) {
              status2.fetch = "inflight";
              if (stale) status2.returnedStale = true;
            }
            return stale ? v2.__staleWhileFetching : v2.__returned = v2;
          }
          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 v2;
          }
          const p = this.backgroundFetch(k, index, options, fetchContext);
          const hasStale = p.__staleWhileFetching !== void 0;
          const staleVal = hasStale && allowStale;
          if (status2) {
            status2.fetch = hasStale && isStale ? "stale" : "refresh";
            if (staleVal && isStale) status2.returnedStale = true;
          }
          return staleVal ? p.__staleWhileFetching : p.__returned = p;
        }
      }
      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(p, n) {
        this.prev[n] = p;
        this.next[p] = 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 v2 = this.valList[index];
              if (this.isBackgroundFetch(v2)) {
                v2.__abortController.abort(new Error("deleted"));
              } else {
                this.dispose(v2, k, "delete");
                if (this.disposeAfter) {
                  this.disposed.push([v2, 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 v2 = this.valList[index];
          if (this.isBackgroundFetch(v2)) {
            v2.__abortController.abort(new Error("deleted"));
          } else {
            const k = this.keyList[index];
            this.dispose(v2, k, "delete");
            if (this.disposeAfter) {
              this.disposed.push([v2, 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, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    }) : function(o, v2) {
      o["default"] = v2;
    });
    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 json(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 = json;
    function req(url38, opts = {}) {
      const href = typeof url38 === "string" ? url38 : url38.href;
      const req2 = (href.startsWith("https:") ? https2 : http3).request(url38, opts);
      const promise = new Promise((resolve6, reject) => {
        req2.once("response", resolve6).once("error", reject).end();
      });
      req2.then = promise.then.bind(promise);
      return req2;
    }
    exports2.req = req;
  }
});

// ../../node_modules/.pnpm/agent-base@7.1.3/node_modules/agent-base/dist/index.js
var require_dist = __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, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    }) : function(o, v2) {
      o["default"] = v2;
    });
    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(m2, exports3) {
      for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m2, p);
    };
    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(v2) {
        if (this[INTERNAL]) {
          this[INTERNAL].defaultPort = v2;
        }
      }
      get protocol() {
        return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:");
      }
      set protocol(v2) {
        if (this[INTERNAL]) {
          this[INTERNAL].protocol = v2;
        }
      }
    };
    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 m2 = s * 60;
    var h2 = m2 * 60;
    var d2 = h2 * 24;
    var w2 = d2 * 7;
    var y = d2 * 365.25;
    module2.exports = function(val, options) {
      options = options || {};
      var type = typeof val;
      if (type === "string" && val.length > 0) {
        return parse8(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 parse8(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 * w2;
        case "days":
        case "day":
        case "d":
          return n * d2;
        case "hours":
        case "hour":
        case "hrs":
        case "hr":
        case "h":
          return n * h2;
        case "minutes":
        case "minute":
        case "mins":
        case "min":
        case "m":
          return n * m2;
        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 >= d2) {
        return Math.round(ms / d2) + "d";
      }
      if (msAbs >= h2) {
        return Math.round(ms / h2) + "h";
      }
      if (msAbs >= m2) {
        return Math.round(ms / m2) + "m";
      }
      if (msAbs >= s) {
        return Math.round(ms / s) + "s";
      }
      return ms + "ms";
    }
    function fmtLong(ms) {
      var msAbs = Math.abs(ms);
      if (msAbs >= d2) {
        return plural(ms, msAbs, d2, "day");
      }
      if (msAbs >= h2) {
        return plural(ms, msAbs, h2, "hour");
      }
      if (msAbs >= m2) {
        return plural(ms, msAbs, m2, "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 = coerce3;
      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 hash = 0;
        for (let i = 0; i < namespace.length; i++) {
          hash = (hash << 5) - hash + namespace.charCodeAt(i);
          hash |= 0;
        }
        return createDebug.colors[Math.abs(hash) % 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, format4) => {
            if (match === "%%") {
              return "%";
            }
            index++;
            const formatter = createDebug.formatters[format4];
            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 = extend2;
        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: (v2) => {
            enableOverride = v2;
          }
        });
        if (typeof createDebug.init === "function") {
          createDebug.init(debug4);
        }
        return debug4;
      }
      function extend2(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 coerce3(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 = load;
    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 m2;
      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 && (m2 = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m2[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 c = "color: " + this.color;
      args.splice(1, 0, c, "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, c);
    }
    exports2.log = console.debug || console.log || (() => {
    });
    function save(namespaces) {
      try {
        if (namespaces) {
          exports2.storage.setItem("debug", namespaces);
        } else {
          exports2.storage.removeItem("debug");
        }
      } catch (error) {
      }
    }
    function load() {
      let r2;
      try {
        r2 = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG");
      } catch (error) {
      }
      if (!r2 && typeof process !== "undefined" && "env" in process) {
        r2 = process.env.DEBUG;
      }
      return r2;
    }
    function localstorage() {
      try {
        return localStorage;
      } catch (error) {
      }
    }
    module2.exports = require_common()(exports2);
    var { formatters } = module2.exports;
    formatters.j = function(v2) {
      try {
        return JSON.stringify(v2);
      } catch (error) {
        return "[UnexpectedJSONParseError]: " + error.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_process5.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_process5.default.platform === "win32") {
    const osRelease = import_node_os5.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 version3 = Number.parseInt((env2.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
    switch (env2.TERM_PROGRAM) {
      case "iTerm.app":
        return version3 >= 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_process5, import_node_os5, 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_process5 = __toESM(require("node:process"), 1);
    import_node_os5 = __toESM(require("node:os"), 1);
    import_node_tty2 = __toESM(require("node:tty"), 1);
    ({ env: env2 } = import_node_process5.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_node4 = __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 util6 = require("util");
    exports2.init = init2;
    exports2.log = log2;
    exports2.formatArgs = formatArgs;
    exports2.save = save;
    exports2.load = load;
    exports2.useColors = useColors;
    exports2.destroy = util6.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 (error) {
    }
    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, (_2, 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 c = this.color;
        const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
        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(util6.formatWithOptions(exports2.inspectOpts, ...args) + "\n");
    }
    function save(namespaces) {
      if (namespaces) {
        process.env.DEBUG = namespaces;
      } else {
        delete process.env.DEBUG;
      }
    }
    function load() {
      return process.env.DEBUG;
    }
    function init2(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(v2) {
      this.inspectOpts.colors = this.useColors;
      return util6.inspect(v2, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
    };
    formatters.O = function(v2) {
      this.inspectOpts.colors = this.useColors;
      return util6.inspect(v2, 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_node4();
    }
  }
});

// ../../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(url38) {
      var parsedUrl = typeof url38 === "string" ? parseUrl(url38) : url38 || {};
      var proto2 = parsedUrl.protocol;
      var hostname = parsedUrl.host;
      var port = parsedUrl.port;
      if (typeof hostname !== "string" || !hostname || typeof proto2 !== "string") {
        return "";
      }
      proto2 = proto2.split(":", 1)[0];
      hostname = hostname.replace(/:\d*$/, "");
      port = parseInt(port) || DEFAULT_PORTS[proto2] || 0;
      if (!shouldProxy(hostname, port)) {
        return "";
      }
      var proxy = getEnv("npm_config_" + proto2 + "_proxy") || getEnv(proto2 + "_proxy") || getEnv("npm_config_proxy") || getEnv("all_proxy");
      if (proxy && proxy.indexOf("://") === -1) {
        proxy = proto2 + "://" + proxy;
      }
      return proxy;
    }
    function shouldProxy(hostname, port) {
      var NO_PROXY = (getEnv("npm_config_no_proxy") || getEnv("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 hostname !== parsedProxyHostname;
        }
        if (parsedProxyHostname.charAt(0) === "*") {
          parsedProxyHostname = parsedProxyHostname.slice(1);
        }
        return !stringEndsWith.call(hostname, parsedProxyHostname);
      });
    }
    function getEnv(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_dist2 = __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, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    }) : function(o, v2) {
      o["default"] = v2;
    });
    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_dist();
    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 ? omit(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 hostname = req.getHeader("host") || "localhost";
        const base2 = `${protocol}//${hostname}`;
        const url38 = new url_1.URL(req.path, base2);
        if (opts.port !== 80) {
          url38.port = String(opts.port);
        }
        req.path = String(url38);
        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 omit(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((resolve6, 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 current2 = headers[key];
            if (typeof current2 === "string") {
              headers[key] = [current2, value];
            } else if (Array.isArray(current2)) {
              current2.push(value);
            } else {
              headers[key] = value;
            }
          }
          debug4("got proxy server response: %o %o", firstLine, headers);
          cleanup();
          resolve6({
            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_dist3 = __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, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    }) : function(o, v2) {
      o["default"] = v2;
    });
    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_dist();
    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 ? omit(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({
              ...omit(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 omit(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_utils = __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, offset2) {
      if (typeof value === "number") {
        if (!isFiniteInteger(value) || value < 0) {
          throw new Error(offset2 ? ERRORS.INVALID_OFFSET : ERRORS.INVALID_LENGTH);
        }
      } else {
        throw new Error(offset2 ? ERRORS.INVALID_OFFSET_NON_NUMBER : ERRORS.INVALID_LENGTH_NON_NUMBER);
      }
    }
    function checkLengthValue(length) {
      checkOffsetOrLengthValue(length, false);
    }
    exports2.checkLengthValue = checkLengthValue;
    function checkOffsetValue(offset2) {
      checkOffsetOrLengthValue(offset2, true);
    }
    exports2.checkOffsetValue = checkOffsetValue;
    function checkTargetOffset(offset2, buff) {
      if (offset2 < 0 || offset2 > 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_utils();
    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(offset2) {
        return this._readNumberValue(Buffer.prototype.readInt8, 1, offset2);
      }
      /**
       * 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(offset2) {
        return this._readNumberValue(Buffer.prototype.readInt16BE, 2, offset2);
      }
      /**
       * 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(offset2) {
        return this._readNumberValue(Buffer.prototype.readInt16LE, 2, offset2);
      }
      /**
       * 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(offset2) {
        return this._readNumberValue(Buffer.prototype.readInt32BE, 4, offset2);
      }
      /**
       * 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(offset2) {
        return this._readNumberValue(Buffer.prototype.readInt32LE, 4, offset2);
      }
      /**
       * 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(offset2) {
        utils_1.bigIntAndBufferInt64Check("readBigInt64BE");
        return this._readNumberValue(Buffer.prototype.readBigInt64BE, 8, offset2);
      }
      /**
       * 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(offset2) {
        utils_1.bigIntAndBufferInt64Check("readBigInt64LE");
        return this._readNumberValue(Buffer.prototype.readBigInt64LE, 8, offset2);
      }
      /**
       * 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, offset2) {
        this._writeNumberValue(Buffer.prototype.writeInt8, 1, value, offset2);
        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, offset2) {
        return this._insertNumberValue(Buffer.prototype.writeInt8, 1, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._writeNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._insertNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._writeNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._insertNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._writeNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._insertNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._writeNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._insertNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset2);
      }
      /**
       * 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, offset2) {
        utils_1.bigIntAndBufferInt64Check("writeBigInt64BE");
        return this._writeNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset2);
      }
      /**
       * 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, offset2) {
        utils_1.bigIntAndBufferInt64Check("writeBigInt64BE");
        return this._insertNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset2);
      }
      /**
       * 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, offset2) {
        utils_1.bigIntAndBufferInt64Check("writeBigInt64LE");
        return this._writeNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset2);
      }
      /**
       * 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, offset2) {
        utils_1.bigIntAndBufferInt64Check("writeBigInt64LE");
        return this._insertNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset2);
      }
      // 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(offset2) {
        return this._readNumberValue(Buffer.prototype.readUInt8, 1, offset2);
      }
      /**
       * 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(offset2) {
        return this._readNumberValue(Buffer.prototype.readUInt16BE, 2, offset2);
      }
      /**
       * 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(offset2) {
        return this._readNumberValue(Buffer.prototype.readUInt16LE, 2, offset2);
      }
      /**
       * 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(offset2) {
        return this._readNumberValue(Buffer.prototype.readUInt32BE, 4, offset2);
      }
      /**
       * 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(offset2) {
        return this._readNumberValue(Buffer.prototype.readUInt32LE, 4, offset2);
      }
      /**
       * 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(offset2) {
        utils_1.bigIntAndBufferInt64Check("readBigUInt64BE");
        return this._readNumberValue(Buffer.prototype.readBigUInt64BE, 8, offset2);
      }
      /**
       * 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(offset2) {
        utils_1.bigIntAndBufferInt64Check("readBigUInt64LE");
        return this._readNumberValue(Buffer.prototype.readBigUInt64LE, 8, offset2);
      }
      /**
       * 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, offset2) {
        return this._writeNumberValue(Buffer.prototype.writeUInt8, 1, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._insertNumberValue(Buffer.prototype.writeUInt8, 1, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._writeNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._insertNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._writeNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._insertNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._writeNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._insertNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._writeNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._insertNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset2);
      }
      /**
       * 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, offset2) {
        utils_1.bigIntAndBufferInt64Check("writeBigUInt64BE");
        return this._writeNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset2);
      }
      /**
       * 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, offset2) {
        utils_1.bigIntAndBufferInt64Check("writeBigUInt64BE");
        return this._insertNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset2);
      }
      /**
       * 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, offset2) {
        utils_1.bigIntAndBufferInt64Check("writeBigUInt64LE");
        return this._writeNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset2);
      }
      /**
       * 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, offset2) {
        utils_1.bigIntAndBufferInt64Check("writeBigUInt64LE");
        return this._insertNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset2);
      }
      // 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(offset2) {
        return this._readNumberValue(Buffer.prototype.readFloatBE, 4, offset2);
      }
      /**
       * 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(offset2) {
        return this._readNumberValue(Buffer.prototype.readFloatLE, 4, offset2);
      }
      /**
       * 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, offset2) {
        return this._writeNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._insertNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._writeNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._insertNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset2);
      }
      // 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(offset2) {
        return this._readNumberValue(Buffer.prototype.readDoubleBE, 8, offset2);
      }
      /**
       * 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(offset2) {
        return this._readNumberValue(Buffer.prototype.readDoubleLE, 8, offset2);
      }
      /**
       * 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, offset2) {
        return this._writeNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._insertNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._writeNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset2);
      }
      /**
       * 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, offset2) {
        return this._insertNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset2);
      }
      // 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, offset2, encoding) {
        utils_1.checkOffsetValue(offset2);
        return this._handleString(value, true, offset2, 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, offset2, encoding) {
        utils_1.checkOffsetValue(offset2);
        this.insertString(value, offset2, encoding);
        this.insertUInt8(0, offset2 + 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, offset2) {
        utils_1.checkOffsetValue(offset2);
        return this._handleBuffer(value, true, offset2);
      }
      /**
       * 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, offset2) {
        return this._handleBuffer(value, false, offset2);
      }
      /**
       * 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, offset2) {
        utils_1.checkOffsetValue(offset2);
        this.insertBuffer(value, offset2);
        this.insertUInt8(0, offset2 + 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, offset2) {
        if (typeof offset2 !== "undefined") {
          utils_1.checkOffsetValue(offset2);
        }
        this.writeBuffer(value, offset2);
        this.writeUInt8(0, typeof offset2 === "number" ? offset2 + 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(offset2) {
        utils_1.checkOffsetValue(offset2);
        utils_1.checkTargetOffset(offset2, this);
        this._readOffset = offset2;
      }
      /**
       * 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(offset2) {
        utils_1.checkOffsetValue(offset2);
        utils_1.checkTargetOffset(offset2, this);
        this._writeOffset = offset2;
      }
      /**
       * 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, offset2) {
        const offsetVal = typeof offset2 === "number" ? offset2 : 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 offset2 === "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, offset2) {
        let offsetVal = this._readOffset;
        if (typeof offset2 !== "undefined") {
          utils_1.checkOffsetValue(offset2);
          offsetVal = offset2;
        }
        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, offset2) {
        utils_1.checkOffsetValue(offset2);
        this._ensureCapacity(this.length + dataLength);
        if (offset2 < this.length) {
          this._buff.copy(this._buff, offset2 + dataLength, offset2, this._buff.length);
        }
        if (offset2 + dataLength > this.length) {
          this.length = offset2 + 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, offset2) {
        const offsetVal = typeof offset2 === "number" ? offset2 : 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 data2 = this._buff;
          let newLength = oldLength * 3 / 2 + 1;
          if (newLength < minLength) {
            newLength = minLength;
          }
          this._buff = Buffer.allocUnsafe(newLength);
          data2.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, offset2) {
        this.ensureReadable(byteSize, offset2);
        const value = func.call(this._buff, typeof offset2 === "number" ? offset2 : this._readOffset);
        if (typeof offset2 === "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, offset2) {
        utils_1.checkOffsetValue(offset2);
        this.ensureInsertable(byteSize, offset2);
        func.call(this._buff, value, offset2);
        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, offset2) {
        if (typeof offset2 === "number") {
          if (offset2 < 0) {
            throw new Error(utils_1.ERRORS.INVALID_WRITE_BEYOND_BOUNDS);
          }
          utils_1.checkOffsetValue(offset2);
        }
        const offsetVal = typeof offset2 === "number" ? offset2 : this._writeOffset;
        this._ensureWriteable(byteSize, offsetVal);
        func.call(this._buff, value, offsetVal);
        if (typeof offset2 === "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(array) {
      for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[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, c) {
        if (a != null)
          if ("number" == typeof a) this.fromNumber(a, b, c);
          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, x2, w2, j, c, n) {
        while (--n >= 0) {
          var v2 = x2 * this[i++] + w2[j] + c;
          c = Math.floor(v2 / 67108864);
          w2[j++] = v2 & 67108863;
        }
        return c;
      }
      function am2(i, x2, w2, j, c, n) {
        var xl = x2 & 32767, xh = x2 >> 15;
        while (--n >= 0) {
          var l = this[i] & 32767;
          var h2 = this[i++] >> 15;
          var m2 = xh * l + h2 * xl;
          l = xl * l + ((m2 & 32767) << 15) + w2[j] + (c & 1073741823);
          c = (l >>> 30) + (m2 >>> 15) + xh * h2 + (c >>> 30);
          w2[j++] = l & 1073741823;
        }
        return c;
      }
      function am3(i, x2, w2, j, c, n) {
        var xl = x2 & 16383, xh = x2 >> 14;
        while (--n >= 0) {
          var l = this[i] & 16383;
          var h2 = this[i++] >> 14;
          var m2 = xh * l + h2 * xl;
          l = xl * l + ((m2 & 16383) << 14) + w2[j] + c;
          c = (l >> 28) + (m2 >> 14) + xh * h2;
          w2[j++] = l & 268435455;
        }
        return c;
      }
      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 c = BI_RC[s.charCodeAt(i)];
        return c == null ? -1 : c;
      }
      function bnpCopyTo(r2) {
        for (var i = this.t - 1; i >= 0; --i) r2[i] = this[i];
        r2.t = this.t;
        r2.s = this.s;
      }
      function bnpFromInt(x2) {
        this.t = 1;
        this.s = x2 < 0 ? -1 : 0;
        if (x2 > 0) this[0] = x2;
        else if (x2 < -1) this[0] = x2 + this.DV;
        else this.t = 0;
      }
      function nbv(i) {
        var r2 = nbi();
        r2.fromInt(i);
        return r2;
      }
      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 x2 = k == 8 ? s[i] & 255 : intAt(s, i);
          if (x2 < 0) {
            if (s.charAt(i) == "-") mi = true;
            continue;
          }
          mi = false;
          if (sh == 0)
            this[this.t++] = x2;
          else if (sh + k > this.DB) {
            this[this.t - 1] |= (x2 & (1 << this.DB - sh) - 1) << sh;
            this[this.t++] = x2 >> this.DB - sh;
          } else
            this[this.t - 1] |= x2 << 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 c = this.s & this.DM;
        while (this.t > 0 && this[this.t - 1] == c) --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, d2, m2 = false, r2 = "", i = this.t;
        var p = this.DB - i * this.DB % k;
        if (i-- > 0) {
          if (p < this.DB && (d2 = this[i] >> p) > 0) {
            m2 = true;
            r2 = int2char(d2);
          }
          while (i >= 0) {
            if (p < k) {
              d2 = (this[i] & (1 << p) - 1) << k - p;
              d2 |= this[--i] >> (p += this.DB - k);
            } else {
              d2 = this[i] >> (p -= k) & km;
              if (p <= 0) {
                p += this.DB;
                --i;
              }
            }
            if (d2 > 0) m2 = true;
            if (m2) r2 += int2char(d2);
          }
        }
        return m2 ? r2 : "0";
      }
      function bnNegate() {
        var r2 = nbi();
        BigInteger.ZERO.subTo(this, r2);
        return r2;
      }
      function bnAbs() {
        return this.s < 0 ? this.negate() : this;
      }
      function bnCompareTo(a) {
        var r2 = this.s - a.s;
        if (r2 != 0) return r2;
        var i = this.t;
        r2 = i - a.t;
        if (r2 != 0) return this.s < 0 ? -r2 : r2;
        while (--i >= 0) if ((r2 = this[i] - a[i]) != 0) return r2;
        return 0;
      }
      function nbits(x2) {
        var r2 = 1, t2;
        if ((t2 = x2 >>> 16) != 0) {
          x2 = t2;
          r2 += 16;
        }
        if ((t2 = x2 >> 8) != 0) {
          x2 = t2;
          r2 += 8;
        }
        if ((t2 = x2 >> 4) != 0) {
          x2 = t2;
          r2 += 4;
        }
        if ((t2 = x2 >> 2) != 0) {
          x2 = t2;
          r2 += 2;
        }
        if ((t2 = x2 >> 1) != 0) {
          x2 = t2;
          r2 += 1;
        }
        return r2;
      }
      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, r2) {
        var i;
        for (i = this.t - 1; i >= 0; --i) r2[i + n] = this[i];
        for (i = n - 1; i >= 0; --i) r2[i] = 0;
        r2.t = this.t + n;
        r2.s = this.s;
      }
      function bnpDRShiftTo(n, r2) {
        for (var i = n; i < this.t; ++i) r2[i - n] = this[i];
        r2.t = Math.max(this.t - n, 0);
        r2.s = this.s;
      }
      function bnpLShiftTo(n, r2) {
        var bs = n % this.DB;
        var cbs = this.DB - bs;
        var bm = (1 << cbs) - 1;
        var ds = Math.floor(n / this.DB), c = this.s << bs & this.DM, i;
        for (i = this.t - 1; i >= 0; --i) {
          r2[i + ds + 1] = this[i] >> cbs | c;
          c = (this[i] & bm) << bs;
        }
        for (i = ds - 1; i >= 0; --i) r2[i] = 0;
        r2[ds] = c;
        r2.t = this.t + ds + 1;
        r2.s = this.s;
        r2.clamp();
      }
      function bnpRShiftTo(n, r2) {
        r2.s = this.s;
        var ds = Math.floor(n / this.DB);
        if (ds >= this.t) {
          r2.t = 0;
          return;
        }
        var bs = n % this.DB;
        var cbs = this.DB - bs;
        var bm = (1 << bs) - 1;
        r2[0] = this[ds] >> bs;
        for (var i = ds + 1; i < this.t; ++i) {
          r2[i - ds - 1] |= (this[i] & bm) << cbs;
          r2[i - ds] = this[i] >> bs;
        }
        if (bs > 0) r2[this.t - ds - 1] |= (this.s & bm) << cbs;
        r2.t = this.t - ds;
        r2.clamp();
      }
      function bnpSubTo(a, r2) {
        var i = 0, c = 0, m2 = Math.min(a.t, this.t);
        while (i < m2) {
          c += this[i] - a[i];
          r2[i++] = c & this.DM;
          c >>= this.DB;
        }
        if (a.t < this.t) {
          c -= a.s;
          while (i < this.t) {
            c += this[i];
            r2[i++] = c & this.DM;
            c >>= this.DB;
          }
          c += this.s;
        } else {
          c += this.s;
          while (i < a.t) {
            c -= a[i];
            r2[i++] = c & this.DM;
            c >>= this.DB;
          }
          c -= a.s;
        }
        r2.s = c < 0 ? -1 : 0;
        if (c < -1) r2[i++] = this.DV + c;
        else if (c > 0) r2[i++] = c;
        r2.t = i;
        r2.clamp();
      }
      function bnpMultiplyTo(a, r2) {
        var x2 = this.abs(), y = a.abs();
        var i = x2.t;
        r2.t = i + y.t;
        while (--i >= 0) r2[i] = 0;
        for (i = 0; i < y.t; ++i) r2[i + x2.t] = x2.am(0, y[i], r2, i, 0, x2.t);
        r2.s = 0;
        r2.clamp();
        if (this.s != a.s) BigInteger.ZERO.subTo(r2, r2);
      }
      function bnpSquareTo(r2) {
        var x2 = this.abs();
        var i = r2.t = 2 * x2.t;
        while (--i >= 0) r2[i] = 0;
        for (i = 0; i < x2.t - 1; ++i) {
          var c = x2.am(i, x2[i], r2, 2 * i, 0, 1);
          if ((r2[i + x2.t] += x2.am(i + 1, 2 * x2[i], r2, 2 * i + 1, c, x2.t - i - 1)) >= x2.DV) {
            r2[i + x2.t] -= x2.DV;
            r2[i + x2.t + 1] = 1;
          }
        }
        if (r2.t > 0) r2[r2.t - 1] += x2.am(i, x2[i], r2, 2 * i, 0, 1);
        r2.s = 0;
        r2.clamp();
      }
      function bnpDivRemTo(m2, q2, r2) {
        var pm = m2.abs();
        if (pm.t <= 0) return;
        var pt = this.abs();
        if (pt.t < pm.t) {
          if (q2 != null) q2.fromInt(0);
          if (r2 != null) this.copyTo(r2);
          return;
        }
        if (r2 == null) r2 = nbi();
        var y = nbi(), ts = this.s, ms = m2.s;
        var nsh = this.DB - nbits(pm[pm.t - 1]);
        if (nsh > 0) {
          pm.lShiftTo(nsh, y);
          pt.lShiftTo(nsh, r2);
        } else {
          pm.copyTo(y);
          pt.copyTo(r2);
        }
        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 = r2.t, j = i - ys, t2 = q2 == null ? nbi() : q2;
        y.dlShiftTo(j, t2);
        if (r2.compareTo(t2) >= 0) {
          r2[r2.t++] = 1;
          r2.subTo(t2, r2);
        }
        BigInteger.ONE.dlShiftTo(ys, t2);
        t2.subTo(y, y);
        while (y.t < ys) y[y.t++] = 0;
        while (--j >= 0) {
          var qd = r2[--i] == y0 ? this.DM : Math.floor(r2[i] * d1 + (r2[i - 1] + e) * d2);
          if ((r2[i] += y.am(0, qd, r2, j, 0, ys)) < qd) {
            y.dlShiftTo(j, t2);
            r2.subTo(t2, r2);
            while (r2[i] < --qd) r2.subTo(t2, r2);
          }
        }
        if (q2 != null) {
          r2.drShiftTo(ys, q2);
          if (ts != ms) BigInteger.ZERO.subTo(q2, q2);
        }
        r2.t = ys;
        r2.clamp();
        if (nsh > 0) r2.rShiftTo(nsh, r2);
        if (ts < 0) BigInteger.ZERO.subTo(r2, r2);
      }
      function bnMod(a) {
        var r2 = nbi();
        this.abs().divRemTo(a, null, r2);
        if (this.s < 0 && r2.compareTo(BigInteger.ZERO) > 0) a.subTo(r2, r2);
        return r2;
      }
      function Classic(m2) {
        this.m = m2;
      }
      function cConvert(x2) {
        if (x2.s < 0 || x2.compareTo(this.m) >= 0) return x2.mod(this.m);
        else return x2;
      }
      function cRevert(x2) {
        return x2;
      }
      function cReduce(x2) {
        x2.divRemTo(this.m, null, x2);
      }
      function cMulTo(x2, y, r2) {
        x2.multiplyTo(y, r2);
        this.reduce(r2);
      }
      function cSqrTo(x2, r2) {
        x2.squareTo(r2);
        this.reduce(r2);
      }
      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 x2 = this[0];
        if ((x2 & 1) == 0) return 0;
        var y = x2 & 3;
        y = y * (2 - (x2 & 15) * y) & 15;
        y = y * (2 - (x2 & 255) * y) & 255;
        y = y * (2 - ((x2 & 65535) * y & 65535)) & 65535;
        y = y * (2 - x2 * y % this.DV) % this.DV;
        return y > 0 ? this.DV - y : -y;
      }
      function Montgomery(m2) {
        this.m = m2;
        this.mp = m2.invDigit();
        this.mpl = this.mp & 32767;
        this.mph = this.mp >> 15;
        this.um = (1 << m2.DB - 15) - 1;
        this.mt2 = 2 * m2.t;
      }
      function montConvert(x2) {
        var r2 = nbi();
        x2.abs().dlShiftTo(this.m.t, r2);
        r2.divRemTo(this.m, null, r2);
        if (x2.s < 0 && r2.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r2, r2);
        return r2;
      }
      function montRevert(x2) {
        var r2 = nbi();
        x2.copyTo(r2);
        this.reduce(r2);
        return r2;
      }
      function montReduce(x2) {
        while (x2.t <= this.mt2)
          x2[x2.t++] = 0;
        for (var i = 0; i < this.m.t; ++i) {
          var j = x2[i] & 32767;
          var u0 = j * this.mpl + ((j * this.mph + (x2[i] >> 15) * this.mpl & this.um) << 15) & x2.DM;
          j = i + this.m.t;
          x2[j] += this.m.am(0, u0, x2, i, 0, this.m.t);
          while (x2[j] >= x2.DV) {
            x2[j] -= x2.DV;
            x2[++j]++;
          }
        }
        x2.clamp();
        x2.drShiftTo(this.m.t, x2);
        if (x2.compareTo(this.m) >= 0) x2.subTo(this.m, x2);
      }
      function montSqrTo(x2, r2) {
        x2.squareTo(r2);
        this.reduce(r2);
      }
      function montMulTo(x2, y, r2) {
        x2.multiplyTo(y, r2);
        this.reduce(r2);
      }
      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, z3) {
        if (e > 4294967295 || e < 1) return BigInteger.ONE;
        var r2 = nbi(), r22 = nbi(), g = z3.convert(this), i = nbits(e) - 1;
        g.copyTo(r2);
        while (--i >= 0) {
          z3.sqrTo(r2, r22);
          if ((e & 1 << i) > 0) z3.mulTo(r22, g, r2);
          else {
            var t2 = r2;
            r2 = r22;
            r22 = t2;
          }
        }
        return z3.revert(r2);
      }
      function bnModPowInt(e, m2) {
        var z3;
        if (e < 256 || m2.isEven()) z3 = new Classic(m2);
        else z3 = new Montgomery(m2);
        return this.exp(e, z3);
      }
      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 r2 = nbi();
        this.copyTo(r2);
        return r2;
      }
      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(r2) {
        return Math.floor(Math.LN2 * this.DB / Math.log(r2));
      }
      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 d2 = nbv(a), y = nbi(), z3 = nbi(), r2 = "";
        this.divRemTo(d2, y, z3);
        while (y.signum() > 0) {
          r2 = (a + z3.intValue()).toString(b).substr(1) + r2;
          y.divRemTo(d2, y, z3);
        }
        return z3.intValue().toString(b) + r2;
      }
      function bnpFromRadix(s, b) {
        this.fromInt(0);
        if (b == null) b = 10;
        var cs = this.chunkSize(b);
        var d2 = Math.pow(b, cs), mi = false, j = 0, w2 = 0;
        for (var i = 0; i < s.length; ++i) {
          var x2 = intAt(s, i);
          if (x2 < 0) {
            if (s.charAt(i) == "-" && this.signum() == 0) mi = true;
            continue;
          }
          w2 = b * w2 + x2;
          if (++j >= cs) {
            this.dMultiply(d2);
            this.dAddOffset(w2, 0);
            j = 0;
            w2 = 0;
          }
        }
        if (j > 0) {
          this.dMultiply(Math.pow(b, j));
          this.dAddOffset(w2, 0);
        }
        if (mi) BigInteger.ZERO.subTo(this, this);
      }
      function bnpFromNumber(a, b, c) {
        if ("number" == typeof b) {
          if (a < 2) this.fromInt(1);
          else {
            this.fromNumber(a, c);
            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 x2 = new Array(), t2 = a & 7;
          x2.length = (a >> 3) + 1;
          b.nextBytes(x2);
          if (t2 > 0) x2[0] &= (1 << t2) - 1;
          else x2[0] = 0;
          this.fromString(x2, 256);
        }
      }
      function bnToByteArray() {
        var i = this.t, r2 = new Array();
        r2[0] = this.s;
        var p = this.DB - i * this.DB % 8, d2, k = 0;
        if (i-- > 0) {
          if (p < this.DB && (d2 = this[i] >> p) != (this.s & this.DM) >> p)
            r2[k++] = d2 | this.s << this.DB - p;
          while (i >= 0) {
            if (p < 8) {
              d2 = (this[i] & (1 << p) - 1) << 8 - p;
              d2 |= this[--i] >> (p += this.DB - 8);
            } else {
              d2 = this[i] >> (p -= 8) & 255;
              if (p <= 0) {
                p += this.DB;
                --i;
              }
            }
            if ((d2 & 128) != 0) d2 |= -256;
            if (k == 0 && (this.s & 128) != (d2 & 128)) ++k;
            if (k > 0 || d2 != this.s) r2[k++] = d2;
          }
        }
        return r2;
      }
      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, r2) {
        var i, f, m2 = Math.min(a.t, this.t);
        for (i = 0; i < m2; ++i) r2[i] = op(this[i], a[i]);
        if (a.t < this.t) {
          f = a.s & this.DM;
          for (i = m2; i < this.t; ++i) r2[i] = op(this[i], f);
          r2.t = this.t;
        } else {
          f = this.s & this.DM;
          for (i = m2; i < a.t; ++i) r2[i] = op(f, a[i]);
          r2.t = a.t;
        }
        r2.s = op(this.s, a.s);
        r2.clamp();
      }
      function op_and(x2, y) {
        return x2 & y;
      }
      function bnAnd(a) {
        var r2 = nbi();
        this.bitwiseTo(a, op_and, r2);
        return r2;
      }
      function op_or(x2, y) {
        return x2 | y;
      }
      function bnOr(a) {
        var r2 = nbi();
        this.bitwiseTo(a, op_or, r2);
        return r2;
      }
      function op_xor(x2, y) {
        return x2 ^ y;
      }
      function bnXor(a) {
        var r2 = nbi();
        this.bitwiseTo(a, op_xor, r2);
        return r2;
      }
      function op_andnot(x2, y) {
        return x2 & ~y;
      }
      function bnAndNot(a) {
        var r2 = nbi();
        this.bitwiseTo(a, op_andnot, r2);
        return r2;
      }
      function bnNot() {
        var r2 = nbi();
        for (var i = 0; i < this.t; ++i) r2[i] = this.DM & ~this[i];
        r2.t = this.t;
        r2.s = ~this.s;
        return r2;
      }
      function bnShiftLeft(n) {
        var r2 = nbi();
        if (n < 0) this.rShiftTo(-n, r2);
        else this.lShiftTo(n, r2);
        return r2;
      }
      function bnShiftRight(n) {
        var r2 = nbi();
        if (n < 0) this.lShiftTo(-n, r2);
        else this.rShiftTo(n, r2);
        return r2;
      }
      function lbit(x2) {
        if (x2 == 0) return -1;
        var r2 = 0;
        if ((x2 & 65535) == 0) {
          x2 >>= 16;
          r2 += 16;
        }
        if ((x2 & 255) == 0) {
          x2 >>= 8;
          r2 += 8;
        }
        if ((x2 & 15) == 0) {
          x2 >>= 4;
          r2 += 4;
        }
        if ((x2 & 3) == 0) {
          x2 >>= 2;
          r2 += 2;
        }
        if ((x2 & 1) == 0) ++r2;
        return r2;
      }
      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(x2) {
        var r2 = 0;
        while (x2 != 0) {
          x2 &= x2 - 1;
          ++r2;
        }
        return r2;
      }
      function bnBitCount() {
        var r2 = 0, x2 = this.s & this.DM;
        for (var i = 0; i < this.t; ++i) r2 += cbit(this[i] ^ x2);
        return r2;
      }
      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 r2 = BigInteger.ONE.shiftLeft(n);
        this.bitwiseTo(r2, op, r2);
        return r2;
      }
      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, r2) {
        var i = 0, c = 0, m2 = Math.min(a.t, this.t);
        while (i < m2) {
          c += this[i] + a[i];
          r2[i++] = c & this.DM;
          c >>= this.DB;
        }
        if (a.t < this.t) {
          c += a.s;
          while (i < this.t) {
            c += this[i];
            r2[i++] = c & this.DM;
            c >>= this.DB;
          }
          c += this.s;
        } else {
          c += this.s;
          while (i < a.t) {
            c += a[i];
            r2[i++] = c & this.DM;
            c >>= this.DB;
          }
          c += a.s;
        }
        r2.s = c < 0 ? -1 : 0;
        if (c > 0) r2[i++] = c;
        else if (c < -1) r2[i++] = this.DV + c;
        r2.t = i;
        r2.clamp();
      }
      function bnAdd(a) {
        var r2 = nbi();
        this.addTo(a, r2);
        return r2;
      }
      function bnSubtract(a) {
        var r2 = nbi();
        this.subTo(a, r2);
        return r2;
      }
      function bnMultiply(a) {
        var r2 = nbi();
        this.multiplyTo(a, r2);
        return r2;
      }
      function bnSquare() {
        var r2 = nbi();
        this.squareTo(r2);
        return r2;
      }
      function bnDivide(a) {
        var r2 = nbi();
        this.divRemTo(a, r2, null);
        return r2;
      }
      function bnRemainder(a) {
        var r2 = nbi();
        this.divRemTo(a, null, r2);
        return r2;
      }
      function bnDivideAndRemainder(a) {
        var q2 = nbi(), r2 = nbi();
        this.divRemTo(a, q2, r2);
        return new Array(q2, r2);
      }
      function bnpDMultiply(n) {
        this[this.t] = this.am(0, n - 1, this, 0, 0, this.t);
        ++this.t;
        this.clamp();
      }
      function bnpDAddOffset(n, w2) {
        if (n == 0) return;
        while (this.t <= w2) this[this.t++] = 0;
        this[w2] += n;
        while (this[w2] >= this.DV) {
          this[w2] -= this.DV;
          if (++w2 >= this.t) this[this.t++] = 0;
          ++this[w2];
        }
      }
      function NullExp() {
      }
      function nNop(x2) {
        return x2;
      }
      function nMulTo(x2, y, r2) {
        x2.multiplyTo(y, r2);
      }
      function nSqrTo(x2, r2) {
        x2.squareTo(r2);
      }
      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, r2) {
        var i = Math.min(this.t + a.t, n);
        r2.s = 0;
        r2.t = i;
        while (i > 0) r2[--i] = 0;
        var j;
        for (j = r2.t - this.t; i < j; ++i) r2[i + this.t] = this.am(0, a[i], r2, i, 0, this.t);
        for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r2, i, 0, n - i);
        r2.clamp();
      }
      function bnpMultiplyUpperTo(a, n, r2) {
        --n;
        var i = r2.t = this.t + a.t - n;
        r2.s = 0;
        while (--i >= 0) r2[i] = 0;
        for (i = Math.max(n - this.t, 0); i < a.t; ++i)
          r2[this.t + i - n] = this.am(n - i, a[i], r2, 0, 0, this.t + i - n);
        r2.clamp();
        r2.drShiftTo(1, r2);
      }
      function Barrett(m2) {
        this.r2 = nbi();
        this.q3 = nbi();
        BigInteger.ONE.dlShiftTo(2 * m2.t, this.r2);
        this.mu = this.r2.divide(m2);
        this.m = m2;
      }
      function barrettConvert(x2) {
        if (x2.s < 0 || x2.t > 2 * this.m.t) return x2.mod(this.m);
        else if (x2.compareTo(this.m) < 0) return x2;
        else {
          var r2 = nbi();
          x2.copyTo(r2);
          this.reduce(r2);
          return r2;
        }
      }
      function barrettRevert(x2) {
        return x2;
      }
      function barrettReduce(x2) {
        x2.drShiftTo(this.m.t - 1, this.r2);
        if (x2.t > this.m.t + 1) {
          x2.t = this.m.t + 1;
          x2.clamp();
        }
        this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
        this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
        while (x2.compareTo(this.r2) < 0) x2.dAddOffset(1, this.m.t + 1);
        x2.subTo(this.r2, x2);
        while (x2.compareTo(this.m) >= 0) x2.subTo(this.m, x2);
      }
      function barrettSqrTo(x2, r2) {
        x2.squareTo(r2);
        this.reduce(r2);
      }
      function barrettMulTo(x2, y, r2) {
        x2.multiplyTo(y, r2);
        this.reduce(r2);
      }
      Barrett.prototype.convert = barrettConvert;
      Barrett.prototype.revert = barrettRevert;
      Barrett.prototype.reduce = barrettReduce;
      Barrett.prototype.mulTo = barrettMulTo;
      Barrett.prototype.sqrTo = barrettSqrTo;
      function bnModPow(e, m2) {
        var i = e.bitLength(), k, r2 = nbv(1), z3;
        if (i <= 0) return r2;
        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)
          z3 = new Classic(m2);
        else if (m2.isEven())
          z3 = new Barrett(m2);
        else
          z3 = new Montgomery(m2);
        var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1;
        g[1] = z3.convert(this);
        if (k > 1) {
          var g2 = nbi();
          z3.sqrTo(g[1], g2);
          while (n <= km) {
            g[n] = nbi();
            z3.mulTo(g2, g[n - 2], g[n]);
            n += 2;
          }
        }
        var j = e.t - 1, w2, is1 = true, r22 = nbi(), t2;
        i = nbits(e[j]) - 1;
        while (j >= 0) {
          if (i >= k1) w2 = e[j] >> i - k1 & km;
          else {
            w2 = (e[j] & (1 << i + 1) - 1) << k1 - i;
            if (j > 0) w2 |= e[j - 1] >> this.DB + i - k1;
          }
          n = k;
          while ((w2 & 1) == 0) {
            w2 >>= 1;
            --n;
          }
          if ((i -= n) < 0) {
            i += this.DB;
            --j;
          }
          if (is1) {
            g[w2].copyTo(r2);
            is1 = false;
          } else {
            while (n > 1) {
              z3.sqrTo(r2, r22);
              z3.sqrTo(r22, r2);
              n -= 2;
            }
            if (n > 0) z3.sqrTo(r2, r22);
            else {
              t2 = r2;
              r2 = r22;
              r22 = t2;
            }
            z3.mulTo(r22, g[w2], r2);
          }
          while (j >= 0 && (e[j] & 1 << i) == 0) {
            z3.sqrTo(r2, r22);
            t2 = r2;
            r2 = r22;
            r22 = t2;
            if (--i < 0) {
              i = this.DB - 1;
              --j;
            }
          }
        }
        return z3.revert(r2);
      }
      function bnGCD(a) {
        var x2 = this.s < 0 ? this.negate() : this.clone();
        var y = a.s < 0 ? a.negate() : a.clone();
        if (x2.compareTo(y) < 0) {
          var t2 = x2;
          x2 = y;
          y = t2;
        }
        var i = x2.getLowestSetBit(), g = y.getLowestSetBit();
        if (g < 0) return x2;
        if (i < g) g = i;
        if (g > 0) {
          x2.rShiftTo(g, x2);
          y.rShiftTo(g, y);
        }
        while (x2.signum() > 0) {
          if ((i = x2.getLowestSetBit()) > 0) x2.rShiftTo(i, x2);
          if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y);
          if (x2.compareTo(y) >= 0) {
            x2.subTo(y, x2);
            x2.rShiftTo(1, x2);
          } else {
            y.subTo(x2, y);
            y.rShiftTo(1, y);
          }
        }
        if (g > 0) y.lShiftTo(g, y);
        return y;
      }
      function bnpModInt(n) {
        if (n <= 0) return 0;
        var d2 = this.DV % n, r2 = this.s < 0 ? n - 1 : 0;
        if (this.t > 0)
          if (d2 == 0) r2 = this[0] % n;
          else for (var i = this.t - 1; i >= 0; --i) r2 = (d2 * r2 + this[i]) % n;
        return r2;
      }
      function bnModInverse(m2) {
        var ac = m2.isEven();
        if (this.isEven() && ac || m2.signum() == 0) return BigInteger.ZERO;
        var u = m2.clone(), v2 = this.clone();
        var a = nbv(1), b = nbv(0), c = nbv(0), d2 = nbv(1);
        while (u.signum() != 0) {
          while (u.isEven()) {
            u.rShiftTo(1, u);
            if (ac) {
              if (!a.isEven() || !b.isEven()) {
                a.addTo(this, a);
                b.subTo(m2, b);
              }
              a.rShiftTo(1, a);
            } else if (!b.isEven()) b.subTo(m2, b);
            b.rShiftTo(1, b);
          }
          while (v2.isEven()) {
            v2.rShiftTo(1, v2);
            if (ac) {
              if (!c.isEven() || !d2.isEven()) {
                c.addTo(this, c);
                d2.subTo(m2, d2);
              }
              c.rShiftTo(1, c);
            } else if (!d2.isEven()) d2.subTo(m2, d2);
            d2.rShiftTo(1, d2);
          }
          if (u.compareTo(v2) >= 0) {
            u.subTo(v2, u);
            if (ac) a.subTo(c, a);
            b.subTo(d2, b);
          } else {
            v2.subTo(u, v2);
            if (ac) c.subTo(a, c);
            d2.subTo(b, d2);
          }
        }
        if (v2.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;
        if (d2.compareTo(m2) >= 0) return d2.subtract(m2);
        if (d2.signum() < 0) d2.addTo(m2, d2);
        else return d2;
        if (d2.signum() < 0) return d2.add(m2);
        else return d2;
      }
      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, x2 = this.abs();
        if (x2.t == 1 && x2[0] <= lowprimes[lowprimes.length - 1]) {
          for (i = 0; i < lowprimes.length; ++i)
            if (x2[0] == lowprimes[i]) return true;
          return false;
        }
        if (x2.isEven()) return false;
        i = 1;
        while (i < lowprimes.length) {
          var m2 = lowprimes[i], j = i + 1;
          while (j < lowprimes.length && m2 < lplim) m2 *= lowprimes[j++];
          m2 = x2.modInt(m2);
          while (i < j) if (m2 % lowprimes[i++] == 0) return false;
        }
        return x2.millerRabin(t2);
      }
      function bnpMillerRabin(t2) {
        var n1 = this.subtract(BigInteger.ONE);
        var k = n1.getLowestSetBit();
        if (k <= 0) return false;
        var r2 = 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(r2, 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(x2) {
        rng_pool[rng_pptr++] ^= x2 & 255;
        rng_pool[rng_pptr++] ^= x2 >> 8 & 255;
        rng_pool[rng_pptr++] ^= x2 >> 16 & 255;
        rng_pool[rng_pptr++] ^= x2 >> 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 z2 = window.crypto.random(32);
            for (t = 0; t < z2.length; ++t)
              rng_pool[rng_pptr++] = z2.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, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    }) : function(o, v2) {
      o["default"] = v2;
    });
    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 constants = __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 = constants.GROUPS;
        this.parsedAddress = [];
        this.parsedSubnet = "";
        this.subnet = "/32";
        this.subnetMask = 32;
        this.v4 = true;
        this.isCorrect = common.isCorrect(constants.BITS);
        this.isInSubnet = common.isInSubnet;
        this.address = address;
        const subnet = constants.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 > constants.BITS) {
            throw new address_error_1.AddressError("Invalid subnet mask.");
          }
          address = address.replace(constants.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(constants.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(hex) {
        const padded = hex.replace(/:/g, "").padStart(8, "0");
        const groups = [];
        let i;
        for (i = 0; i < 8; i += 2) {
          const h2 = padded.slice(i, i + 2);
          groups.push(parseInt(h2, 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(integer) {
        return _Address4.fromHex(integer.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 < constants.GROUPS; i += 2) {
          const hex = (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(hex, 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(constants.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(constants.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(constants.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(constants.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, offset2 = 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 + offset2, 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, offset2 = 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 + offset2, 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, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    }) : function(o, v2) {
      o["default"] = v2;
    });
    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, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    }) : function(o, v2) {
      o["default"] = v2;
    });
    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(number) {
      const r2 = /(\d+)(\d{3})/;
      while (r2.test(number)) {
        number = number.replace(r2, "$1,$2");
      }
      return number;
    }
    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 hex = bigInteger.toString(16).padStart(32, "0");
        const groups = [];
        let i;
        for (i = 0; i < constants6.GROUPS; i++) {
          groups.push(hex.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(url38) {
        let host;
        let port = null;
        let result;
        if (url38.indexOf("[") !== -1 && url38.indexOf("]:") !== -1) {
          result = constants6.RE_URL_WITH_PORT.exec(url38);
          if (result === null) {
            return {
              error: "failed to parse address with port",
              address: null,
              port: null
            };
          }
          host = result[1];
          port = result[2];
        } else if (url38.indexOf("/") !== -1) {
          url38 = url38.replace(/^[a-z0-9]+:\/\//, "");
          result = constants6.RE_URL.exec(url38);
          if (result === null) {
            return {
              error: "failed to parse address from URL",
              address: null,
              port: null
            };
          }
          host = result[1];
        } else {
          host = url38;
        }
        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, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    }) : function(o, v2) {
      o["default"] = v2;
    });
    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(int32) {
      const octet1 = int32 >>> 24 & 255;
      const octet2 = int32 >>> 16 & 255;
      const octet3 = int32 >>> 8 & 255;
      const octet4 = int32 & 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(data2) {
        if (!Buffer.isBuffer(data2)) {
          throw new Error("Attempted to append a non-buffer instance to ReceiveBuffer.");
        }
        if (this.offset + data2.length >= this.buffer.length) {
          const tmp = this.buffer;
          this.buffer = Buffer.allocUnsafe(Math.max(this.buffer.length + this.originalSize, this.buffer.length + data2.length));
          tmp.copy(this.buffer);
        }
        data2.copy(this.buffer, this.offset);
        return this.offset += data2.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(resolve6) {
          resolve6(value);
        });
      }
      return new (P || (P = Promise))(function(resolve6, 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 ? resolve6(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((resolve6, reject) => {
          try {
            (0, helpers_1.validateSocksClientOptions)(options, ["connect"]);
          } catch (err) {
            if (typeof callback === "function") {
              callback(err);
              return resolve6(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);
              resolve6(info);
            } else {
              resolve6(info);
            }
          });
          client.once("error", (err) => {
            client.removeAllListeners();
            if (typeof callback === "function") {
              callback(err);
              resolve6(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((resolve6, reject) => __awaiter2(this, void 0, void 0, function* () {
          try {
            (0, helpers_1.validateSocksClientChainOptions)(options);
          } catch (err) {
            if (typeof callback === "function") {
              callback(err);
              return resolve6(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 });
              resolve6({ socket: sock });
            } else {
              resolve6({ socket: sock });
            }
          } catch (err) {
            if (typeof callback === "function") {
              callback(err);
              resolve6(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(data2) {
        const buff = smart_buffer_1.SmartBuffer.fromBuffer(data2);
        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 = (data2) => this.onDataReceivedHandler(data2);
        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(data2) {
        this.receiveBuffer.append(data2);
        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 data2 = this.receiveBuffer.get(8);
        if (data2[1] !== constants_1.Socks4Response.Granted) {
          this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedConnection} - (${constants_1.Socks4Response[data2[1]]})`);
        } else {
          if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) {
            const buff = smart_buffer_1.SmartBuffer.fromBuffer(data2);
            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 data2 = this.receiveBuffer.get(8);
        if (data2[1] !== constants_1.Socks4Response.Granted) {
          this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${constants_1.Socks4Response[data2[1]]})`);
        } else {
          const buff = smart_buffer_1.SmartBuffer.fromBuffer(data2);
          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 data2 = this.receiveBuffer.get(2);
        if (data2[0] !== 5) {
          this.closeSocket(constants_1.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion);
        } else if (data2[1] === constants_1.SOCKS5_NO_ACCEPTABLE_AUTH) {
          this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType);
        } else {
          if (data2[1] === constants_1.Socks5Auth.NoAuth) {
            this.socks5ChosenAuthType = constants_1.Socks5Auth.NoAuth;
            this.sendSocks5CommandRequest();
          } else if (data2[1] === constants_1.Socks5Auth.UserPass) {
            this.socks5ChosenAuthType = constants_1.Socks5Auth.UserPass;
            this.sendSocks5UserPassAuthentication();
          } else if (data2[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(data2) {
        return __awaiter2(this, void 0, void 0, function* () {
          return yield this.options.proxy.custom_auth_response_handler(data2);
        });
      }
      handleSocks5AuthenticationNoAuthHandshakeResponse(data2) {
        return __awaiter2(this, void 0, void 0, function* () {
          return data2[1] === 0;
        });
      }
      handleSocks5AuthenticationUserPassHandshakeResponse(data2) {
        return __awaiter2(this, void 0, void 0, function* () {
          return data2[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, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __exportStar2 = exports2 && exports2.__exportStar || function(m2, exports3) {
      for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m2, p);
    };
    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_dist4 = __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, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    }) : function(o, v2) {
      o["default"] = v2;
    });
    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_dist();
    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(url38) {
      let lookup = false;
      let type = 5;
      const host = url38.hostname;
      const port = parseInt(url38.port, 10) || 1080;
      switch (url38.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(url38.protocol)}`);
      }
      const proxy = {
        host,
        port,
        type
      };
      if (url38.username) {
        Object.defineProperty(proxy, "userId", {
          value: decodeURIComponent(url38.username),
          enumerable: false
        });
      }
      if (url38.password != null) {
        Object.defineProperty(proxy, "password", {
          value: decodeURIComponent(url38.password),
          enumerable: false
        });
      }
      return { lookup, proxy };
    }
    var SocksProxyAgent = class extends agent_base_1.Agent {
      constructor(uri, opts) {
        super(opts);
        const url38 = typeof uri === "string" ? new url_1.URL(uri) : uri;
        const { proxy, lookup } = parseSocksURL(url38);
        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((resolve6, reject) => {
            lookupFn(host, {}, (err, res) => {
              if (err) {
                reject(err);
              } else {
                resolve6(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({
            ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"),
            socket
          });
          tlsSocket.once("error", (error) => {
            debug4("Socket TLS error", error.message);
            cleanup(tlsSocket);
          });
          return tlsSocket;
        }
        return socket;
      }
    };
    SocksProxyAgent.protocols = [
      "socks",
      "socks4",
      "socks4a",
      "socks5",
      "socks5h"
    ];
    exports2.SocksProxyAgent = SocksProxyAgent;
    function omit(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 meta = uri.substring(5, firstComma).split(";");
      let charset = "";
      let base64 = false;
      const type = meta[0] || "text/plain";
      let typeFull = type;
      for (let i = 1; i < meta.length; i++) {
        if (meta[i] === "base64") {
          base64 = true;
        } else if (meta[i]) {
          typeFull += `;${meta[i]}`;
          if (meta[i].indexOf("charset=") === 0) {
            charset = meta[i].substring(8);
          }
        }
      }
      if (!meta[0] && !charset.length) {
        typeFull += ";charset=US-ASCII";
        charset = "US-ASCII";
      }
      const data2 = unescape(uri.substring(firstComma + 1));
      const buffer = base64 ? convert.base64ToArrayBuffer(data2) : convert.stringToBuffer(data2);
      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_node5 = __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(base64) {
      return nodeBuffertoArrayBuffer(Buffer.from(base64, "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_node5();
    var notmodified_1 = __importDefault2(require_notmodified());
    var debug4 = (0, debug_1.default)("get-uri:data");
    var DataReadable = class extends stream_1.Readable {
      constructor(hash, buf) {
        super();
        this.push(buf);
        this.push(null);
        this.hash = hash;
      }
    };
    var data2 = async ({ href: uri }, { cache } = {}) => {
      const shasum = (0, crypto_1.createHash)("sha1");
      shasum.update(uri);
      const hash = shasum.digest("hex");
      debug4('generated SHA1 hash for "data:" URI: %o', hash);
      if (cache?.hash === hash) {
        debug4("got matching cache SHA1 hash: %o", hash);
        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(hash, Buffer.from(buffer));
      }
    };
    exports2.data = data2;
  }
});

// ../../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 file2 = 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 = file2;
    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", (data2) => this._onControlSocketData(data2));
          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", (error) => {
          error.message += ` (${identifier})`;
          this.closeWithError(error);
        });
        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 file2 = new FileInfo_1.FileInfo(name);
      const fileType = groups[3];
      if (fileType === "<DIR>") {
        file2.type = FileInfo_1.FileType.Directory;
        file2.size = 0;
      } else {
        file2.type = FileInfo_1.FileType.File;
        file2.size = parseInt(groups[4], 10);
      }
      file2.rawModifiedAt = groups[1] + " " + groups[2];
      return file2;
    }
    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 file2 = new FileInfo_1.FileInfo(name);
      file2.size = parseInt(groups[18], 10);
      file2.user = groups[16];
      file2.group = groups[17];
      file2.hardLinkCount = parseInt(groups[15], 10);
      file2.rawModifiedAt = groups[19] + " " + groups[20];
      file2.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":
          file2.type = FileInfo_1.FileType.Directory;
          break;
        case "e":
          file2.type = FileInfo_1.FileType.SymbolicLink;
          break;
        case "l":
          file2.type = FileInfo_1.FileType.SymbolicLink;
          break;
        case "b":
        case "c":
          file2.type = FileInfo_1.FileType.File;
          break;
        case "f":
        case "-":
          file2.type = FileInfo_1.FileType.File;
          break;
        default:
          file2.type = FileInfo_1.FileType.Unknown;
      }
      if (file2.isSymbolicLink) {
        const end = name.indexOf(" -> ");
        if (end !== -1) {
          file2.name = name.substring(0, end);
          file2.link = name.substring(end + 4);
        }
      }
      return file2;
    }
    exports2.parseLine = parseLine;
    function transformList(files) {
      return files;
    }
    exports2.transformList = transformList;
    function parseMode(r2, w2, x2) {
      let value = 0;
      if (r2 !== "-") {
        value += FileInfo_1.FileInfo.UnixPermission.Read;
      }
      if (w2 !== "-") {
        value += FileInfo_1.FileInfo.UnixPermission.Write;
      }
      const execToken = x2.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 file2 of files) {
        if (!file2.isSymbolicLink && file2.uniqueID !== void 0) {
          nonLinksByID.set(file2.uniqueID, file2);
        }
      }
      const resolvedFiles = [];
      for (const file2 of files) {
        if (file2.isSymbolicLink && file2.uniqueID !== void 0 && file2.link === void 0) {
          const target = nonLinksByID.get(file2.uniqueID);
          if (target !== void 0) {
            file2.link = target.name;
          }
        }
        const isPartOfDirectory = !file2.name.includes("/");
        if (isPartOfDirectory) {
          resolvedFiles.push(file2);
        }
      }
      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, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    }) : function(o, v2) {
      o["default"] = v2;
    });
    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, _2, 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((resolve6, 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");
            resolve6(tlsSocket);
          }
        }).once("error", (error) => {
          reject(error);
        });
      });
    }
    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((resolve6, 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;
          resolve6();
        });
      });
    }
    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, config) {
      const resolver = new TransferResolver(config.ftp, config.tracker);
      const fullCommand = `${config.command} ${config.remotePath}`;
      return config.ftp.handle(fullCommand, (res, task) => {
        if (res instanceof Error) {
          resolver.onError(task, res);
        } else if (res.code === 150 || res.code === 125) {
          const dataSocket = config.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", () => {
            config.ftp.log(`Uploading to ${(0, netUtils_1.describeAddress)(dataSocket)} (${(0, netUtils_1.describeTLS)(dataSocket)})`);
            resolver.onDataStart(config.remotePath, config.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, config) {
      if (!config.ftp.dataSocket) {
        throw new Error("Download will be initiated but no data connection is available.");
      }
      const resolver = new TransferResolver(config.ftp, config.tracker);
      return config.ftp.handle(config.command, (res, task) => {
        if (res instanceof Error) {
          resolver.onError(task, res);
        } else if (res.code === 150 || res.code === 125) {
          const dataSocket = config.ftp.dataSocket;
          if (!dataSocket) {
            resolver.onError(task, new Error("Download should begin but no data connection is available."));
            return;
          }
          config.ftp.log(`Downloading from ${(0, netUtils_1.describeAddress)(dataSocket)} (${(0, netUtils_1.describeTLS)(dataSocket)})`);
          resolver.onDataStart(config.remotePath, config.type);
          (0, stream_1.pipeline)(dataSocket, destination, (err) => {
            if (err) {
              resolver.onError(task, err);
            } else {
              resolver.onDataDone(task);
            }
          });
        } else if (res.code === 350) {
          config.ftp.send("RETR " + config.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 _a, _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 = (_a = options.secureOptions) !== null && _a !== void 0 ? _a : {};
          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(path62) {
        const validPath = await this.protectWhitespace(path62);
        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(path62) {
        const validPath = await this.protectWhitespace(path62);
        const res = await this.send(`MDTM ${validPath}`);
        const date = res.message.slice(4);
        return (0, parseListMLSD_1.parseMLSxDate)(date);
      }
      /**
       * Get the size of a file.
       */
      async size(path62) {
        const validPath = await this.protectWhitespace(path62);
        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(path62, ignoreErrorCodes = false) {
        const validPath = await this.protectWhitespace(path62);
        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(path62 = "") {
        const validPath = await this.protectWhitespace(path62);
        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 file2 of await this.list()) {
          if (file2.isDirectory) {
            await this.cd(file2.name);
            await this.clearWorkingDir();
            await this.cdup();
            await this.removeEmptyDir(file2.name);
          } else {
            await this.remove(file2.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 file2 of files) {
          const fullPath = (0, path_1.join)(localDirPath, file2);
          const stats = await fsStat(fullPath);
          if (stats.isFile()) {
            await this.uploadFrom(fullPath, file2);
          } else if (stats.isDirectory()) {
            await this._openDir(file2);
            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 file2 of await this.list()) {
          const localPath = (0, path_1.join)(localDirPath, file2.name);
          if (file2.isDirectory) {
            await this.cd(file2.name);
            await this._downloadFromWorkingDir(localPath);
            await this.cdup();
          } else if (file2.isFile) {
            await this.downloadTo(localPath, file2.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(path62) {
        const validPath = await this.protectWhitespace(path62);
        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(path62) {
        if (!path62.startsWith(" ")) {
          return path62;
        }
        const pwd = await this.pwd();
        const absolutePathPrefix = pwd.endsWith("/") ? pwd : pwd + "/";
        return absolutePathPrefix + path62;
      }
      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(path62) {
      try {
        await fsStat(path62);
      } catch (err) {
        await fsMkDir(path62, { 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_dist5 = __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, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __exportStar2 = exports2 && exports2.__exportStar || function(m2, exports3) {
      for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m2, p);
    };
    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_dist5();
    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 (url38, opts = {}) => {
      const { cache } = opts;
      const filepath = decodeURIComponent(url38.pathname);
      let lastModified;
      if (!filepath) {
        throw new TypeError('No "pathname"!');
      }
      const client = new basic_ftp_1.Client();
      try {
        const host = url38.hostname || url38.host || "localhost";
        const port = parseInt(url38.port || "0", 10) || 21;
        const user = url38.username ? decodeURIComponent(url38.username) : void 0;
        const password = url38.password ? decodeURIComponent(url38.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 (url38, opts = {}) => {
      debug4("GET %o", url38.href);
      const cache = getCache(url38, 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(url38, options);
      const [res] = await (0, events_1.once)(req, "response");
      const code = res.statusCode || 0;
      res.date = Date.now();
      res.parsed = url38;
      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, url38.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 !== url38.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(url38, cache) {
      if (cache) {
        if (cache.parsed && cache.parsed.href === url38.href) {
          return cache;
        }
        if (cache.redirects) {
          for (let i = 0; i < cache.redirects.length; i++) {
            const c = getCache(url38, cache.redirects[i]);
            if (c) {
              return c;
            }
          }
        }
      }
      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 = (url38, opts) => {
      return (0, http_1.http)(url38, { ...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_dist6 = __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(p) {
      return VALID_PROTOCOLS.has(p);
    }
    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 url38 = typeof uri === "string" ? new URL(uri) : uri;
      const protocol = url38.protocol.replace(/:$/, "");
      if (!isValidProtocol(protocol)) {
        throw new TypeError(`Unsupported protocol "${protocol}" specified in URI: "${uri}"`);
      }
      const getter = exports2.protocols[protocol];
      return getter(url38, 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 clone(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(array, func) {
        var diff, len, i, current2;
        len = array.length;
        i = 0;
        while (len) {
          diff = len >>> 1;
          current2 = i + diff;
          if (func(array[current2])) {
            len = diff;
          } else {
            i = current2 + 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, path62, wrap, ref2) {
        this.node = node;
        this.path = path62;
        this.wrap = wrap;
        this.ref = ref2;
      }
      function Controller() {
      }
      Controller.prototype.path = function path62() {
        var i, iz, j, jz, result, element;
        function addToPath(result2, path63) {
          if (Array.isArray(path63)) {
            for (j = 0, jz = path63.length; j < jz; ++j) {
              result2.push(path63[j]);
            }
          } else {
            result2.push(path63);
          }
        }
        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 current2() {
        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, current2, current22, 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 + ".");
              }
            }
            current2 = candidates.length;
            while ((current2 -= 1) >= 0) {
              key = candidates[current2];
              candidate = node[key];
              if (!candidate) {
                continue;
              }
              if (Array.isArray(candidate)) {
                current22 = candidate.length;
                while ((current22 -= 1) >= 0) {
                  if (!candidate[current22]) {
                    continue;
                  }
                  if (candidateExistsInLeaveList(leavelist, candidate[current22])) {
                    continue;
                  }
                  if (isProperty(nodeType, candidates[current2])) {
                    element = new Element(candidate[current22], [key, current22], "Property", null);
                  } else if (isNode(candidate[current22])) {
                    element = new Element(candidate[current22], [key, current22], 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, current2, current22, 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 + ".");
            }
          }
          current2 = candidates.length;
          while ((current2 -= 1) >= 0) {
            key = candidates[current2];
            candidate = node[key];
            if (!candidate) {
              continue;
            }
            if (Array.isArray(candidate)) {
              current22 = candidate.length;
              while ((current22 -= 1) >= 0) {
                if (!candidate[current22]) {
                  continue;
                }
                if (isProperty(nodeType, candidates[current2])) {
                  element = new Element(candidate[current22], [key, current22], "Property", new Reference(candidate, current22));
                } else if (isNode(candidate[current22])) {
                  element = new Element(candidate[current22], [key, current22], null, new Reference(candidate, current22));
                } 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 clone({});
      };
      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 current2;
        if (node.type !== "IfStatement") {
          return false;
        }
        if (node.alternate == null) {
          return false;
        }
        current2 = node.consequent;
        do {
          if (current2.type === "IfStatement") {
            if (current2.alternate == null) {
              return true;
            }
          }
          current2 = trailingStatement(current2);
        } while (current2);
        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 isDecimalDigit2(ch2) {
        return 48 <= ch2 && ch2 <= 57;
      }
      function isHexDigit2(ch2) {
        return 48 <= ch2 && ch2 <= 57 || // 0..9
        97 <= ch2 && ch2 <= 102 || // a..f
        65 <= ch2 && ch2 <= 70;
      }
      function isOctalDigit2(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 isWhiteSpace2(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: isDecimalDigit2,
        isHexDigit: isHexDigit2,
        isOctalDigit: isOctalDigit2,
        isWhiteSpace: isWhiteSpace2,
        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, check;
        if (id.length === 0) {
          return false;
        }
        check = 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 (!check(ch)) {
            return false;
          }
          check = 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_utils2 = __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_base64 = __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(number) {
      if (0 <= number && number < intToCharMap.length) {
        return intToCharMap[number];
      }
      throw new TypeError("Must be between 0 and 63: " + number);
    };
    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 base64 = require_base64();
    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 += base64.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 = base64.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 url38 = "";
      if (aParsedUrl.scheme) {
        url38 += aParsedUrl.scheme + ":";
      }
      url38 += "//";
      if (aParsedUrl.auth) {
        url38 += aParsedUrl.auth + "@";
      }
      if (aParsedUrl.host) {
        url38 += aParsedUrl.host;
      }
      if (aParsedUrl.port) {
        url38 += ":" + aParsedUrl.port;
      }
      if (aParsedUrl.path) {
        url38 += aParsedUrl.path;
      }
      return url38;
    }
    exports2.urlGenerate = urlGenerate;
    function normalize2(aPath) {
      var path62 = aPath;
      var url38 = urlParse(aPath);
      if (url38) {
        if (!url38.path) {
          return aPath;
        }
        path62 = url38.path;
      }
      var isAbsolute5 = exports2.isAbsolute(path62);
      var parts = path62.split(/\/+/);
      for (var part, up2 = 0, i = parts.length - 1; i >= 0; i--) {
        part = parts[i];
        if (part === ".") {
          parts.splice(i, 1);
        } else if (part === "..") {
          up2++;
        } else if (up2 > 0) {
          if (part === "") {
            parts.splice(i + 1, up2);
            up2 = 0;
          } else {
            parts.splice(i, 2);
            up2--;
          }
        }
      }
      path62 = parts.join("/");
      if (path62 === "") {
        path62 = isAbsolute5 ? "/" : ".";
      }
      if (url38) {
        url38.path = path62;
        return urlGenerate(url38);
      }
      return path62;
    }
    exports2.normalize = normalize2;
    function join6(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 = join6;
    exports2.isAbsolute = function(aPath) {
      return aPath.charAt(0) === "/" || urlRegexp.test(aPath);
    };
    function relative4(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 = relative4;
    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 = join6(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 util6 = 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 set = new ArraySet();
      for (var i = 0, len = aArray.length; i < len; i++) {
        set.add(aArray[i], aAllowDuplicates);
      }
      return set;
    };
    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 : util6.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 = util6.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 = util6.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 util6 = 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 || util6.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(util6.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 util6 = require_util2();
    var ArraySet = require_array_set().ArraySet;
    var MappingList = require_mapping_list().MappingList;
    function SourceMapGenerator(aArgs) {
      if (!aArgs) {
        aArgs = {};
      }
      this._file = util6.getArg(aArgs, "file", null);
      this._sourceRoot = util6.getArg(aArgs, "sourceRoot", null);
      this._skipValidation = util6.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 = util6.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 = util6.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 = util6.getArg(aArgs, "generated");
      var original = util6.getArg(aArgs, "original", null);
      var source = util6.getArg(aArgs, "source", null);
      var name = util6.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 = util6.relative(this._sourceRoot, source);
      }
      if (aSourceContent != null) {
        if (!this._sourcesContents) {
          this._sourcesContents = /* @__PURE__ */ Object.create(null);
        }
        this._sourcesContents[util6.toSetString(source)] = aSourceContent;
      } else if (this._sourcesContents) {
        delete this._sourcesContents[util6.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 = util6.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 = util6.join(aSourceMapPath, mapping.source);
            }
            if (sourceRoot != null) {
              mapping.source = util6.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 = util6.join(aSourceMapPath, sourceFile2);
          }
          if (sourceRoot != null) {
            sourceFile2 = util6.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 (!util6.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 = util6.relative(aSourceRoot, source);
        }
        var key = util6.toSetString(source);
        return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null;
      }, this);
    };
    SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() {
      var map = {
        version: this._version,
        sources: this._sources.toArray(),
        names: this._names.toArray(),
        mappings: this._serializeMappings()
      };
      if (this._file != null) {
        map.file = this._file;
      }
      if (this._sourceRoot != null) {
        map.sourceRoot = this._sourceRoot;
      }
      if (this._sourcesContents) {
        map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
      }
      return map;
    };
    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, x2, y) {
      var temp = ary[x2];
      ary[x2] = ary[y];
      ary[y] = temp;
    }
    function randomIntInRange(low, high) {
      return Math.round(low + Math.random() * (high - low));
    }
    function doQuickSort(ary, comparator, p, r2) {
      if (p < r2) {
        var pivotIndex = randomIntInRange(p, r2);
        var i = p - 1;
        swap(ary, pivotIndex, r2);
        var pivot = ary[r2];
        for (var j = p; j < r2; 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, p, q2 - 1);
        doQuickSort(ary, comparator, q2 + 1, r2);
      }
    }
    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 util6 = 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 = util6.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 c = aStr.charAt(index);
      return c === ";" || c === ",";
    };
    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 = util6.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 = util6.getArg(aArgs, "line");
      var needle = {
        source: util6.getArg(aArgs, "source"),
        originalLine: line,
        originalColumn: util6.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",
        util6.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: util6.getArg(mapping, "generatedLine", null),
              column: util6.getArg(mapping, "generatedColumn", null),
              lastColumn: util6.getArg(mapping, "lastGeneratedColumn", null)
            });
            mapping = this._originalMappings[++index];
          }
        } else {
          var originalColumn = mapping.originalColumn;
          while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) {
            mappings.push({
              line: util6.getArg(mapping, "generatedLine", null),
              column: util6.getArg(mapping, "generatedColumn", null),
              lastColumn: util6.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 = util6.parseSourceMapInput(aSourceMap);
      }
      var version3 = util6.getArg(sourceMap, "version");
      var sources = util6.getArg(sourceMap, "sources");
      var names = util6.getArg(sourceMap, "names", []);
      var sourceRoot = util6.getArg(sourceMap, "sourceRoot", null);
      var sourcesContent = util6.getArg(sourceMap, "sourcesContent", null);
      var mappings = util6.getArg(sourceMap, "mappings");
      var file2 = util6.getArg(sourceMap, "file", null);
      if (version3 != this._version) {
        throw new Error("Unsupported version: " + version3);
      }
      if (sourceRoot) {
        sourceRoot = util6.normalize(sourceRoot);
      }
      sources = sources.map(String).map(util6.normalize).map(function(source) {
        return sourceRoot && util6.isAbsolute(sourceRoot) && util6.isAbsolute(source) ? util6.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 util6.computeSourceURL(sourceRoot, s, aSourceMapURL);
      });
      this.sourceRoot = sourceRoot;
      this.sourcesContent = sourcesContent;
      this._mappings = mappings;
      this._sourceMapURL = aSourceMapURL;
      this.file = file2;
    }
    BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
    BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
    BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
      var relativeSource = aSource;
      if (this.sourceRoot != null) {
        relativeSource = util6.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 util6.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, util6.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, util6.compareByGeneratedPositionsDeflated);
      this.__generatedMappings = generatedMappings;
      quickSort(originalMappings, util6.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: util6.getArg(aArgs, "line"),
        generatedColumn: util6.getArg(aArgs, "column")
      };
      var index = this._findMapping(
        needle,
        this._generatedMappings,
        "generatedLine",
        "generatedColumn",
        util6.compareByGeneratedPositionsDeflated,
        util6.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND)
      );
      if (index >= 0) {
        var mapping = this._generatedMappings[index];
        if (mapping.generatedLine === needle.generatedLine) {
          var source = util6.getArg(mapping, "source", null);
          if (source !== null) {
            source = this._sources.at(source);
            source = util6.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
          }
          var name = util6.getArg(mapping, "name", null);
          if (name !== null) {
            name = this._names.at(name);
          }
          return {
            source,
            line: util6.getArg(mapping, "originalLine", null),
            column: util6.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 = util6.relative(this.sourceRoot, relativeSource);
      }
      var url38;
      if (this.sourceRoot != null && (url38 = util6.urlParse(this.sourceRoot))) {
        var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
        if (url38.scheme == "file" && this._sources.has(fileUriAbsPath)) {
          return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
        }
        if ((!url38.path || url38.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 = util6.getArg(aArgs, "source");
      source = this._findSourceIndex(source);
      if (source < 0) {
        return {
          line: null,
          column: null,
          lastColumn: null
        };
      }
      var needle = {
        source,
        originalLine: util6.getArg(aArgs, "line"),
        originalColumn: util6.getArg(aArgs, "column")
      };
      var index = this._findMapping(
        needle,
        this._originalMappings,
        "originalLine",
        "originalColumn",
        util6.compareByOriginalPositions,
        util6.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND)
      );
      if (index >= 0) {
        var mapping = this._originalMappings[index];
        if (mapping.source === needle.source) {
          return {
            line: util6.getArg(mapping, "generatedLine", null),
            column: util6.getArg(mapping, "generatedColumn", null),
            lastColumn: util6.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 = util6.parseSourceMapInput(aSourceMap);
      }
      var version3 = util6.getArg(sourceMap, "version");
      var sections = util6.getArg(sourceMap, "sections");
      if (version3 != this._version) {
        throw new Error("Unsupported version: " + version3);
      }
      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 offset2 = util6.getArg(s, "offset");
        var offsetLine = util6.getArg(offset2, "line");
        var offsetColumn = util6.getArg(offset2, "column");
        if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) {
          throw new Error("Section offsets must be ordered and non-overlapping.");
        }
        lastOffset = offset2;
        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(util6.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: util6.getArg(aArgs, "line"),
        generatedColumn: util6.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(util6.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 = util6.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, util6.compareByGeneratedPositionsDeflated);
      quickSort(this.__originalMappings, util6.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 util6 = 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 = util6.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 ? util6.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[util6.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(util6.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 map = 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) {
            map.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) {
          map.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) {
              map.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) {
        map.setSourceContent(sourceFile, sourceContent);
      });
      return { code: generated.code, map };
    };
    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, base2, indent, json, renumber, hexadecimal, quotes, escapeless, newline2, space2, parentheses, semicolons, safeConcatenation, directive, extra, parse8, sourceMap, sourceCode, preserveBlankLines, FORMAT_MINIFY, FORMAT_DEFAULTS;
      estraverse = require_estraverse();
      esutils = require_utils2();
      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 merge(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 json ? "null" : renumber ? "1e400" : "1e+400";
        }
        result = "" + value;
        if (!renumber || result.length < 3) {
          return result;
        }
        point = result.indexOf(".");
        if (!json && 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 hex;
        if (code === 8) {
          return "\\b";
        }
        if (code === 12) {
          return "\\f";
        }
        if (code === 9) {
          return "\\t";
        }
        hex = code.toString(16).toUpperCase();
        if (json || code > 255) {
          return "\\u" + "0000".slice(hex.length) + hex;
        } else if (code === 0 && !esutils.code.isDecimalDigit(next)) {
          return "\\0";
        } else if (code === 11) {
          return "\\x0B";
        } else {
          return "\\x" + "00".slice(hex.length) + hex;
        }
      }
      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 && json) {
            result += "\\";
          } else if (esutils.code.isLineTerminator(code) || code === 92) {
            result += escapeDisallowedCharacter(code);
            continue;
          } else if (!esutils.code.isIdentifierPartES5(code) && (json && code < 32 || !json && !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 join6(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 [base2, stmt];
      }
      function withIndent(fn) {
        var previousBase;
        previousBase = base2;
        base2 += indent;
        fn(base2);
        base2 = 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 array, i, len, line, j, spaces, previousBase, sn;
        array = value.split(/\r\n|[\r\n]/);
        spaces = Number.MAX_VALUE;
        for (i = 1, len = array.length; i < len; ++i) {
          line = array[i];
          j = 0;
          while (j < line.length && esutils.code.isWhiteSpace(line.charCodeAt(j))) {
            ++j;
          }
          if (spaces > j) {
            spaces = j;
          }
        }
        if (typeof specialBase !== "undefined") {
          previousBase = base2;
          if (array[1][spaces] === "*") {
            specialBase += " ";
          }
          base2 = specialBase;
        } else {
          if (spaces & 1) {
            --spaces;
          }
          previousBase = base2;
        }
        for (i = 1, len = array.length; i < len; ++i) {
          sn = toSourceNodeWhenNeeded(addIndent(array[i].slice(spaces)));
          array[i] = sourceMap ? sn.join("") : sn;
        }
        base2 = previousBase;
        return array.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([base2, 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, current2, should) {
        if (current2 < should) {
          return ["(", text, ")"];
        }
        return text;
      }
      function generateVerbatimString(string) {
        var i, iz, result;
        result = string.split(/\r\n|\n/);
        for (i = 1, iz = result.length; i < iz; i++) {
          result[i] = newline2 + base2 + 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, base2];
        }
        return [result, newline2, base2];
      };
      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 = join6(result, operator);
          result = [join6(
            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(base2);
          result.push("}");
          return result;
        },
        ClassDeclaration: function(stmt, flags) {
          var result, fragment;
          result = ["class"];
          if (stmt.id) {
            result = join6(result, this.generateExpression(stmt.id, Precedence.Sequence, E_TTT));
          }
          if (stmt.superClass) {
            fragment = join6("extends", this.generateExpression(stmt.superClass, Precedence.Unary, E_TTT));
            result = join6(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 = join6("do", this.maybeBlock(stmt.body, S_TFFF));
          result = this.maybeBlockSuffix(stmt.body, result);
          return join6(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 = join6(result, "default");
          if (isStatement(stmt.declaration)) {
            result = join6(result, this.generateStatement(stmt.declaration, bodyFlags));
          } else {
            result = join6(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 join6(result, this.generateStatement(stmt.declaration, bodyFlags));
          }
          if (stmt.specifiers) {
            if (stmt.specifiers.length === 0) {
              result = join6(result, "{" + space2 + "}");
            } else if (stmt.specifiers[0].type === Syntax.ExportBatchSpecifier) {
              result = join6(result, this.generateExpression(stmt.specifiers[0], Precedence.Sequence, E_TTT));
            } else {
              result = join6(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(base2 + "}");
            }
            if (stmt.source) {
              result = join6(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 = join6(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 = join6(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(base2 + "}" + space2);
              }
            }
          }
          result = join6(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 [join6(
            "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 = join6(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 = join6(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 = join6(result, this.generateStatement(stmt.handler[i], S_TFFF));
                  if (stmt.finalizer || i + 1 !== iz) {
                    result = this.maybeBlockSuffix(stmt.handler[i].body, result);
                  }
                }
              } else {
                result = join6(result, this.generateStatement(stmt.handler, S_TFFF));
                if (stmt.finalizer) {
                  result = this.maybeBlockSuffix(stmt.handler.body, result);
                }
              }
            }
          }
          if (stmt.finalizer) {
            result = join6(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 = [
                join6("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 = join6(result, ["else ", this.generateStatement(stmt.alternate, bodyFlags)]);
            } else {
              result = join6(result, join6("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 [join6(
              "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;
        }
      };
      merge(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 = join6(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 = join6(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 = join6(
            "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 = join6(expr.operator, fragment);
          } else {
            result = [expr.operator];
            if (expr.operator.length > 2) {
              result = join6(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 = join6(
              result,
              this.generateExpression(expr.argument, Precedence.Yield, E_TTT)
            );
          }
          return parenthesize(result, Precedence.Yield, precedence);
        },
        AwaitExpression: function(expr, precedence, flags) {
          var result = join6(
            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 ? base2 : "");
          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 = join6(result, this.generateExpression(expr.id, Precedence.Sequence, E_TTT));
          }
          if (expr.superClass) {
            fragment = join6("extends", this.generateExpression(expr.superClass, Precedence.Unary, E_TTT));
            result = join6(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 = [
              join6(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 join6(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(base2);
          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 ? base2 : "");
          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") && parse8 && extra.raw) {
            try {
              raw = parse8(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 = join6(result, fragment);
                } else {
                  result.push(fragment);
                }
              }
            });
          }
          if (expr.filter) {
            result = join6(result, "if" + space2);
            fragment = this.generateExpression(expr.filter, Precedence.Sequence, E_TTT);
            result = join6(result, ["(", fragment, ")"]);
          }
          if (!extra.moz.comprehensionExpressionStartsWithAssignment) {
            fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT);
            result = join6(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 = join6(fragment, expr.of ? "of" : "in");
          fragment = join6(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);
        }
      };
      merge(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 defaultOptions3 = getDefaultOptions(), result, pair;
        if (options != null) {
          if (typeof options.indent === "string") {
            defaultOptions3.format.indent.style = options.indent;
          }
          if (typeof options.base === "number") {
            defaultOptions3.format.indent.base = options.base;
          }
          options = updateDeeply(defaultOptions3, options);
          indent = options.format.indent.style;
          if (typeof options.base === "string") {
            base2 = options.base;
          } else {
            base2 = stringRepeat(indent, options.format.indent.base);
          }
        } else {
          options = defaultOptions3;
          indent = options.format.indent.style;
          base2 = stringRepeat(indent, options.format.indent.base);
        }
        json = options.format.json;
        renumber = options.format.renumber;
        hexadecimal = json ? false : options.format.hexadecimal;
        quotes = json ? "double" : options.format.quotes;
        escapeless = options.format.escapeless;
        newline2 = options.format.newline;
        space2 = options.format.space;
        if (options.format.compact) {
          newline2 = space2 = indent = base2 = "";
        }
        parentheses = options.format.parentheses;
        semicolons = options.format.semicolons;
        safeConcatenation = options.format.safeConcatenation;
        directive = options.directive;
        parse8 = json ? 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 parse8(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 = parse8;
            function parseModule(code, options, delegate) {
              var parsingOptions = options || {};
              parsingOptions.sourceType = "module";
              return parse8(code, parsingOptions, delegate);
            }
            exports3.parseModule = parseModule;
            function parseScript(code, options, delegate) {
              var parsingOptions = options || {};
              parsingOptions.sourceType = "script";
              return parse8(code, parsingOptions, delegate);
            }
            exports3.parseScript = parseScript;
            function tokenize(code, options, delegate) {
              var tokenizer2 = new tokenizer_1.Tokenizer(code, options);
              var tokens;
              tokens = [];
              try {
                while (true) {
                  var token = tokenizer2.getNextToken();
                  if (!token) {
                    break;
                  }
                  if (delegate) {
                    token = delegate(token);
                  }
                  tokens.push(token);
                }
              } catch (e) {
                tokenizer2.errorHandler.tolerate(e);
              }
              if (tokenizer2.errorHandler.tolerant) {
                tokens.errors = tokenizer2.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(d2, b) {
                d2.__proto__ = b;
              } || function(d2, b) {
                for (var p in b) if (b.hasOwnProperty(p)) d2[p] = b[p];
              };
              return function(d2, b) {
                extendStatics2(d2, b);
                function __() {
                  this.constructor = d2;
                }
                d2.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 Node3 = __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 hex = 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) {
                          hex = ch === "x";
                          valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0));
                          numeric = numeric && !hex;
                        }
                        break;
                      default:
                        valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0)));
                        valid = valid && !(hex && !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 (hex && str.length > 2) {
                    result = String.fromCharCode(parseInt("0" + str.substr(1), 16));
                  } else if (!numeric && !hex && 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 object = elementName;
                    this.expectJSX(".");
                    var property = this.parseJSXIdentifier();
                    elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object, 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 Node3.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(object, property) {
                this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression;
                this.object = object;
                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(object, property) {
                this.type = syntax_1.Syntax.MemberExpression;
                this.computed = true;
                this.object = object;
                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(init2, test, update, body) {
                this.type = syntax_1.Syntax.ForStatement;
                this.init = init2;
                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(meta, property) {
                this.type = syntax_1.Syntax.MetaProperty;
                this.meta = meta;
                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(object, property) {
                this.type = syntax_1.Syntax.MemberExpression;
                this.computed = false;
                this.object = object;
                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, init2) {
                this.type = syntax_1.Syntax.VariableDeclarator;
                this.id = id;
                this.init = init2;
              }
              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(object, body) {
                this.type = syntax_1.Syntax.WithStatement;
                this.object = object;
                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 Node3 = __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 Parser3 = (function() {
              function Parser4(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
                };
              }
              Parser4.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);
              };
              Parser4.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);
              };
              Parser4.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);
                }
              };
              Parser4.prototype.throwUnexpectedToken = function(token, message) {
                throw this.unexpectedTokenError(token, message);
              };
              Parser4.prototype.tolerateUnexpectedToken = function(token, message) {
                this.errorHandler.tolerate(this.unexpectedTokenError(token, message));
              };
              Parser4.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);
                    }
                  }
                }
              };
              Parser4.prototype.getTokenRaw = function(token) {
                return this.scanner.source.slice(token.start, token.end);
              };
              Parser4.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;
              };
              Parser4.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;
              };
              Parser4.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;
              };
              Parser4.prototype.createNode = function() {
                return {
                  index: this.startMarker.index,
                  line: this.startMarker.line,
                  column: this.startMarker.column
                };
              };
              Parser4.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
                };
              };
              Parser4.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;
              };
              Parser4.prototype.expect = function(value) {
                var token = this.nextToken();
                if (token.type !== 7 || token.value !== value) {
                  this.throwUnexpectedToken(token);
                }
              };
              Parser4.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(",");
                }
              };
              Parser4.prototype.expectKeyword = function(keyword) {
                var token = this.nextToken();
                if (token.type !== 4 || token.value !== keyword) {
                  this.throwUnexpectedToken(token);
                }
              };
              Parser4.prototype.match = function(value) {
                return this.lookahead.type === 7 && this.lookahead.value === value;
              };
              Parser4.prototype.matchKeyword = function(keyword) {
                return this.lookahead.type === 4 && this.lookahead.value === keyword;
              };
              Parser4.prototype.matchContextualKeyword = function(keyword) {
                return this.lookahead.type === 3 && this.lookahead.value === keyword;
              };
              Parser4.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 === "|=";
              };
              Parser4.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;
              };
              Parser4.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;
              };
              Parser4.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;
                }
              };
              Parser4.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 Node3.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 Node3.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 Node3.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 Node3.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 Node3.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 Node3.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 Node3.ThisExpression());
                      } else if (this.matchKeyword("class")) {
                        expr = this.parseClassExpression();
                      } else {
                        expr = this.throwUnexpectedToken(this.nextToken());
                      }
                    }
                    break;
                  default:
                    expr = this.throwUnexpectedToken(this.nextToken());
                }
                return expr;
              };
              Parser4.prototype.parseSpreadElement = function() {
                var node = this.createNode();
                this.expect("...");
                var arg = this.inheritCoverGrammar(this.parseAssignmentExpression);
                return this.finalize(node, new Node3.SpreadElement(arg));
              };
              Parser4.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 Node3.ArrayExpression(elements));
              };
              Parser4.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;
              };
              Parser4.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 Node3.FunctionExpression(null, params.params, method, isGenerator));
              };
              Parser4.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 Node3.AsyncFunctionExpression(null, params.params, method));
              };
              Parser4.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 Node3.Literal(token.value, raw));
                    break;
                  case 3:
                  case 1:
                  case 5:
                  case 4:
                    key = this.finalize(node, new Node3.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;
              };
              Parser4.prototype.isPropertyKey = function(key, value) {
                return key.type === syntax_1.Syntax.Identifier && key.name === value || key.type === syntax_1.Syntax.Literal && key.value === value;
              };
              Parser4.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 isAsync3 = false;
                if (token.type === 3) {
                  var id = token.value;
                  this.nextToken();
                  computed = this.match("[");
                  isAsync3 = !this.hasLineTerminator && id === "async" && !this.match(":") && !this.match("(") && !this.match("*") && !this.match(",");
                  key = isAsync3 ? this.parseObjectPropertyKey() : this.finalize(node, new Node3.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 && !isAsync3 && token.value === "get" && lookaheadPropertyKey) {
                  kind = "get";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  this.context.allowYield = false;
                  value = this.parseGetterMethod();
                } else if (token.type === 3 && !isAsync3 && 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(":") && !isAsync3) {
                    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 = isAsync3 ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
                    method = true;
                  } else if (token.type === 3) {
                    var id = this.finalize(node, new Node3.Identifier(token.value));
                    if (this.match("=")) {
                      this.context.firstCoverInitializedNameError = this.lookahead;
                      this.nextToken();
                      shorthand = true;
                      var init2 = this.isolateCoverGrammar(this.parseAssignmentExpression);
                      value = this.finalize(node, new Node3.AssignmentPattern(id, init2));
                    } else {
                      shorthand = true;
                      value = id;
                    }
                  } else {
                    this.throwUnexpectedToken(this.nextToken());
                  }
                }
                return this.finalize(node, new Node3.Property(kind, key, computed, value, method, shorthand));
              };
              Parser4.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 Node3.ObjectExpression(properties));
              };
              Parser4.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 Node3.TemplateElement({ raw, cooked }, token.tail));
              };
              Parser4.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 Node3.TemplateElement({ raw, cooked }, token.tail));
              };
              Parser4.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 Node3.TemplateLiteral(quasis, expressions));
              };
              Parser4.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;
                }
              };
              Parser4.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 Node3.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;
              };
              Parser4.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;
              };
              Parser4.prototype.isIdentifierName = function(token) {
                return token.type === 3 || token.type === 4 || token.type === 1 || token.type === 5;
              };
              Parser4.prototype.parseIdentifierName = function() {
                var node = this.createNode();
                var token = this.nextToken();
                if (!this.isIdentifierName(token)) {
                  this.throwUnexpectedToken(token);
                }
                return this.finalize(node, new Node3.Identifier(token.value));
              };
              Parser4.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 Node3.MetaProperty(id, property);
                  } else {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                } else {
                  var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression);
                  var args = this.match("(") ? this.parseArguments() : [];
                  expr = new Node3.NewExpression(callee, args);
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                }
                return this.finalize(node, expr);
              };
              Parser4.prototype.parseAsyncArgument = function() {
                var arg = this.parseAssignmentExpression();
                this.context.firstCoverInitializedNameError = null;
                return arg;
              };
              Parser4.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;
              };
              Parser4.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 Node3.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 Node3.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 Node3.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 Node3.ComputedMemberExpression(expr, property));
                  } else if (this.lookahead.type === 10 && this.lookahead.head) {
                    var quasi = this.parseTemplateLiteral();
                    expr = this.finalize(this.startNode(startToken), new Node3.TaggedTemplateExpression(expr, quasi));
                  } else {
                    break;
                  }
                }
                this.context.allowIn = previousAllowIn;
                return expr;
              };
              Parser4.prototype.parseSuper = function() {
                var node = this.createNode();
                this.expectKeyword("super");
                if (!this.match("[") && !this.match(".")) {
                  this.throwUnexpectedToken(this.lookahead);
                }
                return this.finalize(node, new Node3.Super());
              };
              Parser4.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 Node3.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 Node3.StaticMemberExpression(expr, property));
                  } else if (this.lookahead.type === 10 && this.lookahead.head) {
                    var quasi = this.parseTemplateLiteral();
                    expr = this.finalize(node, new Node3.TaggedTemplateExpression(expr, quasi));
                  } else {
                    break;
                  }
                }
                return expr;
              };
              Parser4.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 Node3.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 Node3.UpdateExpression(operator, expr, prefix));
                    }
                  }
                }
                return expr;
              };
              Parser4.prototype.parseAwaitExpression = function() {
                var node = this.createNode();
                this.nextToken();
                var argument = this.parseUnaryExpression();
                return this.finalize(node, new Node3.AwaitExpression(argument));
              };
              Parser4.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 Node3.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;
              };
              Parser4.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 Node3.BinaryExpression("**", left, right));
                }
                return expr;
              };
              Parser4.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;
              };
              Parser4.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 Node3.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 Node3.BinaryExpression(operator, stack[i - 2], expr));
                    i -= 2;
                    lastMarker = marker;
                  }
                }
                return expr;
              };
              Parser4.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 Node3.ConditionalExpression(expr, consequent, alternate));
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                }
                return expr;
              };
              Parser4.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 Node3.Identifier;
              };
              Parser4.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
                };
              };
              Parser4.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 isAsync3 = 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 = isAsync3;
                      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 = isAsync3 ? this.finalize(node, new Node3.AsyncArrowFunctionExpression(list.params, body, expression)) : this.finalize(node, new Node3.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 Node3.AssignmentExpression(operator, expr, right));
                      this.context.firstCoverInitializedNameError = null;
                    }
                  }
                }
                return expr;
              };
              Parser4.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 Node3.SequenceExpression(expressions));
                }
                return expr;
              };
              Parser4.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;
              };
              Parser4.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 Node3.BlockStatement(block));
              };
              Parser4.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 init2 = null;
                if (kind === "const") {
                  if (!this.matchKeyword("in") && !this.matchContextualKeyword("of")) {
                    if (this.match("=")) {
                      this.nextToken();
                      init2 = 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("=");
                  init2 = this.isolateCoverGrammar(this.parseAssignmentExpression);
                }
                return this.finalize(node, new Node3.VariableDeclarator(id, init2));
              };
              Parser4.prototype.parseBindingList = function(kind, options) {
                var list = [this.parseLexicalBinding(kind, options)];
                while (this.match(",")) {
                  this.nextToken();
                  list.push(this.parseLexicalBinding(kind, options));
                }
                return list;
              };
              Parser4.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";
              };
              Parser4.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 Node3.VariableDeclaration(declarations, kind));
              };
              Parser4.prototype.parseBindingRestElement = function(params, kind) {
                var node = this.createNode();
                this.expect("...");
                var arg = this.parsePattern(params, kind);
                return this.finalize(node, new Node3.RestElement(arg));
              };
              Parser4.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 Node3.ArrayPattern(elements));
              };
              Parser4.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 init2 = this.finalize(node, new Node3.Identifier(keyToken.value));
                  if (this.match("=")) {
                    params.push(keyToken);
                    shorthand = true;
                    this.nextToken();
                    var expr = this.parseAssignmentExpression();
                    value = this.finalize(this.startNode(keyToken), new Node3.AssignmentPattern(init2, expr));
                  } else if (!this.match(":")) {
                    params.push(keyToken);
                    shorthand = true;
                    value = init2;
                  } 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 Node3.Property("init", key, computed, value, method, shorthand));
              };
              Parser4.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 Node3.ObjectPattern(properties));
              };
              Parser4.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;
              };
              Parser4.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 Node3.AssignmentPattern(pattern, right));
                }
                return pattern;
              };
              Parser4.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 Node3.Identifier(token.value));
              };
              Parser4.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 init2 = null;
                if (this.match("=")) {
                  this.nextToken();
                  init2 = this.isolateCoverGrammar(this.parseAssignmentExpression);
                } else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) {
                  this.expect("=");
                }
                return this.finalize(node, new Node3.VariableDeclarator(id, init2));
              };
              Parser4.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;
              };
              Parser4.prototype.parseVariableStatement = function() {
                var node = this.createNode();
                this.expectKeyword("var");
                var declarations = this.parseVariableDeclarationList({ inFor: false });
                this.consumeSemicolon();
                return this.finalize(node, new Node3.VariableDeclaration(declarations, "var"));
              };
              Parser4.prototype.parseEmptyStatement = function() {
                var node = this.createNode();
                this.expect(";");
                return this.finalize(node, new Node3.EmptyStatement());
              };
              Parser4.prototype.parseExpressionStatement = function() {
                var node = this.createNode();
                var expr = this.parseExpression();
                this.consumeSemicolon();
                return this.finalize(node, new Node3.ExpressionStatement(expr));
              };
              Parser4.prototype.parseIfClause = function() {
                if (this.context.strict && this.matchKeyword("function")) {
                  this.tolerateError(messages_1.Messages.StrictFunction);
                }
                return this.parseStatement();
              };
              Parser4.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 Node3.EmptyStatement());
                } else {
                  this.expect(")");
                  consequent = this.parseIfClause();
                  if (this.matchKeyword("else")) {
                    this.nextToken();
                    alternate = this.parseIfClause();
                  }
                }
                return this.finalize(node, new Node3.IfStatement(test, consequent, alternate));
              };
              Parser4.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 Node3.DoWhileStatement(body, test));
              };
              Parser4.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 Node3.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 Node3.WhileStatement(test, body));
              };
              Parser4.prototype.parseForStatement = function() {
                var init2 = 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")) {
                    init2 = 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");
                      }
                      init2 = this.finalize(init2, new Node3.VariableDeclaration(declarations, "var"));
                      this.nextToken();
                      left = init2;
                      right = this.parseExpression();
                      init2 = null;
                    } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword("of")) {
                      init2 = this.finalize(init2, new Node3.VariableDeclaration(declarations, "var"));
                      this.nextToken();
                      left = init2;
                      right = this.parseAssignmentExpression();
                      init2 = null;
                      forIn = false;
                    } else {
                      init2 = this.finalize(init2, new Node3.VariableDeclaration(declarations, "var"));
                      this.expect(";");
                    }
                  } else if (this.matchKeyword("const") || this.matchKeyword("let")) {
                    init2 = this.createNode();
                    var kind = this.nextToken().value;
                    if (!this.context.strict && this.lookahead.value === "in") {
                      init2 = this.finalize(init2, new Node3.Identifier(kind));
                      this.nextToken();
                      left = init2;
                      right = this.parseExpression();
                      init2 = 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")) {
                        init2 = this.finalize(init2, new Node3.VariableDeclaration(declarations, kind));
                        this.nextToken();
                        left = init2;
                        right = this.parseExpression();
                        init2 = null;
                      } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword("of")) {
                        init2 = this.finalize(init2, new Node3.VariableDeclaration(declarations, kind));
                        this.nextToken();
                        left = init2;
                        right = this.parseAssignmentExpression();
                        init2 = null;
                        forIn = false;
                      } else {
                        this.consumeSemicolon();
                        init2 = this.finalize(init2, new Node3.VariableDeclaration(declarations, kind));
                      }
                    }
                  } else {
                    var initStartToken = this.lookahead;
                    var previousAllowIn = this.context.allowIn;
                    this.context.allowIn = false;
                    init2 = this.inheritCoverGrammar(this.parseAssignmentExpression);
                    this.context.allowIn = previousAllowIn;
                    if (this.matchKeyword("in")) {
                      if (!this.context.isAssignmentTarget || init2.type === syntax_1.Syntax.AssignmentExpression) {
                        this.tolerateError(messages_1.Messages.InvalidLHSInForIn);
                      }
                      this.nextToken();
                      this.reinterpretExpressionAsPattern(init2);
                      left = init2;
                      right = this.parseExpression();
                      init2 = null;
                    } else if (this.matchContextualKeyword("of")) {
                      if (!this.context.isAssignmentTarget || init2.type === syntax_1.Syntax.AssignmentExpression) {
                        this.tolerateError(messages_1.Messages.InvalidLHSInForLoop);
                      }
                      this.nextToken();
                      this.reinterpretExpressionAsPattern(init2);
                      left = init2;
                      right = this.parseAssignmentExpression();
                      init2 = null;
                      forIn = false;
                    } else {
                      if (this.match(",")) {
                        var initSeq = [init2];
                        while (this.match(",")) {
                          this.nextToken();
                          initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
                        }
                        init2 = this.finalize(this.startNode(initStartToken), new Node3.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 Node3.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 Node3.ForStatement(init2, test, update, body)) : forIn ? this.finalize(node, new Node3.ForInStatement(left, right, body)) : this.finalize(node, new Node3.ForOfStatement(left, right, body));
              };
              Parser4.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 Node3.ContinueStatement(label));
              };
              Parser4.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 Node3.BreakStatement(label));
              };
              Parser4.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 Node3.ReturnStatement(argument));
              };
              Parser4.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 object = this.parseExpression();
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                  body = this.finalize(this.createNode(), new Node3.EmptyStatement());
                } else {
                  this.expect(")");
                  body = this.parseStatement();
                }
                return this.finalize(node, new Node3.WithStatement(object, body));
              };
              Parser4.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 Node3.SwitchCase(test, consequent));
              };
              Parser4.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 Node3.SwitchStatement(discriminant, cases));
              };
              Parser4.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 Node3.LabeledStatement(id, body);
                } else {
                  this.consumeSemicolon();
                  statement = new Node3.ExpressionStatement(expr);
                }
                return this.finalize(node, statement);
              };
              Parser4.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 Node3.ThrowStatement(argument));
              };
              Parser4.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 Node3.CatchClause(param, body));
              };
              Parser4.prototype.parseFinallyClause = function() {
                this.expectKeyword("finally");
                return this.parseBlock();
              };
              Parser4.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 Node3.TryStatement(block, handler, finalizer));
              };
              Parser4.prototype.parseDebuggerStatement = function() {
                var node = this.createNode();
                this.expectKeyword("debugger");
                this.consumeSemicolon();
                return this.finalize(node, new Node3.DebuggerStatement());
              };
              Parser4.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;
              };
              Parser4.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 Node3.BlockStatement(body));
              };
              Parser4.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;
                }
              };
              Parser4.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 Node3.RestElement(arg));
              };
              Parser4.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 Node3.Identifier;
                options.params.push(param);
              };
              Parser4.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
                };
              };
              Parser4.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;
              };
              Parser4.prototype.parseFunctionDeclaration = function(identifierIsOptional) {
                var node = this.createNode();
                var isAsync3 = this.matchContextualKeyword("async");
                if (isAsync3) {
                  this.nextToken();
                }
                this.expectKeyword("function");
                var isGenerator = isAsync3 ? 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 = isAsync3;
                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 isAsync3 ? this.finalize(node, new Node3.AsyncFunctionDeclaration(id, params, body)) : this.finalize(node, new Node3.FunctionDeclaration(id, params, body, isGenerator));
              };
              Parser4.prototype.parseFunctionExpression = function() {
                var node = this.createNode();
                var isAsync3 = this.matchContextualKeyword("async");
                if (isAsync3) {
                  this.nextToken();
                }
                this.expectKeyword("function");
                var isGenerator = isAsync3 ? 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 = isAsync3;
                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 isAsync3 ? this.finalize(node, new Node3.AsyncFunctionExpression(id, params, body)) : this.finalize(node, new Node3.FunctionExpression(id, params, body, isGenerator));
              };
              Parser4.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 Node3.Directive(expr, directive) : new Node3.ExpressionStatement(expr));
              };
              Parser4.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;
              };
              Parser4.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;
              };
              Parser4.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 Node3.FunctionExpression(null, formalParameters.params, method, isGenerator));
              };
              Parser4.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 Node3.RestElement) {
                  this.tolerateError(messages_1.Messages.BadSetterRestParameter);
                }
                var method = this.parsePropertyMethod(formalParameters);
                this.context.allowYield = previousAllowYield;
                return this.finalize(node, new Node3.FunctionExpression(null, formalParameters.params, method, isGenerator));
              };
              Parser4.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 Node3.FunctionExpression(null, params.params, method, isGenerator));
              };
              Parser4.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;
              };
              Parser4.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 Node3.YieldExpression(argument, delegate));
              };
              Parser4.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 isAsync3 = 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 !== "*") {
                      isAsync3 = 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 = isAsync3 ? 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 Node3.MethodDefinition(key, computed, value, kind, isStatic));
              };
              Parser4.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;
              };
              Parser4.prototype.parseClassBody = function() {
                var node = this.createNode();
                var elementList = this.parseClassElementList();
                return this.finalize(node, new Node3.ClassBody(elementList));
              };
              Parser4.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 Node3.ClassDeclaration(id, superClass, classBody));
              };
              Parser4.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 Node3.ClassExpression(id, superClass, classBody));
              };
              Parser4.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 Node3.Module(body));
              };
              Parser4.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 Node3.Script(body));
              };
              Parser4.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 Node3.Literal(token.value, raw));
              };
              Parser4.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 Node3.ImportSpecifier(local, imported));
              };
              Parser4.prototype.parseNamedImports = function() {
                this.expect("{");
                var specifiers = [];
                while (!this.match("}")) {
                  specifiers.push(this.parseImportSpecifier());
                  if (!this.match("}")) {
                    this.expect(",");
                  }
                }
                this.expect("}");
                return specifiers;
              };
              Parser4.prototype.parseImportDefaultSpecifier = function() {
                var node = this.createNode();
                var local = this.parseIdentifierName();
                return this.finalize(node, new Node3.ImportDefaultSpecifier(local));
              };
              Parser4.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 Node3.ImportNamespaceSpecifier(local));
              };
              Parser4.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 Node3.ImportDeclaration(specifiers, src));
              };
              Parser4.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 Node3.ExportSpecifier(local, exported));
              };
              Parser4.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 Node3.ExportDefaultDeclaration(declaration));
                  } else if (this.matchKeyword("class")) {
                    var declaration = this.parseClassDeclaration(true);
                    exportDeclaration = this.finalize(node, new Node3.ExportDefaultDeclaration(declaration));
                  } else if (this.matchContextualKeyword("async")) {
                    var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression();
                    exportDeclaration = this.finalize(node, new Node3.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 Node3.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 Node3.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 Node3.ExportNamedDeclaration(declaration, [], null));
                } else if (this.matchAsyncFunction()) {
                  var declaration = this.parseFunctionDeclaration();
                  exportDeclaration = this.finalize(node, new Node3.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 Node3.ExportNamedDeclaration(null, specifiers, source));
                }
                return exportDeclaration;
              };
              return Parser4;
            })();
            exports3.Parser = Parser3;
          },
          /* 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(error) {
                this.errors.push(error);
              };
              ErrorHandler2.prototype.tolerate = function(error) {
                if (this.tolerant) {
                  this.recordError(error);
                } else {
                  throw error;
                }
              };
              ErrorHandler2.prototype.constructError = function(msg, column) {
                var error = new Error(msg);
                try {
                  throw error;
                } catch (base2) {
                  if (Object.create && Object.defineProperty) {
                    error = Object.create(base2);
                    Object.defineProperty(error, "column", { value: column });
                  }
                }
                return error;
              };
              ErrorHandler2.prototype.createError = function(index, line, col, description) {
                var msg = "Line " + line + ": " + description;
                var error = this.constructError(msg, col);
                error.index = index;
                error.lineNumber = line;
                error.description = description;
                return error;
              };
              ErrorHandler2.prototype.throwError = function(index, line, col, description) {
                throw this.createError(index, line, col, description);
              };
              ErrorHandler2.prototype.tolerateError = function(index, line, col, description) {
                var error = this.createError(index, line, col, description);
                if (this.tolerant) {
                  this.recordError(error);
                } else {
                  throw error;
                }
              };
              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(offset2) {
                var comments = [];
                var start, loc;
                if (this.trackComment) {
                  comments = [];
                  start = this.index - offset2;
                  loc = {
                    start: {
                      line: this.lineNumber,
                      column: this.index - this.lineStart - offset2
                    },
                    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 + offset2, 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 + offset2, 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, $2) {
                    var codePoint = parseInt($1 || $2, 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 regex2 = previous !== null;
                switch (previous) {
                  case "this":
                  case "]":
                    regex2 = false;
                    break;
                  case ")":
                    var keyword = this.values[this.paren - 1];
                    regex2 = keyword === "if" || keyword === "while" || keyword === "for" || keyword === "with";
                    break;
                  case "}":
                    regex2 = false;
                    if (this.values[this.curly - 3] === "function") {
                      var check = this.values[this.curly - 4];
                      regex2 = check ? !this.beforeFunctionExpression(check) : false;
                    } else if (this.values[this.curly - 4] === "function") {
                      var check = this.values[this.curly - 5];
                      regex2 = check ? !this.beforeFunctionExpression(check) : true;
                    }
                    break;
                  default:
                    break;
                }
                return regex2;
              };
              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, config) {
                this.errorHandler = new error_handler_1.ErrorHandler();
                this.errorHandler.tolerant = config ? typeof config.tolerant === "boolean" && config.tolerant : false;
                this.scanner = new scanner_1.Scanner(code, this.errorHandler);
                this.scanner.trackComment = config ? typeof config.comment === "boolean" && config.comment : false;
                this.trackRange = config ? typeof config.range === "boolean" && config.range : false;
                this.trackLoc = config ? typeof config.loc === "boolean" && config.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(d2, b) {
  if (typeof b !== "function" && b !== null)
    throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  extendStatics(d2, b);
  function __() {
    this.constructor = d2;
  }
  d2.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __rest(s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
    t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
}
function __decorate(decorators, target, key, desc) {
  var c = arguments.length, r2 = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r2 = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d2 = decorators[i]) r2 = (c < 3 ? d2(r2) : c > 3 ? d2(target, key, r2) : d2(target, key)) || r2;
  return c > 3 && r2 && Object.defineProperty(target, key, r2), r2;
}
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 _2, done = false;
  for (var i = decorators.length - 1; i >= 0; i--) {
    var context = {};
    for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
    for (var p in contextIn.access) context.access[p] = contextIn.access[p];
    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 (_2 = accept(result.get)) descriptor.get = _2;
      if (_2 = accept(result.set)) descriptor.set = _2;
      if (_2 = accept(result.init)) initializers.unshift(_2);
    } else if (_2 = accept(result)) {
      if (kind === "field") initializers.unshift(_2);
      else descriptor[key] = _2;
    }
  }
  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(x2) {
  return typeof x2 === "symbol" ? x2 : "".concat(x2);
}
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(resolve6) {
      resolve6(value);
    });
  }
  return new (P || (P = Promise))(function(resolve6, 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 ? resolve6(result.value) : adopt2(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator(thisArg, body) {
  var _2 = { 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(v2) {
      return step([n, v2]);
    };
  }
  function step(op) {
    if (f) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_2 = 0)), _2) 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:
          _2.label++;
          return { value: op[1], done: false };
        case 5:
          _2.label++;
          y = op[1];
          op = [0];
          continue;
        case 7:
          op = _2.ops.pop();
          _2.trys.pop();
          continue;
        default:
          if (!(t = _2.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _2 = 0;
            continue;
          }
          if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
            _2.label = op[1];
            break;
          }
          if (op[0] === 6 && _2.label < t[1]) {
            _2.label = t[1];
            t = op;
            break;
          }
          if (t && _2.label < t[2]) {
            _2.label = t[2];
            _2.ops.push(op);
            break;
          }
          if (t[2]) _2.ops.pop();
          _2.trys.pop();
          continue;
      }
      op = body.call(thisArg, _2);
    } 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(m2, o) {
  for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m2, p);
}
function __values(o) {
  var s = typeof Symbol === "function" && Symbol.iterator, m2 = s && o[s], i = 0;
  if (m2) return m2.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 m2 = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m2) return o;
  var i = m2.call(o), r2, ar = [], e;
  try {
    while ((n === void 0 || n-- > 0) && !(r2 = i.next()).done) ar.push(r2.value);
  } catch (error) {
    e = { error };
  } finally {
    try {
      if (r2 && !r2.done && (m2 = i["return"])) m2.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 r2 = Array(s), k = 0, i = 0; i < il; i++)
    for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
      r2[k] = a[j];
  return r2;
}
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(v2) {
  return this instanceof __await ? (this.v = v2, this) : new __await(v2);
}
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(v2) {
      return Promise.resolve(v2).then(f, reject);
    };
  }
  function verb(n, f) {
    if (g[n]) {
      i[n] = function(v2) {
        return new Promise(function(a, b) {
          q2.push([n, v2, a, b]) > 1 || resume(n, v2);
        });
      };
      if (f) i[n] = f(i[n]);
    }
  }
  function resume(n, v2) {
    try {
      step(g[n](v2));
    } catch (e) {
      settle(q2[0][3], e);
    }
  }
  function step(r2) {
    r2.value instanceof __await ? Promise.resolve(r2.value.v).then(fulfill, reject) : settle(q2[0][2], r2);
  }
  function fulfill(value) {
    resume("next", value);
  }
  function reject(value) {
    resume("throw", value);
  }
  function settle(f, v2) {
    if (f(v2), q2.shift(), q2.length) resume(q2[0][0], q2[0][1]);
  }
}
function __asyncDelegator(o) {
  var i, p;
  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(v2) {
      return (p = !p) ? { value: __await(o[n](v2)), done: false } : f ? f(v2) : v2;
    } : f;
  }
}
function __asyncValues(o) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var m2 = o[Symbol.asyncIterator], i;
  return m2 ? m2.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(v2) {
      return new Promise(function(resolve6, reject) {
        v2 = o[n](v2), settle(resolve6, reject, v2.done, v2.value);
      });
    };
  }
  function settle(resolve6, reject, d2, v2) {
    Promise.resolve(v2).then(function(v3) {
      resolve6({ value: v3, done: d2 });
    }, 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 r2, s = 0;
  function next() {
    while (r2 = env3.stack.pop()) {
      try {
        if (!r2.async && s === 1) return s = 0, env3.stack.push(r2), Promise.resolve().then(next);
        if (r2.dispose) {
          var result = r2.dispose.call(r2.value);
          if (r2.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(path62, preserveJsx) {
  if (typeof path62 === "string" && /^\.\.?\//.test(path62)) {
    return path62.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m2, tsx, d2, ext, cm) {
      return tsx ? preserveJsx ? ".jsx" : ".js" : d2 && (!ext || !cm) ? m2 : d2 + ext + "." + cm.toLowerCase() + "js";
    });
  }
  return path62;
}
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(d2, b) {
      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b2) {
        d3.__proto__ = b2;
      } || function(d3, b2) {
        for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d3[p] = b2[p];
      };
      return extendStatics(d2, 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 p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
        }
        return t;
      };
      return __assign.apply(this, arguments);
    };
    __createBinding = Object.create ? (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    });
    __setModuleDefault = Object.create ? (function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    }) : function(o, v2) {
      o["default"] = v2;
    };
    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(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, 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 hasOwn2 = 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(types4) {
          var _this = _super.call(this) || this;
          _this.types = types4;
          _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 hasOwn2.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 types4 = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            types4[_i] = arguments[_i];
          }
          return new OrType(types4.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 (isArray2.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 (isObject.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 hasOwn2.call(defCache, typeName) ? defCache[typeName] : defCache[typeName] = new DefImpl(typeName);
        },
        hasDef: function(typeName) {
          return hasOwn2.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 isArray2 = defBuiltInType("array", []);
      var isObject = 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: isArray2,
        object: isObject,
        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" && hasOwn2.call(defCache, type)) {
            var d2 = defCache[type];
            if (d2.finalized) {
              return d2;
            }
          }
        }
        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 (hasOwn2.call(built, param))
                return;
              var all2 = _this.allFields;
              if (!hasOwn2.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 (hasOwn2.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();
                  extend2(allFields, def.allFields);
                  extend2(allSupertypes, def.allSupertypes);
                } else {
                  var message = "unknown supertype name " + JSON.stringify(name) + " for subtype " + JSON.stringify(_this.typeName);
                  throw new Error(message);
                }
              });
              extend2(allFields, this.ownFields);
              allSupertypes[this.typeName] = this;
              this.fieldNames.length = 0;
              for (var fieldName in allFields) {
                if (hasOwn2.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 (!hasOwn2.call(defCache, typeName)) {
          throw new Error("");
        }
        var d2 = defCache[typeName];
        if (d2.finalized !== true) {
          throw new Error("");
        }
        return d2.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 d2 = defCache[typeName];
          if (d2.finalized !== true) {
            throw new Error("" + typeName);
          }
          for (var j = 0; j < d2.supertypeList.length; ++j) {
            var superTypeName = d2.supertypeList[j];
            if (hasOwn2.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(object) {
        var d2 = defFromValue(object);
        if (d2) {
          return d2.fieldNames.slice(0);
        }
        if ("type" in object) {
          throw new Error("did not recognize object of type " + JSON.stringify(object.type));
        }
        return Object.keys(object);
      }
      function getFieldValue(object, fieldName) {
        var d2 = defFromValue(object);
        if (d2) {
          var field = d2.allFields[fieldName];
          if (field) {
            return field.getValue(object);
          }
        }
        return object && object[fieldName];
      }
      function eachField(object, callback, context) {
        getFieldNames(object).forEach(function(name) {
          callback.call(this, name, getFieldValue(object, name));
        }, context);
      }
      function someField(object, callback, context) {
        return getFieldNames(object).some(function(name) {
          return callback.call(this, name, getFieldValue(object, 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 d2 = defCache[typeName];
          if (d2.finalized !== true) {
            throw new Error("");
          }
          if (hasOwn2.call(lastSeen, typeName)) {
            delete list[lastSeen[typeName]];
          }
          lastSeen[typeName] = pos;
          list.push.apply(list, d2.baseNames);
        }
        for (var to = 0, from = to, len = list.length; from < len; ++from) {
          if (hasOwn2.call(list, from)) {
            list[to++] = list[from];
          }
        }
        list.length = to;
      }
      function extend2(into, from) {
        Object.keys(from).forEach(function(name) {
          into[name] = from[name];
        });
        return into;
      }
      function finalize() {
        Object.keys(defCache).forEach(function(name) {
          defCache[name].finalize();
        });
      }
      return {
        Type,
        builtInTypes,
        getSupertypeNames,
        computeSupertypeLookupTable,
        builders,
        defineMethod,
        getBuilderName,
        getStatementBuilderName,
        namedTypes,
        getFieldNames,
        getFieldValue,
        eachField,
        someField,
        finalize
      };
    }
    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 hasOwn2 = Op.hasOwnProperty;
    function pathPlugin(fork) {
      var types4 = fork.use(types_1.default);
      var isArray2 = types4.builtInTypes.array;
      var isNumber = types4.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(path62) {
        return path62.__childCache || (path62.__childCache = /* @__PURE__ */ Object.create(null));
      }
      function getChildPath(path62, name) {
        var cache = getChildCache(path62);
        var actualChildValue = path62.getValueProperty(name);
        var childPath = cache[name];
        if (!hasOwn2.call(cache, name) || // Ensure consistency between cache and reality.
        childPath.value !== actualChildValue) {
          childPath = cache[name] = new path62.constructor(actualChildValue, path62, 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 path62 = this;
        var count = names.length;
        for (var i = 0; i < count; ++i) {
          path62 = getChildPath(path62, names[i]);
        }
        return path62;
      };
      Pp.each = function each(callback, context) {
        var childPaths = [];
        var len = this.value.length;
        var i = 0;
        for (var i = 0; i < len; ++i) {
          if (hasOwn2.call(this.value, i)) {
            childPaths[i] = this.get(i);
          }
        }
        context = context || this;
        for (i = 0; i < len; ++i) {
          if (hasOwn2.call(childPaths, i)) {
            callback.call(context, childPaths[i]);
          }
        }
      };
      Pp.map = function map(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(path62, offset2, start, end) {
        isArray2.assert(path62.value);
        if (offset2 === 0) {
          return emptyMoves;
        }
        var length = path62.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(path62);
        for (var i = start; i < end; ++i) {
          if (hasOwn2.call(path62.value, i)) {
            var childPath = path62.get(i);
            if (childPath.name !== i) {
              throw new Error("");
            }
            var newIndex = i + offset2;
            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;
            path62.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];
        }
        isArray2.assert(this.value);
        delete getChildCache(this).length;
        return this.value.push.apply(this.value, args);
      };
      Pp.pop = function pop() {
        isArray2.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 pp2 = this.parentPath;
        var argc = args.length;
        var insertAtArgs = [this.name];
        for (var i = 0; i < argc; ++i) {
          insertAtArgs.push(args[i]);
        }
        return pp2.insertAt.apply(pp2, insertAtArgs);
      };
      Pp.insertAfter = function insertAfter() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        var pp2 = this.parentPath;
        var argc = args.length;
        var insertAtArgs = [this.name + 1];
        for (var i = 0; i < argc; ++i) {
          insertAtArgs.push(args[i]);
        }
        return pp2.insertAt.apply(pp2, insertAtArgs);
      };
      function repairRelationshipWithParent(path62) {
        if (!(path62 instanceof Path)) {
          throw new Error("");
        }
        var pp2 = path62.parentPath;
        if (!pp2) {
          return path62;
        }
        var parentValue = pp2.value;
        var parentCache = getChildCache(pp2);
        if (parentValue[path62.name] === path62.value) {
          parentCache[path62.name] = path62;
        } else if (isArray2.check(parentValue)) {
          var i = parentValue.indexOf(path62.value);
          if (i >= 0) {
            parentCache[path62.name = i] = path62;
          }
        } else {
          parentValue[path62.name] = path62.value;
          parentCache[path62.name] = path62;
        }
        if (parentValue[path62.name] !== path62.value) {
          throw new Error("");
        }
        if (path62.parentPath.get(path62.name) !== path62) {
          throw new Error("");
        }
        return path62;
      }
      Pp.replace = function replace(replacement) {
        var results = [];
        var parentValue = this.parentPath.value;
        var parentCache = getChildCache(this.parentPath);
        var count = arguments.length;
        repairRelationshipWithParent(this);
        if (isArray2.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 hasOwn2 = Object.prototype.hasOwnProperty;
    function scopePlugin(fork) {
      var types4 = fork.use(types_1.default);
      var Type = types4.Type;
      var namedTypes = types4.namedTypes;
      var Node3 = namedTypes.Node;
      var Expression = namedTypes.Expression;
      var isArray2 = types4.builtInTypes.array;
      var b = types4.builders;
      var Scope3 = function Scope4(path62, parentScope) {
        if (!(this instanceof Scope4)) {
          throw new Error("Scope constructor cannot be invoked without 'new'");
        }
        ScopeType.assert(path62.value);
        var depth;
        if (parentScope) {
          if (!(parentScope instanceof Scope4)) {
            throw new Error("");
          }
          depth = parentScope.depth + 1;
        } else {
          parentScope = null;
          depth = 0;
        }
        Object.defineProperties(this, {
          path: { value: path62 },
          node: { value: path62.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);
      Scope3.isEstablishedBy = function(node) {
        return ScopeType.check(node);
      };
      var Sp = Scope3.prototype;
      Sp.didScan = false;
      Sp.declares = function(name) {
        this.scan();
        return hasOwn2.call(this.bindings, name);
      };
      Sp.declaresType = function(name) {
        this.scan();
        return hasOwn2.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] = types4.builders.identifier(name);
      };
      Sp.injectTemporary = function(identifier, init2) {
        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, init2 || 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(path62, bindings, scopeTypes2) {
        var node = path62.value;
        ScopeType.assert(node);
        if (namedTypes.CatchClause.check(node)) {
          var param = path62.get("param");
          if (param.value) {
            addPattern(param, bindings);
          }
        } else {
          recursiveScanScope(path62, bindings, scopeTypes2);
        }
      }
      function recursiveScanScope(path62, bindings, scopeTypes2) {
        var node = path62.value;
        if (path62.parent && namedTypes.FunctionExpression.check(path62.parent.node) && path62.parent.node.id) {
          addPattern(path62.parent.get("id"), bindings);
        }
        if (!node) {
        } else if (isArray2.check(node)) {
          path62.each(function(childPath) {
            recursiveScanChild(childPath, bindings, scopeTypes2);
          });
        } else if (namedTypes.Function.check(node)) {
          path62.get("params").each(function(paramPath) {
            addPattern(paramPath, bindings);
          });
          recursiveScanChild(path62.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(path62.get("id"), scopeTypes2);
        } else if (namedTypes.VariableDeclarator.check(node)) {
          addPattern(path62.get("id"), bindings);
          recursiveScanChild(path62.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.
            path62.get(node.local ? "local" : node.name ? "name" : "id"),
            bindings
          );
        } else if (Node3.check(node) && !Expression.check(node)) {
          types4.eachField(node, function(name, child) {
            var childPath = path62.get(name);
            if (!pathHasValue(childPath, child)) {
              throw new Error("");
            }
            recursiveScanChild(childPath, bindings, scopeTypes2);
          });
        }
      }
      function pathHasValue(path62, value) {
        if (path62.value === value) {
          return true;
        }
        if (Array.isArray(path62.value) && path62.value.length === 0 && Array.isArray(value) && value.length === 0) {
          return true;
        }
        return false;
      }
      function recursiveScanChild(path62, bindings, scopeTypes2) {
        var node = path62.value;
        if (!node || Expression.check(node)) {
        } else if (namedTypes.FunctionDeclaration.check(node) && node.id !== null) {
          addPattern(path62.get("id"), bindings);
        } else if (namedTypes.ClassDeclaration && namedTypes.ClassDeclaration.check(node)) {
          addPattern(path62.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 = hasOwn2.call(bindings, catchParamName);
            recursiveScanScope(path62.get("body"), bindings, scopeTypes2);
            if (!hadBinding) {
              delete bindings[catchParamName];
            }
          }
        } else {
          recursiveScanScope(path62, bindings, scopeTypes2);
        }
      }
      function addPattern(patternPath, bindings) {
        var pattern = patternPath.value;
        namedTypes.Pattern.assert(pattern);
        if (namedTypes.Identifier.check(pattern)) {
          if (hasOwn2.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, types5) {
        var pattern = patternPath.value;
        namedTypes.Pattern.assert(pattern);
        if (namedTypes.Identifier.check(pattern)) {
          if (hasOwn2.call(types5, pattern.name)) {
            types5[pattern.name].push(patternPath);
          } else {
            types5[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 Scope3;
    }
    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 types4 = fork.use(types_1.default);
      var n = types4.namedTypes;
      var b = types4.builders;
      var isNumber = types4.builtInTypes.number;
      var isArray2 = types4.builtInTypes.array;
      var Path = fork.use(path_1.default);
      var Scope3 = 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 pp2 = this.parentPath;
        return pp2 && pp2.node || null;
      };
      NPp._computeParent = function() {
        var value = this.value;
        var pp2 = this.parentPath;
        if (!n.Node.check(value)) {
          while (pp2 && !n.Node.check(pp2.value)) {
            pp2 = pp2.parentPath;
          }
          if (pp2) {
            pp2 = pp2.parentPath;
          }
        }
        while (pp2 && !n.Node.check(pp2.value)) {
          pp2 = pp2.parentPath;
        }
        return pp2 || null;
      };
      NPp._computeScope = function() {
        var value = this.value;
        var pp2 = this.parentPath;
        var scope = pp2 && pp2.scope;
        if (n.Node.check(value) && Scope3.isEstablishedBy(value)) {
          scope = new Scope3(this, scope);
        }
        return scope || null;
      };
      NPp.getValueProperty = function(name) {
        return types4.getFieldValue(this.value, name);
      };
      NPp.needsParens = function(assumeExpressionContext) {
        var pp2 = this.parentPath;
        if (!pp2) {
          return false;
        }
        var node = this.value;
        if (!n.Expression.check(node)) {
          return false;
        }
        if (node.type === "Identifier") {
          return false;
        }
        while (!n.Node.check(pp2.value)) {
          pp2 = pp2.parentPath;
          if (!pp2) {
            return false;
          }
        }
        var parent = pp2.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 (isArray2.check(node)) {
          return node.some(containsCallExpression);
        }
        if (n.Node.check(node)) {
          return types4.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(path62) {
        for (var node, parent; path62.parent; path62 = path62.parent) {
          node = path62.node;
          parent = path62.parent.node;
          if (n.BlockStatement.check(parent) && path62.parent.name === "body" && path62.name === 0) {
            if (parent.body[0] !== node) {
              throw new Error("Nodes must be equal");
            }
            return true;
          }
          if (n.ExpressionStatement.check(parent) && path62.name === "expression") {
            if (parent.expression !== node) {
              throw new Error("Nodes must be equal");
            }
            return true;
          }
          if (n.SequenceExpression.check(parent) && path62.parent.name === "expressions" && path62.name === 0) {
            if (parent.expressions[0] !== node) {
              throw new Error("Nodes must be equal");
            }
            continue;
          }
          if (n.CallExpression.check(parent) && path62.name === "callee") {
            if (parent.callee !== node) {
              throw new Error("Nodes must be equal");
            }
            continue;
          }
          if (n.MemberExpression.check(parent) && path62.name === "object") {
            if (parent.object !== node) {
              throw new Error("Nodes must be equal");
            }
            continue;
          }
          if (n.ConditionalExpression.check(parent) && path62.name === "test") {
            if (parent.test !== node) {
              throw new Error("Nodes must be equal");
            }
            continue;
          }
          if (isBinary(parent) && path62.name === "left") {
            if (parent.left !== node) {
              throw new Error("Nodes must be equal");
            }
            continue;
          }
          if (n.UnaryExpression.check(parent) && !parent.prefix && path62.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 hasOwn2 = Object.prototype.hasOwnProperty;
    function pathVisitorPlugin(fork) {
      var types4 = fork.use(types_1.default);
      var NodePath = fork.use(node_path_1.default);
      var isArray2 = types4.builtInTypes.array;
      var isObject = types4.builtInTypes.object;
      var isFunction = types4.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 = hasOwn2.call(this._methodNameTable, "Block") || hasOwn2.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 = types4.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 (!isObject.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;
        extend2(Vp, methods);
        extend2(Visitor, PathVisitor);
        isFunction.assert(Visitor.fromMethodsObject);
        isFunction.assert(Visitor.visit);
        return new Visitor();
      };
      function extend2(target, source) {
        for (var property in source) {
          if (hasOwn2.call(source, property)) {
            target[property] = source[property];
          }
        }
        return target;
      }
      PathVisitor.visit = function visit2(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(path62) {
        if (this instanceof this.Context) {
          return this.visitor.visitWithoutReset(path62);
        }
        if (!(path62 instanceof NodePath)) {
          throw new Error("");
        }
        var value = path62.value;
        var methodName = value && typeof value === "object" && typeof value.type === "string" && this._methodNameTable[value.type];
        if (methodName) {
          var context = this.acquireContext(path62);
          try {
            return context.invokeVisitorMethod(methodName);
          } finally {
            this.releaseContext(context);
          }
        } else {
          return visitChildren(path62, this);
        }
      };
      function visitChildren(path62, visitor) {
        if (!(path62 instanceof NodePath)) {
          throw new Error("");
        }
        if (!(visitor instanceof PathVisitor)) {
          throw new Error("");
        }
        var value = path62.value;
        if (isArray2.check(value)) {
          path62.each(visitor.visitWithoutReset, visitor);
        } else if (!isObject.check(value)) {
        } else {
          var childNames = types4.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 (!hasOwn2.call(value, childName)) {
              value[childName] = types4.getFieldValue(value, childName);
            }
            childPaths.push(path62.get(childName));
          }
          for (var i = 0; i < childCount; ++i) {
            visitor.visitWithoutReset(childPaths[i]);
          }
        }
        return path62.value;
      }
      PVp.acquireContext = function(path62) {
        if (this._reusableContextStack.length === 0) {
          return new this.Context(path62);
        }
        return this._reusableContextStack.pop().reset(path62);
      };
      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(path62) {
          if (!(this instanceof Context)) {
            throw new Error("");
          }
          if (!(this instanceof PathVisitor)) {
            throw new Error("");
          }
          if (!(path62 instanceof NodePath)) {
            throw new Error("");
          }
          Object.defineProperty(this, "visitor", {
            value: visitor,
            writable: false,
            enumerable: true,
            configurable: false
          });
          this.currentPath = path62;
          this.needToCallTraverse = true;
          Object.seal(this);
        }
        if (!(visitor instanceof PathVisitor)) {
          throw new Error("");
        }
        var Cp = Context.prototype = Object.create(visitor);
        Cp.constructor = Context;
        extend2(Cp, sharedContextProtoMethods);
        return Context;
      }
      var sharedContextProtoMethods = /* @__PURE__ */ Object.create(null);
      sharedContextProtoMethods.reset = function reset3(path62) {
        if (!(this instanceof this.Context)) {
          throw new Error("");
        }
        if (!(path62 instanceof NodePath)) {
          throw new Error("");
        }
        this.currentPath = path62;
        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 path62 = this.currentPath;
        return path62 && path62.value;
      };
      sharedContextProtoMethods.traverse = function traverse(path62, newVisitor) {
        if (!(this instanceof this.Context)) {
          throw new Error("");
        }
        if (!(path62 instanceof NodePath)) {
          throw new Error("");
        }
        if (!(this.currentPath instanceof NodePath)) {
          throw new Error("");
        }
        this.needToCallTraverse = false;
        return visitChildren(path62, PathVisitor.fromMethodsObject(newVisitor || this.visitor));
      };
      sharedContextProtoMethods.visit = function visit2(path62, newVisitor) {
        if (!(this instanceof this.Context)) {
          throw new Error("");
        }
        if (!(path62 instanceof NodePath)) {
          throw new Error("");
        }
        if (!(this.currentPath instanceof NodePath)) {
          throw new Error("");
        }
        this.needToCallTraverse = false;
        return PathVisitor.fromMethodsObject(newVisitor || this.visitor).visitWithoutReset(path62);
      };
      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 types4 = fork.use(types_1.default);
      var getFieldNames = types4.getFieldNames;
      var getFieldValue = types4.getFieldValue;
      var isArray2 = types4.builtInTypes.array;
      var isObject = types4.builtInTypes.object;
      var isDate = types4.builtInTypes.Date;
      var isRegExp = types4.builtInTypes.RegExp;
      var hasOwn2 = Object.prototype.hasOwnProperty;
      function astNodesAreEquivalent(a, b, problemPath) {
        if (isArray2.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 (isArray2.check(a)) {
          return arraysAreEquivalent(a, b, problemPath);
        }
        if (isObject.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) {
        isArray2.assert(a);
        var aLength = a.length;
        if (!isArray2.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) {
        isObject.assert(a);
        if (!isObject.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 (!hasOwn2.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 types4 = fork.use(types_1.default);
      defs.forEach(fork.use);
      types4.finalize();
      var PathVisitor = fork.use(path_visitor_1.default);
      return {
        Type: types4.Type,
        builtInTypes: types4.builtInTypes,
        namedTypes: types4.namedTypes,
        builders: types4.builders,
        defineMethod: types4.defineMethod,
        getFieldNames: types4.getFieldNames,
        getFieldValue: types4.getFieldValue,
        eachField: types4.eachField,
        someField: types4.someField,
        getSupertypeNames: types4.getSupertypeNames,
        getBuilderName: types4.getBuilderName,
        astNodesAreEquivalent: fork.use(equiv_1.default),
        finalize: types4.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(plugin2) {
        var idx = used.indexOf(plugin2);
        if (idx === -1) {
          idx = used.length;
          used.push(plugin2);
          usedResult[idx] = plugin2(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 types4 = fork.use(types_1.default);
      var Type = types4.Type;
      var builtin = types4.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 types4 = fork.use(types_1.default);
      var Type = types4.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 types4 = fork.use(types_1.default);
      var def = types4.Type.def;
      var or = types4.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 types4 = fork.use(types_1.default);
      var def = types4.Type.def;
      var or = types4.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 types4 = fork.use(types_1.default);
      var def = types4.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 types4 = fork.use(types_1.default);
      var def = types4.Type.def;
      var or = types4.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 types4 = fork.use(types_1.default);
      var def = types4.Type.def;
      var or = types4.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 types4 = fork.use(types_1.default);
      var def = types4.Type.def;
      var or = types4.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 types4 = fork.use(types_1.default);
      var defaults = fork.use(shared_1.default).defaults;
      var def = types4.Type.def;
      var or = types4.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 types4 = fork.use(types_1.default);
      var defaults = fork.use(shared_1.default).defaults;
      var def = types4.Type.def;
      var or = types4.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 types4 = fork.use(types_1.default);
      var n = types4.namedTypes;
      var def = types4.Type.def;
      var or = types4.Type.or;
      var defaults = fork.use(shared_1.default).defaults;
      var StringLiteral = types4.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 types4 = fork.use(types_1.default);
      var Type = types4.Type;
      var def = types4.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 _a = 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 = _a.astNodesAreEquivalent;
    var builders = _a.builders;
    var builtInTypes = _a.builtInTypes;
    var defineMethod = _a.defineMethod;
    var eachField = _a.eachField;
    var finalize = _a.finalize;
    var getBuilderName = _a.getBuilderName;
    var getFieldNames = _a.getFieldNames;
    var getFieldValue = _a.getFieldValue;
    var getSupertypeNames = _a.getSupertypeNames;
    var n = _a.namedTypes;
    var NodePath = _a.NodePath;
    var Path = _a.Path;
    var PathVisitor = _a.PathVisitor;
    var someField = _a.someField;
    var Type = _a.Type;
    var use = _a.use;
    var visit2 = _a.visit;
    exports2.astNodesAreEquivalent = astNodesAreEquivalent;
    exports2.builders = builders;
    exports2.builtInTypes = builtInTypes;
    exports2.defineMethod = defineMethod;
    exports2.eachField = eachField;
    exports2.finalize = finalize;
    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 = visit2;
    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(path62) {
            if (path62.node.declarations) {
              for (let i = 0; i < path62.node.declarations.length; i++) {
                const declaration = path62.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(path62) {
            if (ast_types_1.namedTypes.Identifier.check(path62.node.left) && ast_types_1.namedTypes.Identifier.check(path62.node.right) && checkName(path62.node.right.name, names) && !checkName(path62.node.left.name, names)) {
              names.push(path62.node.left.name);
            }
            return false;
          },
          visitFunction(path62) {
            if (path62.node.id) {
              let shouldDegenerate = false;
              (0, ast_types_1.visit)(path62.node, {
                visitCallExpression(path63) {
                  if (checkNames(path63.node, names)) {
                    shouldDegenerate = true;
                  }
                  return false;
                }
              });
              if (!shouldDegenerate) {
                return false;
              }
              path62.node.async = true;
              if (!checkName(path62.node.id.name, names)) {
                names.push(path62.node.id.name);
              }
            }
            this.traverse(path62);
          }
        });
      } while (lastNamesLength !== names.length);
      (0, ast_types_1.visit)(ast, {
        visitCallExpression(path62) {
          if (checkNames(path62.node, names)) {
            const delegate = false;
            const { name, parent: { node: pNode } } = path62;
            const expr = ast_types_1.builders.awaitExpression(path62.node, delegate);
            if (ast_types_1.namedTypes.CallExpression.check(pNode)) {
              pNode.arguments[name] = expr;
            } else {
              pNode[name] = expr;
            }
          }
          this.traverse(path62);
        }
      });
      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 r2 = 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(r2, "toString", {
        value: () => compiled,
        enumerable: false
      });
      return r2;
    }
    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 promise = vm.newPromise();
        promise.settled.then(vm.runtime.executePendingJobs);
        val.then((r2) => {
          promise.resolve(hostToQuickJSHandle(vm, r2));
        }, (err) => {
          promise.reject(hostToQuickJSHandle(vm, err));
        });
        return promise.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_dist7 = __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, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __exportStar2 = exports2 && exports2.__exportStar || function(m2, exports3) {
      for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m2, p);
    };
    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, domain) {
      host = String(host);
      domain = String(domain);
      return host.substr(domain.length * -1) === domain;
    }
    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((resolve6, reject) => {
        (0, dns_1.lookup)(host, opts, (err, res) => {
          if (err) {
            reject(err);
          } else {
            resolve6(res);
          }
        });
      });
    }
    exports2.dnsLookup = dnsLookup;
    function isGMT(v2) {
      return v2 === "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 r2 = await (0, util_1.dnsLookup)(host, { family });
        if (typeof r2 === "string") {
          return r2;
        }
      } 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, c, d2;
        a = (long & 255 << 24) >>> 24;
        b = (long & 255 << 16) >>> 16;
        c = (long & 255 << 8) >>> 8;
        d2 = long & 255;
        return [a, b, c, d2].join(".");
      };
      ip2long = function(ip) {
        var b, c, i, j, n, ref2;
        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);
          }
          ref2 = atob2(ip), n = ref2[0], c = ref2[1];
          ip = ip.substring(c);
          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 base2, dmax, i, n, start;
        n = 0;
        base2 = 10;
        dmax = "9";
        i = 0;
        if (s.length > 1 && s[i] === "0") {
          if (s[i + 1] === "x" || s[i + 1] === "X") {
            i += 2;
            base2 = 16;
          } else if ("0" <= s[i + 1] && s[i + 1] <= "9") {
            i++;
            base2 = 8;
            dmax = "7";
          }
        }
        start = i;
        while (i < s.length) {
          if ("0" <= s[i] && s[i] <= dmax) {
            n = n * base2 + (chr(s[i]) - chr0) >>> 0;
          } else if (base2 === 16) {
            if ("a" <= s[i] && s[i] <= "f") {
              n = n * base2 + (10 + chr(s[i]) - chra) >>> 0;
            } else if ("A" <= s[i] && s[i] <= "F") {
              n = n * base2 + (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 error, i, j, ref2;
          if (typeof net3 !== "string") {
            throw new Error("Missing `net' parameter");
          }
          if (!mask) {
            ref2 = net3.split("/", 2), net3 = ref2[0], mask = ref2[1];
          }
          if (!mask) {
            mask = 32;
          }
          if (typeof mask === "string" && mask.indexOf(".") > -1) {
            try {
              this.maskLong = ip2long(mask);
            } catch (error1) {
              error = 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) {
            error = 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((resolve6, reject) => {
        const socket = net_1.default.connect({ host: "8.8.8.8", port: 53 });
        const onError = () => {
          resolve6(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") {
            resolve6(addr);
          } else if (addr.address) {
            resolve6(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(v2) {
      if (!v2)
        return false;
      return weekdays.includes(v2);
    }
  }
});

// ../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/index.js
var require_dist8 = __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_dist7();
    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(url38, _host) {
        const urlObj = typeof url38 === "string" ? new URL(url38) : url38;
        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(v2) {
      if (typeof v2 !== "function")
        return false;
      if (v2.constructor.name === "AsyncFunction")
        return true;
      if (String(v2).indexOf("__awaiter(") !== -1)
        return true;
      return Boolean(v2.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)), (error) => handleNextStep(gen.throw(error)));
        }
        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(map) {
        this.assertAlive();
        const result = map(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 (error) {
        disposeError = error;
      }
      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 Scope3 = 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 (error) {
          blockError = error;
          throw error;
        } 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 (error) {
            blockError = error;
            throw error;
          } 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 (error) {
          blockError = error;
          throw error;
        } 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 = Scope3;
  }
});

// ../../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((resolve6) => {
          this.onSettled = resolve6;
        });
        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(string) {
        const numBytes = this.module.lengthBytesUTF8(string) + 1;
        const ptr = this.module._malloc(numBytes);
        this.module.stringToUTF8(string, 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 (error) {
                return this.errorToHandle(error).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, (error) => error instanceof lifetime_1.Lifetime ? deferredPromise.reject(error) : this.newError(error).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(error) {
        const errorHandle = this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));
        if (error && typeof error === "object") {
          if (error.name !== void 0) {
            this.newString(error.name).consume((handle) => this.setProp(errorHandle, "name", handle));
          }
          if (error.message !== void 0) {
            this.newString(error.message).consume((handle) => this.setProp(errorHandle, "message", handle));
          }
        } else if (typeof error === "string") {
          this.newString(error).consume((handle) => this.setProp(errorHandle, "message", handle));
        } else if (error !== void 0) {
          this.newString(String(error)).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((resolve6) => {
          lifetime_1.Scope.withScope((scope) => {
            const resolveHandle = scope.manage(this.newFunction("resolve", (value) => {
              resolve6({ value: value && value.dup() });
            }));
            const rejectHandle = scope.manage(this.newFunction("reject", (error) => {
              resolve6({ error: error && error.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 set = 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, set.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(error) {
        return this.errorToHandle(error).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((error) => this.dump(error));
          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(error) {
        if (error instanceof lifetime_1.Lifetime) {
          return error;
        }
        return this.newError(error);
      }
    };
    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, moduleName2) {
            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(moduleName2, 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 (error) {
              (0, debug_1.debugLog)("cToHostLoadModule: caught error", error);
              context.throw(error);
              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 (error) {
              (0, debug_1.debugLog)("normalizeModule: caught error", error);
              context.throw(error);
              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 error = Object.assign(resultValue, { context });
          return {
            error
          };
        }
      }
      /**
       * 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 (error) {
              console.error("[C to host error: returning null]", error);
              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 (error) {
              console.error("[C to host interrupt: returning error]", error);
              return 1;
            }
          }),
          loadModuleSource: (asyncify, rt, ctx, moduleName2) => 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, moduleName2);
            } catch (error) {
              console.error("[C to host module loader error: returning null]", error);
              return 0;
            }
          }),
          normalizeModule: (asyncify, rt, ctx, moduleBaseName, moduleName2) => 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, moduleName2);
            } catch (error) {
              console.error("[C to host module loader error: returning null]", error);
              return 0;
            }
          })
        });
        this.module = module3;
        this.module.callbacks = this.cToHostCallbacks;
      }
      setRuntimeCallbacks(rt, callbacks) {
        this.runtimeCallbacks.set(rt, callbacks);
      }
      deleteRuntime(rt) {
        this.runtimeCallbacks.delete(rt);
      }
      setContextCallbacks(ctx, callbacks) {
        this.contextCallbacks.set(ctx, callbacks);
      }
      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);
              }, (error) => {
                (0, debug_1.debugLog)("asyncify.handleSleep: rejected:", error);
                console.error("QuickJS: cannot handle error in suspended function", error);
                this.suspended = void 0;
              });
            } catch (error) {
              (0, debug_1.debugLog)("asyncify.handleSleep: error:", error);
              this.suspended = void 0;
              throw error;
            }
          });
        }
        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 error = vm.dump(scope.manage(result.error));
            throw error;
          }
          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 (error) {
          (0, debug_1.debugLog)("QTS_Eval_MaybeAsync threw", error);
          throw error;
        }
        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_dist9();
    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 error = vm.dump(scope.manage(result.error));
            throw error;
          }
          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 m2, n;
        a.ready = new Promise(function(b, c) {
          m2 = b;
          n = c;
        });
        var p = Object.assign({}, a), t = "./this.program", u = "object" == typeof window, v2 = "function" == typeof importScripts, w2 = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, x2 = "", y, z2, A;
        if (w2) {
          var fs60 = require("fs"), B = require("path");
          x2 = v2 ? B.dirname(x2) + "/" : __dirname + "/";
          y = (b, c) => {
            var d2 = C(b);
            if (d2)
              return c ? d2 : d2.toString();
            b = b.startsWith("file://") ? new URL(b) : B.normalize(b);
            return fs60.readFileSync(b, c ? void 0 : "utf8");
          };
          A = (b) => {
            b = y(b, true);
            b.buffer || (b = new Uint8Array(b));
            return b;
          };
          z2 = (b, c, d2) => {
            var e = C(b);
            e && c(e);
            b = b.startsWith("file://") ? new URL(b) : B.normalize(b);
            fs60.readFile(b, function(f, g) {
              f ? d2(f) : c(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 (u || v2)
          v2 ? x2 = self.location.href : "undefined" != typeof document && document.currentScript && (x2 = document.currentScript.src), _scriptDir && (x2 = _scriptDir), 0 !== x2.indexOf("blob:") ? x2 = x2.substr(0, x2.replace(/[?#].*/, "").lastIndexOf("/") + 1) : x2 = "", y = (b) => {
            try {
              var c = new XMLHttpRequest();
              c.open("GET", b, false);
              c.send(null);
              return c.responseText;
            } catch (f) {
              if (b = C(b)) {
                c = [];
                for (var d2 = 0; d2 < b.length; d2++) {
                  var e = b[d2];
                  255 < e && (e &= 255);
                  c.push(String.fromCharCode(e));
                }
                return c.join("");
              }
              throw f;
            }
          }, v2 && (A = (b) => {
            try {
              var c = new XMLHttpRequest();
              c.open("GET", b, false);
              c.responseType = "arraybuffer";
              c.send(null);
              return new Uint8Array(c.response);
            } catch (d2) {
              if (b = C(b))
                return b;
              throw d2;
            }
          }), z2 = (b, c, d2) => {
            var e = new XMLHttpRequest();
            e.open("GET", b, true);
            e.responseType = "arraybuffer";
            e.onload = () => {
              if (200 == e.status || 0 == e.status && e.response)
                c(e.response);
              else {
                var f = C(b);
                f ? c(f.buffer) : d2();
              }
            };
            e.onerror = d2;
            e.send(null);
          };
        var aa = a.print || console.log.bind(console), D = a.printErr || console.warn.bind(console);
        Object.assign(a, p);
        p = null;
        a.thisProgram && (t = a.thisProgram);
        var E;
        a.wasmBinary && (E = a.wasmBinary);
        var noExitRuntime = a.noExitRuntime || true;
        "object" != typeof WebAssembly && F("no native wasm support detected");
        var G2, H2 = false, I, J, K, L2;
        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 = L2 = 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);
          H2 = 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, x2) : x2 + fa;
        }
        function ha(b) {
          try {
            if (b == R && E)
              return new Uint8Array(E);
            var c = C(b);
            if (c)
              return c;
            if (A)
              return A(b);
            throw "both async and sync fetching of the wasm failed";
          } catch (d2) {
            F(d2);
          }
        }
        function ia(b) {
          if (!E && (u || v2)) {
            if ("function" == typeof fetch && !b.startsWith("file://"))
              return fetch(b, { credentials: "same-origin" }).then(function(c) {
                if (!c.ok)
                  throw "failed to load wasm binary file at '" + b + "'";
                return c.arrayBuffer();
              }).catch(function() {
                return ha(b);
              });
            if (z2)
              return new Promise(function(c, d2) {
                z2(b, function(e) {
                  c(new Uint8Array(e));
                }, d2);
              });
          }
          return Promise.resolve().then(function() {
            return ha(b);
          });
        }
        function ja(b, c, d2) {
          return ia(b).then(function(e) {
            return WebAssembly.instantiate(e, c);
          }).then(function(e) {
            return e;
          }).then(d2, function(e) {
            D("failed to asynchronously prepare wasm: " + e);
            F(e);
          });
        }
        function ka(b, c) {
          var d2 = R;
          return E || "function" != typeof WebAssembly.instantiateStreaming || d2.startsWith(Q2) || d2.startsWith("file://") || w2 || "function" != typeof fetch ? ja(d2, b, c) : fetch(d2, { credentials: "same-origin" }).then(function(e) {
            return WebAssembly.instantiateStreaming(e, b).then(c, function(f) {
              D("wasm streaming compile failed: " + f);
              D("falling back to ArrayBuffer instantiation");
              return ja(d2, b, c);
            });
          });
        }
        function S(b) {
          for (; 0 < b.length; )
            b.shift()(a);
        }
        var la = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0;
        function na(b, c, d2) {
          var e = c + d2;
          for (d2 = c; b[d2] && !(d2 >= e); )
            ++d2;
          if (16 < d2 - c && b.buffer && la)
            return la.decode(b.subarray(c, d2));
          for (e = ""; c < d2; ) {
            var f = b[c++];
            if (f & 128) {
              var g = b[c++] & 63;
              if (192 == (f & 224))
                e += String.fromCharCode((f & 31) << 6 | g);
              else {
                var h2 = b[c++] & 63;
                f = 224 == (f & 240) ? (f & 15) << 12 | g << 6 | h2 : (f & 7) << 18 | g << 12 | h2 << 6 | b[c++] & 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 T2(b, c) {
          return b ? na(J, b, c) : "";
        }
        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 U2(b) {
          for (var c = 0, d2 = 0; d2 < b.length; ++d2) {
            var e = b.charCodeAt(d2);
            127 >= e ? c++ : 2047 >= e ? c += 2 : 55296 <= e && 57343 >= e ? (c += 4, ++d2) : c += 3;
          }
          return c;
        }
        function V(b, c, d2) {
          var e = J;
          if (!(0 < d2))
            return 0;
          var f = c;
          d2 = c + d2 - 1;
          for (var g = 0; g < b.length; ++g) {
            var h2 = b.charCodeAt(g);
            if (55296 <= h2 && 57343 >= h2) {
              var k = b.charCodeAt(++g);
              h2 = 65536 + ((h2 & 1023) << 10) | k & 1023;
            }
            if (127 >= h2) {
              if (c >= d2)
                break;
              e[c++] = h2;
            } else {
              if (2047 >= h2) {
                if (c + 1 >= d2)
                  break;
                e[c++] = 192 | h2 >> 6;
              } else {
                if (65535 >= h2) {
                  if (c + 2 >= d2)
                    break;
                  e[c++] = 224 | h2 >> 12;
                } else {
                  if (c + 3 >= d2)
                    break;
                  e[c++] = 240 | h2 >> 18;
                  e[c++] = 128 | h2 >> 12 & 63;
                }
                e[c++] = 128 | h2 >> 6 & 63;
              }
              e[c++] = 128 | h2 & 63;
            }
          }
          e[c] = 0;
          return c - f;
        }
        function qa(b) {
          var c = U2(b) + 1, d2 = ra(c);
          d2 && V(b, d2, c);
          return d2;
        }
        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" }, c;
            for (c in W)
              void 0 === W[c] ? delete b[c] : b[c] = W[c];
            var d2 = [];
            for (c in b)
              d2.push(c + "=" + b[c]);
            X = d2;
          }
          return X;
        }
        var X, ta = [null, [], []];
        function ua(b, c, d2, e) {
          var f = { string: (l) => {
            var q2 = 0;
            if (null !== l && void 0 !== l && 0 !== l) {
              q2 = U2(l) + 1;
              var ma = Y(q2);
              V(l, ma, q2);
              q2 = ma;
            }
            return q2;
          }, array: (l) => {
            var q2 = Y(l.length);
            I.set(l, q2);
            return q2;
          } };
          b = a["_" + b];
          var g = [], h2 = 0;
          if (e)
            for (var k = 0; k < e.length; k++) {
              var r2 = f[d2[k]];
              r2 ? (0 === h2 && (h2 = va()), g[k] = r2(e[k])) : g[k] = e[k];
            }
          d2 = b.apply(null, g);
          return d2 = (function(l) {
            0 !== h2 && wa(h2);
            return "string" === c ? T2(l) : "boolean" === c ? !!l : l;
          })(d2);
        }
        var xa = "function" == typeof atob ? atob : function(b) {
          var c = "", d2 = 0;
          b = b.replace(/[^A-Za-z0-9\+\/=]/g, "");
          do {
            var e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(b.charAt(d2++));
            var f = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(b.charAt(d2++));
            var g = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(b.charAt(d2++));
            var h2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(b.charAt(d2++));
            e = e << 2 | f >> 4;
            f = (f & 15) << 4 | g >> 2;
            var k = (g & 3) << 6 | h2;
            c += String.fromCharCode(e);
            64 !== g && (c += String.fromCharCode(f));
            64 !== h2 && (c += String.fromCharCode(k));
          } while (d2 < b.length);
          return c;
        };
        function C(b) {
          if (b.startsWith(Q2)) {
            b = b.slice(Q2.length);
            if ("boolean" == typeof w2 && w2) {
              var c = Buffer.from(b, "base64");
              c = new Uint8Array(c.buffer, c.byteOffset, c.byteLength);
            } else
              try {
                var d2 = xa(b), e = new Uint8Array(d2.length);
                for (b = 0; b < d2.length; ++b)
                  e[b] = d2.charCodeAt(b);
                c = e;
              } catch (f) {
                throw Error("Converting base64 string to bytes failed.");
              }
            return c;
          }
        }
        var ya = {
          a: function(b, c, d2, e) {
            F("Assertion failed: " + T2(b) + ", at: " + [c ? T2(c) : "unknown filename", d2, e ? T2(e) : "unknown function"]);
          },
          l: function(b, c) {
            b = new Date(1e3 * (L2[b >> 2] + 4294967296 * K[b + 4 >> 2]));
            K[c >> 2] = b.getSeconds();
            K[c + 4 >> 2] = b.getMinutes();
            K[c + 8 >> 2] = b.getHours();
            K[c + 12 >> 2] = b.getDate();
            K[c + 16 >> 2] = b.getMonth();
            K[c + 20 >> 2] = b.getFullYear() - 1900;
            K[c + 24 >> 2] = b.getDay();
            var d2 = b.getFullYear();
            K[c + 28 >> 2] = (0 !== d2 % 4 || 0 === d2 % 100 && 0 !== d2 % 400 ? pa : oa)[b.getMonth()] + b.getDate() - 1 | 0;
            K[c + 36 >> 2] = -(60 * b.getTimezoneOffset());
            d2 = new Date(b.getFullYear(), 6, 1).getTimezoneOffset();
            var e = new Date(b.getFullYear(), 0, 1).getTimezoneOffset();
            K[c + 32 >> 2] = (d2 != e && b.getTimezoneOffset() == Math.min(e, d2)) | 0;
          },
          k: function(b, c, d2) {
            function e(r2) {
              return (r2 = r2.toTimeString().match(/\(([A-Za-z ]+)\)$/)) ? r2[1] : "GMT";
            }
            var f = (/* @__PURE__ */ new Date()).getFullYear(), g = new Date(f, 0, 1), h2 = new Date(f, 6, 1);
            f = g.getTimezoneOffset();
            var k = h2.getTimezoneOffset();
            L2[b >> 2] = 60 * Math.max(f, k);
            K[c >> 2] = Number(f != k);
            b = e(g);
            c = e(h2);
            b = qa(b);
            c = qa(c);
            k < f ? (L2[d2 >> 2] = b, L2[d2 + 4 >> 2] = c) : (L2[d2 >> 2] = c, L2[d2 + 4 >> 2] = b);
          },
          b: function() {
            F("");
          },
          m: function() {
            return Date.now();
          },
          j: function(b) {
            var c = J.length;
            b >>>= 0;
            if (2147483648 < b)
              return false;
            for (var d2 = 1; 4 >= d2; d2 *= 2) {
              var e = c * (1 + 0.2 / d2);
              e = Math.min(e, b + 100663296);
              var f = Math, g = f.min;
              e = Math.max(b, e);
              e += (65536 - e % 65536) % 65536;
              a: {
                var h2 = G2.buffer;
                try {
                  G2.grow(g.call(f, 2147483648, e) - h2.byteLength + 65535 >>> 16);
                  M2();
                  var k = 1;
                  break a;
                } catch (r2) {
                }
                k = void 0;
              }
              if (k)
                return true;
            }
            return false;
          },
          e: function(b, c) {
            var d2 = 0;
            sa().forEach(function(e, f) {
              var g = c + d2;
              f = L2[b + 4 * f >> 2] = g;
              for (g = 0; g < e.length; ++g)
                I[f++ >> 0] = e.charCodeAt(g);
              I[f >> 0] = 0;
              d2 += e.length + 1;
            });
            return 0;
          },
          f: function(b, c) {
            var d2 = sa();
            L2[b >> 2] = d2.length;
            var e = 0;
            d2.forEach(function(f) {
              e += f.length + 1;
            });
            L2[c >> 2] = e;
            return 0;
          },
          d: function() {
            return 52;
          },
          i: function() {
            return 70;
          },
          c: function(b, c, d2, e) {
            for (var f = 0, g = 0; g < d2; g++) {
              var h2 = L2[c >> 2], k = L2[c + 4 >> 2];
              c += 8;
              for (var r2 = 0; r2 < k; r2++) {
                var l = J[h2 + r2], q2 = ta[b];
                0 === l || 10 === l ? ((1 === b ? aa : D)(na(q2, 0)), q2.length = 0) : q2.push(l);
              }
              f += k;
            }
            L2[e >> 2] = f;
            return 0;
          },
          o: function(b, c, d2, e, f) {
            return a.callbacks.callFunction(void 0, b, c, d2, e, f);
          },
          n: function(b) {
            return a.callbacks.shouldInterrupt(void 0, b);
          },
          h: function(b, c, d2) {
            d2 = T2(d2);
            return a.callbacks.loadModuleSource(void 0, b, c, d2);
          },
          g: function(b, c, d2, e) {
            d2 = T2(d2);
            e = T2(e);
            return a.callbacks.normalizeModule(void 0, b, c, d2, e);
          }
        };
        (function() {
          function b(d2) {
            d2 = d2.exports;
            a.asm = d2;
            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 d2;
          }
          var c = { a: ya };
          N++;
          a.monitorRunDependencies && a.monitorRunDependencies(N);
          if (a.instantiateWasm)
            try {
              return a.instantiateWasm(c, b);
            } catch (d2) {
              D("Module.instantiateWasm callback failed with error: " + d2), n(d2);
            }
          ka(c, function(d2) {
            b(d2.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 Y() {
          return (Y = a.asm.ua).apply(null, arguments);
        }
        a.___start_em_js = 74916;
        a.___stop_em_js = 75818;
        a.cwrap = function(b, c, d2, e) {
          var f = !d2 || d2.every((g) => "number" === g || "boolean" === g);
          return "string" !== c && f && !e ? a["_" + b] : function() {
            return ua(b, c, d2, arguments);
          };
        };
        a.UTF8ToString = T2;
        a.stringToUTF8 = function(b, c, d2) {
          return V(b, c, d2);
        };
        a.lengthBytesUTF8 = U2;
        var Z2;
        P = function za() {
          Z2 || Aa();
          Z2 || (P = za);
        };
        function Aa() {
          function b() {
            if (!Z2 && (Z2 = true, a.calledRun = true, !H2)) {
              S(ca);
              m2(a);
              if (a.onRuntimeInitialized)
                a.onRuntimeInitialized();
              if (a.postRun)
                for ("function" == typeof a.postRun && (a.postRun = [a.postRun]); a.postRun.length; ) {
                  var c = a.postRun.shift();
                  da.unshift(c);
                }
              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, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    }) : function(o, v2) {
      o["default"] = v2;
    });
    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 promise;
      return () => {
        return promise ?? (promise = 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((d2) => {
          if (d2.alive) {
            d2.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_dist9 = __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, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    }) : function(o, v2) {
      o["default"] = v2;
    });
    var __exportStar2 = exports2 && exports2.__exportStar || function(m2, exports3) {
      for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m2, p);
    };
    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_dist10 = __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, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    }) : function(o, v2) {
      o["default"] = v2;
    });
    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 crypto7 = __importStar2(require("crypto"));
    var events_1 = require("events");
    var debug_1 = __importDefault2(require_src2());
    var url_1 = require("url");
    var agent_base_1 = require_dist();
    var get_uri_1 = require_dist6();
    var pac_resolver_1 = require_dist8();
    var quickjs_emscripten_1 = require_dist9();
    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 hash = crypto7.createHash("sha1").update(code).digest("hex");
          if (this.resolver && this.resolverHash === hash) {
            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 = hash;
          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 url38 = Object.assign(new url_1.URL(req.path, `${protocol}//${host}`), defaultPort ? void 0 : { port: opts.port });
        debug4("url: %s", url38);
        let result = await resolver(url38);
        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_dist4()));
            agent = new SocksProxyAgent(`socks://${target}`, this.opts);
          } else if (type === "SOCKS4") {
            const { SocksProxyAgent } = await Promise.resolve().then(() => __importStar2(require_dist4()));
            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_dist3()));
              agent = new HttpsProxyAgent(proxyURL, this.opts);
            } else {
              const { HttpProxyAgent } = await Promise.resolve().then(() => __importStar2(require_dist2()));
              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_dist11 = __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, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    }) : function(o, v2) {
      o["default"] = v2;
    });
    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_dist();
    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_dist2()))).HttpProxyAgent,
      https: async () => (await Promise.resolve().then(() => __importStar2(require_dist3()))).HttpsProxyAgent,
      socks: async () => (await Promise.resolve().then(() => __importStar2(require_dist4()))).SocksProxyAgent,
      pac: async () => (await Promise.resolve().then(() => __importStar2(require_dist10()))).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(v2) {
      return Object.keys(exports2.proxies).includes(v2);
    }
    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 url38 = new url_1.URL(req.path, `${protocol}//${host}`).href;
        const proxy = await this.getProxyForUrl(url38, req);
        if (!proxy) {
          debug4("Proxy not enabled for URL: %o", url38);
          return secureEndpoint ? this.httpsAgent : this.httpAgent;
        }
        debug4("Request URL: %o", url38);
        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 fs60 = 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 (!fs60) return false;
      return (stream instanceof (fs60.ReadStream || noop) || stream instanceof (fs60.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 pipe = 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 error;
      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 (!error) error = err;
          if (err) destroys.forEach(call);
          if (reading) return;
          destroys.forEach(call);
          callback(error);
        });
      });
      return streams.reduce(pipe);
    };
    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 } = options;
      let { encoding } = options;
      const isBuffer = encoding === "buffer";
      let objectMode = false;
      if (array) {
        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 (array) {
          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((resolve6, reject) => {
        const rejectPromise = (error) => {
          if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) {
            error.bufferedData = stream.getBufferedValue();
          }
          reject(error);
        };
        stream = pump(inputStream, bufferStream(options), (error) => {
          if (error) {
            rejectPromise(error);
            return;
          }
          resolve6();
        });
        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 called = false;
      return onCb;
      function onCb(err) {
        if (called) throw new Error("callback called twice");
        called = 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 fs60 = require("fs");
    var util6 = require("util");
    var stream = require("stream");
    var Readable4 = 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;
    util6.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, offset2, length, position, callback) {
      var self2 = this;
      self2.pend.go(function(cb) {
        fs60.read(self2.fd, buffer, offset2, length, position, function(err, bytesRead, buffer2) {
          cb();
          callback(err, bytesRead, buffer2);
        });
      });
    };
    FdSlicer.prototype.write = function(buffer, offset2, length, position, callback) {
      var self2 = this;
      self2.pend.go(function(cb) {
        fs60.write(self2.fd, buffer, offset2, 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) {
        fs60.close(self2.fd, onCloseDone);
      }
      function onCloseDone(err) {
        if (err) {
          self2.emit("error", err);
        } else {
          self2.emit("close");
        }
      }
    };
    util6.inherits(ReadStream, Readable4);
    function ReadStream(context, options) {
      options = options || {};
      Readable4.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);
        fs60.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();
    };
    util6.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();
        fs60.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();
    };
    util6.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, offset2, length, position, callback) {
      var end = position + length;
      var delta = end - this.buffer.length;
      var written = delta > 0 ? delta : length;
      this.buffer.copy(buffer, offset2, position, end);
      setImmediate(function() {
        callback(null, written);
      });
    };
    BufferSlicer.prototype.write = function(buffer, offset2, length, position, callback) {
      buffer.copy(this.buffer, position, offset2, offset2 + 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 offset2 = 0;
      while (true) {
        var nextOffset = offset2 + this.maxChunkSize;
        if (nextOffset >= entireSlice.length) {
          if (offset2 < entireSlice.length) {
            readStream.write(entireSlice.slice(offset2, entireSlice.length));
          }
          break;
        }
        readStream.write(entireSlice.slice(offset2, nextOffset));
        offset2 = 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 Buffer5 = 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 (Buffer5.isBuffer(input)) {
        return input;
      }
      var hasNewBufferAPI = typeof Buffer5.alloc === "function" && typeof Buffer5.from === "function";
      if (typeof input === "number") {
        return hasNewBufferAPI ? Buffer5.alloc(input) : new Buffer5(input);
      } else if (typeof input === "string") {
        return hasNewBufferAPI ? Buffer5.from(input) : new Buffer5(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 (Buffer5.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 fs60 = require("fs");
    var zlib2 = require("zlib");
    var fd_slicer = require_fd_slicer();
    var crc32 = require_buffer_crc32();
    var util6 = require("util");
    var EventEmitter2 = require("events").EventEmitter;
    var Transform2 = require("stream").Transform;
    var PassThrough = require("stream").PassThrough;
    var Writable = require("stream").Writable;
    exports2.open = open2;
    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 open2(path62, 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;
      fs60.open(path62, "r", function(err, fd) {
        if (err) return callback(err);
        fromFd(fd, options, function(err2, zipfile) {
          if (err2) fs60.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;
      fs60.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"));
      });
    }
    util6.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(date, time) {
      var day = date & 31;
      var month = (date >> 5 & 15) - 1;
      var year = (date >> 9 & 127) + 1980;
      var millisecond = 0;
      var second = (time & 31) * 2;
      var minute = time >> 5 & 63;
      var hour = time >> 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, offset2, length, position, callback) {
      if (length === 0) {
        return setImmediate(function() {
          callback(null, newBuffer(0));
        });
      }
      reader.read(buffer, offset2, length, position, function(err, bytesRead) {
        if (err) return callback(err);
        if (bytesRead < length) {
          return callback(new Error("unexpected EOF"));
        }
        callback();
      });
    }
    util6.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();
    };
    util6.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, offset2, 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, offset2 + written, 0, chunk.length);
        written += chunk.length;
        cb();
      };
      writeStream.on("finish", callback);
      readStream.on("error", function(error) {
        callback(error);
      });
      readStream.pipe(writeStream);
    };
    RandomAccessReader.prototype.close = function(callback) {
      setImmediate(callback);
    };
    util6.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, offset2) {
      var lower32 = buffer.readUInt32LE(offset2);
      var upper32 = buffer.readUInt32LE(offset2 + 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: fs60 } = require("fs");
    var getStream = require_get_stream();
    var path62 = require("path");
    var { promisify } = require("util");
    var stream = require("stream");
    var yauzl = require_yauzl();
    var openZip = promisify(yauzl.open);
    var pipeline = promisify(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((resolve6, 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");
              resolve6();
            }
          });
          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 = path62.dirname(path62.join(this.opts.dir, entry.fileName));
            try {
              await fs60.mkdir(destDir, { recursive: true });
              const canonicalDestDir = await fs60.realpath(destDir);
              const relativeDestDir = path62.relative(this.opts.dir, canonicalDestDir);
              if (relativeDestDir.split(path62.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 = path62.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 : path62.dirname(dest);
        const mkdirOptions = { recursive: true };
        if (isDir) {
          mkdirOptions.mode = procMode;
        }
        debug4("mkdir", { dir: destDir, ...mkdirOptions });
        await fs60.mkdir(destDir, mkdirOptions);
        if (isDir) return;
        debug4("opening read stream", dest);
        const readStream = await promisify(this.zipfile.openReadStream.bind(this.zipfile))(entry);
        if (symlink) {
          const link = await getStream(readStream);
          debug4("creating symlink", link, dest);
          await fs60.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 (!path62.isAbsolute(opts.dir)) {
        throw new Error("Target directory is expected to be absolute");
      }
      await fs60.mkdir(opts.dir, { recursive: true });
      opts.dir = await fs60.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(data2) {
        if (this.buffer[this.top] !== void 0) return false;
        this.buffer[this.top] = data2;
        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(string, encoding) {
      return Buffer.byteLength(string, 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, offset2, end, encoding) {
      return toBuffer(buffer).fill(value, offset2, 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 toString2(buffer, encoding, start, end) {
      return toBuffer(buffer).toString(encoding, start, end);
    }
    function write(buffer, string, offset2, length, encoding) {
      return toBuffer(buffer).write(string, offset2, length, encoding);
    }
    function writeDoubleLE(buffer, value, offset2) {
      return toBuffer(buffer).writeDoubleLE(value, offset2);
    }
    function writeFloatLE(buffer, value, offset2) {
      return toBuffer(buffer).writeFloatLE(value, offset2);
    }
    function writeUInt32LE(buffer, value, offset2) {
      return toBuffer(buffer).writeUInt32LE(value, offset2);
    }
    function writeInt32LE(buffer, value, offset2) {
      return toBuffer(buffer).writeInt32LE(value, offset2);
    }
    function readDoubleLE(buffer, offset2) {
      return toBuffer(buffer).readDoubleLE(offset2);
    }
    function readFloatLE(buffer, offset2) {
      return toBuffer(buffer).readFloatLE(offset2);
    }
    function readUInt32LE(buffer, offset2) {
      return toBuffer(buffer).readUInt32LE(offset2);
    }
    function readInt32LE(buffer, offset2) {
      return toBuffer(buffer).readInt32LE(offset2);
    }
    function writeDoubleBE(buffer, value, offset2) {
      return toBuffer(buffer).writeDoubleBE(value, offset2);
    }
    function writeFloatBE(buffer, value, offset2) {
      return toBuffer(buffer).writeFloatBE(value, offset2);
    }
    function writeUInt32BE(buffer, value, offset2) {
      return toBuffer(buffer).writeUInt32BE(value, offset2);
    }
    function writeInt32BE(buffer, value, offset2) {
      return toBuffer(buffer).writeInt32BE(value, offset2);
    }
    function readDoubleBE(buffer, offset2) {
      return toBuffer(buffer).readDoubleBE(offset2);
    }
    function readFloatBE(buffer, offset2) {
      return toBuffer(buffer).readFloatBE(offset2);
    }
    function readUInt32BE(buffer, offset2) {
      return toBuffer(buffer).readUInt32BE(offset2);
    }
    function readInt32BE(buffer, offset2) {
      return toBuffer(buffer).readInt32BE(offset2);
    }
    module2.exports = {
      isBuffer,
      isEncoding,
      alloc,
      allocUnsafe,
      allocUnsafeSlow,
      byteLength,
      compare,
      concat,
      copy: copy2,
      equals,
      fill,
      from,
      includes,
      indexOf,
      lastIndexOf,
      swap16,
      swap32,
      swap64,
      toBuffer,
      toString: toString2,
      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(data2) {
        if (this.bytesNeeded === 0) {
          let isBoundary = true;
          for (let i = Math.max(0, data2.byteLength - 4), n = data2.byteLength; i < n && isBoundary; i++) {
            isBoundary = data2[i] <= 127;
          }
          if (isBoundary) return b4a.toString(data2, "utf8");
        }
        let result = "";
        for (let i = 0, n = data2.byteLength; i < n; i++) {
          const byte = data2[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(data2) {
        if (typeof data2 === "string") return data2;
        return this.decoder.decode(data2);
      }
      // For Node.js compatibility
      write(data2) {
        return this.push(data2);
      }
      end(data2) {
        let result = "";
        if (data2) result = this.push(data2);
        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 = 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 || map;
        this.afterWrite = afterWrite.bind(this);
        this.afterUpdateNextTick = updateWriteNT.bind(this);
      }
      get ended() {
        return (this.stream._duplexState & WRITE_DONE) !== 0;
      }
      push(data2) {
        if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false;
        if (this.map !== null) data2 = this.map(data2);
        this.buffered += this.byteLength(data2);
        this.queue.push(data2);
        if (this.buffered < this.highWaterMark) {
          this.stream._duplexState |= WRITE_QUEUED;
          return true;
        }
        this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED;
        return false;
      }
      shift() {
        const data2 = this.queue.shift();
        this.buffered -= this.byteLength(data2);
        if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED;
        return data2;
      }
      end(data2) {
        if (typeof data2 === "function") this.stream.once("finish", data2);
        else if (data2 !== void 0 && data2 !== null) this.push(data2);
        this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY;
      }
      autoBatch(data2, cb) {
        const buffer = [];
        const stream = this.stream;
        buffer.push(data2);
        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 data2 = this.shift();
            stream._duplexState |= WRITE_ACTIVE_AND_WRITING;
            stream._write(data2, 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 = 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 || map;
        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(data2) {
        const stream = this.stream;
        if (data2 === null) {
          this.highWaterMark = 0;
          stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED;
          return false;
        }
        if (this.map !== null) {
          data2 = this.map(data2);
          if (data2 === null) {
            stream._duplexState &= READ_PUSHED;
            return this.buffered < this.highWaterMark;
          }
        }
        this.buffered += this.byteLength(data2);
        this.queue.push(data2);
        stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED;
        return this.buffered < this.highWaterMark;
      }
      shift() {
        const data2 = this.queue.shift();
        this.buffered -= this.byteLength(data2);
        if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED;
        return data2;
      }
      unshift(data2) {
        const pending = [this.map !== null ? this.map(data2) : data2];
        while (this.buffered > 0) pending.push(this.shift());
        for (let i = 0; i < pending.length - 1; i++) {
          const data3 = pending[i];
          this.buffered += this.byteLength(data3);
          this.queue.push(data3);
        }
        this.push(pending[pending.length - 1]);
      }
      read() {
        const stream = this.stream;
        if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
          const data2 = this.shift();
          if (this.pipeTo !== null && this.pipeTo.write(data2) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED;
          if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data2);
          return data2;
        }
        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 data2 = this.shift();
          if (this.pipeTo !== null && this.pipeTo.write(data2) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED;
          if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data2);
        }
      }
      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, data2) {
      if (data2 !== void 0 && data2 !== null) this.push(data2);
      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 Readable4 = 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 map = this._readableState.map || echo;
        this._readableState.map = mapOrSkip;
        return this;
        function mapOrSkip(data2) {
          const next = dec.push(data2);
          return next === "" && (data2.byteLength !== 0 || dec.remaining > 0) ? null : map(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(data2) {
        this._readableState.updateNextTickIfOpen();
        return this._readableState.push(data2);
      }
      unshift(data2) {
        this._readableState.updateNextTickIfOpen();
        return this._readableState.unshift(data2);
      }
      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(data2) {
          if (data2.done) rs.push(null);
          else rs.push(data2.value);
        }
      }
      static from(data2, opts) {
        if (isReadStreamx(data2)) return data2;
        if (data2[asyncIterator]) return this._fromAsyncIterator(data2[asyncIterator](), opts);
        if (!Array.isArray(data2)) data2 = data2 === void 0 ? [] : [data2];
        let i = 0;
        return new _Readable({
          ...opts,
          read(cb) {
            this.push(i === data2.length ? null : data2[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 error = null;
        let promiseResolve = null;
        let promiseReject = null;
        this.on("error", (err) => {
          error = err;
        });
        this.on("readable", onreadable);
        this.on("close", onclose);
        return {
          [asyncIterator]() {
            return this;
          },
          next() {
            return new Promise(function(resolve6, reject) {
              promiseResolve = resolve6;
              promiseReject = reject;
              const data2 = stream.read();
              if (data2 !== null) ondata(data2);
              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(data2) {
          if (promiseReject === null) return;
          if (error) promiseReject(error);
          else if (data2 === null && (stream._duplexState & READ_DONE) === 0) promiseReject(STREAM_DESTROYED);
          else promiseResolve({ value: data2, done: data2 === null });
          promiseReject = promiseResolve = null;
        }
        function destroy(err) {
          stream.destroy(err);
          return new Promise((resolve6, reject) => {
            if (stream._duplexState & DESTROYED) return resolve6({ value: void 0, done: true });
            stream.once("close", function() {
              if (err) reject(err);
              else resolve6({ 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(data2, cb) {
        this._writableState.autoBatch(data2, 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((resolve6) => {
          state.drains.push({ writes, resolve: resolve6 });
        });
      }
      write(data2) {
        this._writableState.updateNextTick();
        return this._writableState.push(data2);
      }
      end(data2) {
        this._writableState.updateNextTick();
        this._writableState.end(data2);
        return this;
      }
    };
    var Duplex = class extends Readable4 {
      // 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(data2, cb) {
        this._writableState.autoBatch(data2, cb);
      }
      _final(cb) {
        cb(null);
      }
      write(data2) {
        this._writableState.updateNextTick();
        return this._writableState.push(data2);
      }
      end(data2) {
        this._writableState.updateNextTick();
        this._writableState.end(data2);
        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(data2, cb) {
        if (this._readableState.buffered >= this._readableState.highWaterMark) {
          this._transformState.data = data2;
        } else {
          this._transform(data2, this._transformState.afterTransform);
        }
      }
      _read(cb) {
        if (this._transformState.data !== null) {
          const data2 = this._transformState.data;
          this._transformState.data = null;
          cb(null);
          this._transform(data2, this._transformState.afterTransform);
        } else {
          cb(null);
        }
      }
      destroy(err) {
        super.destroy(err);
        if (this._transformState.data !== null) {
          this._transformState.data = null;
          this._transformState.afterTransform();
        }
      }
      _transform(data2, cb) {
        cb(null, data2);
      }
      _flush(cb) {
        cb(null);
      }
      _final(cb) {
        this._transformState.afterFinal = cb;
        this._flush(transformAfterFlush.bind(this));
      }
    };
    var PassThrough = class extends Transform2 {
    };
    function transformAfterFlush(err, data2) {
      const cb = this._transformState.afterFinal;
      if (err) return cb(err);
      if (data2 !== null && data2 !== void 0) this.push(data2);
      this.push(null);
      cb(null);
    }
    function pipelinePromise(...streams) {
      return new Promise((resolve6, reject) => {
        return pipeline(...streams, (err) => {
          if (err) return reject(err);
          resolve6();
        });
      });
    }
    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 error = 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 (error === null) error = err;
        });
        dest.on("finish", () => {
          fin = true;
          if (!autoDestroy) done(error);
        });
        if (autoDestroy) {
          dest.on("close", () => done(error || (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 || error) return;
        error = 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(data2) {
      return typeof data2 === "object" && data2 !== null && typeof data2.byteLength === "number";
    }
    function defaultByteLength(data2) {
      return isTypedArray(data2) ? data2.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: Readable4,
      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 encode(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 decode(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 c = cksum(buf);
      if (c === 8 * 32) return null;
      if (c !== 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, offset2, end) {
      for (; offset2 < end; offset2++) {
        if (block[offset2] === num) return offset2;
      }
      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 tuple = [];
      let i;
      for (i = buf.length - 1; i > 0; i--) {
        const byte = buf[i];
        if (positive) tuple.push(byte);
        else tuple.push(255 - byte);
      }
      let sum = 0;
      const l = tuple.length;
      for (i = 0; i < l; i++) {
        sum += tuple[i] * Math.pow(256, i);
      }
      return positive ? sum : -1 * sum;
    }
    function decodeOct(val, offset2, length) {
      val = val.subarray(offset2, offset2 + length);
      offset2 = 0;
      if (val[offset2] & 128) {
        return parse256(val);
      } else {
        while (offset2 < val.length && val[offset2] === 32) offset2++;
        const end = clamp(indexOf(val, 32, offset2, val.length), val.length, val.length);
        while (offset2 < end && val[offset2] === 0) offset2++;
        if (end === offset2) return 0;
        return parseInt(b4a.toString(val.subarray(offset2, end)), 8);
      }
    }
    function decodeStr(val, offset2, length, encoding) {
      return b4a.toString(val.subarray(offset2, indexOf(val, 0, offset2, offset2 + 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: Readable4, 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 Readable4 {
      constructor(self2, header, offset2) {
        super();
        this.header = header;
        this.offset = offset2;
        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 ignore3 = this._buffer.shiftFirst(this._missing);
            if (ignore3 !== null) this._missing -= ignore3.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(data2, cb) {
        this._callback = cb;
        this._buffer.push(data2);
        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 error = null;
        let promiseResolve = null;
        let promiseReject = null;
        let entryStream = null;
        let entryCallback = null;
        const extract = this;
        this.on("entry", onentry);
        this.on("error", (err) => {
          error = 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(resolve6, reject) {
          if (error) {
            return reject(error);
          }
          if (entryStream) {
            resolve6({ value: entryStream, done: false });
            entryStream = null;
            return;
          }
          promiseResolve = resolve6;
          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(error);
          if (!promiseResolve) return;
          if (error) promiseReject(error);
          else promiseResolve({ value: void 0, done: true });
          promiseResolve = promiseReject = null;
        }
        function destroy(err) {
          extract.destroy(err);
          consumeCallback(err);
          return new Promise((resolve6, reject) => {
            if (extract.destroyed) return resolve6({ value: void 0, done: true });
            extract.once("close", function() {
              if (err) reject(err);
              else resolve6({ 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 constants = {
      // 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 || constants;
    } catch {
      module2.exports = constants;
    }
  }
});

// ../../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: Readable4, Writable, getStreamError } = require_streamx();
    var b4a = require_b4a();
    var constants = 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(data2, cb) {
        if (this._isLinkname) {
          this._linkname = this._linkname ? b4a.concat([this._linkname, data2]) : data2;
          return cb(null);
        }
        if (this._isVoid) {
          if (data2.byteLength > 0) {
            return cb(new Error("No body allowed for this entry"));
          }
          return cb();
        }
        this.written += data2.byteLength;
        if (this._pack.push(data2)) 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 Readable4 {
      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 & constants.S_IFMT) {
        case constants.S_IFBLK:
          return "block-device";
        case constants.S_IFCHR:
          return "character-device";
        case constants.S_IFDIR:
          return "directory";
        case constants.S_IFIFO:
          return "fifo";
        case constants.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 fs60 = require("fs");
    var path62 = 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 || fs60;
      const ignore3 = opts.ignore || opts.filter || noop;
      const mapStream = opts.mapStream || echo;
      const statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd2, ignore3, 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 map = opts.map || noop;
      let dmode = typeof opts.dmode === "number" ? opts.dmode : 0;
      let fmode = typeof opts.fmode === "number" ? opts.fmode : 0;
      if (opts.strip) map = strip(map, 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(path62.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 = map(header) || header;
          return pack3.entry(header, onnextentry);
        }
        if (stat4.isSymbolicLink()) {
          header.size = 0;
          header.type = "symlink";
          header = map(header) || header;
          return onsymlink(filename, header);
        }
        header = map(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(path62.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 = path62.resolve(cwd2);
      const xfs = opts.fs || fs60;
      const ignore3 = 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 map = opts.map || noop;
      let dmode = typeof opts.dmode === "number" ? opts.dmode : 0;
      let fmode = typeof opts.fmode === "number" ? opts.fmode : 0;
      if (opts.strip) map = strip(map, 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 = map(header) || header;
        header.name = normalize2(header.name);
        const name = path62.join(cwd2, path62.join("/", header.name));
        if (ignore3(name, header)) {
          stream.resume();
          return next();
        }
        const dir = path62.join(name, ".") === path62.join(cwd2, ".") ? cwd2 : path62.dirname(name);
        validate2(xfs, dir, path62.join(cwd2, "."), function(err, valid) {
          if (err) return next(err);
          if (!valid) return next(new Error(dir + " 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(dir, {
            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 = path62.resolve(path62.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 = path62.join(cwd2, path62.join("/", header.linkname));
            fs60.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(fs61, name, root, cb) {
      if (name === root) return cb(null, true);
      fs61.lstat(name, function(err, st) {
        if (err && err.code !== "ENOENT" && err.code !== "EPERM") return cb(err);
        if (err || st.isDirectory()) return validate2(fs61, path62.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(fs61, stat4, cwd2, ignore3, 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 = path62.join(cwd2, next);
        stat4.call(fs61, 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);
          fs61.readdir(nextAbs, function(err2, files) {
            if (err2) return callback(err2);
            if (sort) files.sort();
            for (let i = 0; i < files.length; i++) {
              if (!ignore3(path62.join(cwd2, next, files[i]))) queue.push(path62.join(next, files[i]));
            }
            callback(null, next, stat5);
          });
        });
      };
    }
    function strip(map, level) {
      return function(header) {
        header.name = header.name.split("/").slice(level).join("/");
        const linkname = header.linkname;
        if (linkname && (header.type === "link" || path62.isAbsolute(linkname))) {
          header.linkname = linkname.split("/").slice(level).join("/");
        }
        return map(header);
      };
    }
  }
});

// ../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/lib/XDGAppPaths.js
var require_XDGAppPaths2 = __commonJS({
  "../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/lib/XDGAppPaths.js"(exports2) {
    "use strict";
    exports2.__esModule = true;
    exports2.Adapt = void 0;
    function isBoolean2(t) {
      return typeOf(t) === "boolean";
    }
    function isObject(t) {
      return typeOf(t) === "object";
    }
    function isString2(t) {
      return typeOf(t) === "string";
    }
    function typeOf(t) {
      return typeof t;
    }
    function Adapt(adapter_) {
      var meta = adapter_.meta, path62 = adapter_.path, xdg = adapter_.xdg;
      var XDGAppPaths_ = /* @__PURE__ */ (function() {
        function XDGAppPaths_2(options_) {
          if (options_ === void 0) {
            options_ = {};
          }
          var _a, _b, _c;
          function XDGAppPaths(options2) {
            if (options2 === void 0) {
              options2 = {};
            }
            return new XDGAppPaths_2(options2);
          }
          var options = isObject(options_) ? options_ : { name: options_ };
          var suffix = (_a = options.suffix) !== null && _a !== void 0 ? _a : "";
          var isolated_ = (_b = options.isolated) !== null && _b !== void 0 ? _b : true;
          var namePriorityList = [
            options.name,
            meta.pkgMainFilename(),
            meta.mainFilename()
          ];
          var nameFallback = "$eval";
          var name = path62.parse(((_c = namePriorityList.find(function(e) {
            return isString2(e);
          })) !== null && _c !== void 0 ? _c : nameFallback) + suffix).name;
          XDGAppPaths.$name = function $name() {
            return name;
          };
          XDGAppPaths.$isolated = function $isolated() {
            return isolated_;
          };
          function isIsolated(dirOptions) {
            var _a2;
            dirOptions = dirOptions !== null && dirOptions !== void 0 ? dirOptions : { isolated: isolated_ };
            var isolated = isBoolean2(dirOptions) ? dirOptions : (_a2 = dirOptions.isolated) !== null && _a2 !== void 0 ? _a2 : isolated_;
            return isolated;
          }
          function finalPathSegment(dirOptions) {
            return isIsolated(dirOptions) ? name : "";
          }
          XDGAppPaths.cache = function cache(dirOptions) {
            return path62.join(xdg.cache(), finalPathSegment(dirOptions));
          };
          XDGAppPaths.config = function config(dirOptions) {
            return path62.join(xdg.config(), finalPathSegment(dirOptions));
          };
          XDGAppPaths.data = function data2(dirOptions) {
            return path62.join(xdg.data(), finalPathSegment(dirOptions));
          };
          XDGAppPaths.runtime = function runtime(dirOptions) {
            return xdg.runtime() ? path62.join(xdg.runtime(), finalPathSegment(dirOptions)) : void 0;
          };
          XDGAppPaths.state = function state(dirOptions) {
            return path62.join(xdg.state(), finalPathSegment(dirOptions));
          };
          XDGAppPaths.configDirs = function configDirs(dirOptions) {
            return xdg.configDirs().map(function(s) {
              return path62.join(s, finalPathSegment(dirOptions));
            });
          };
          XDGAppPaths.dataDirs = function dataDirs(dirOptions) {
            return xdg.dataDirs().map(function(s) {
              return path62.join(s, finalPathSegment(dirOptions));
            });
          };
          return XDGAppPaths;
        }
        return XDGAppPaths_2;
      })();
      return { XDGAppPaths: new XDGAppPaths_() };
    }
    exports2.Adapt = Adapt;
  }
});

// ../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/lib/XDG.js
var require_XDG2 = __commonJS({
  "../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/lib/XDG.js"(exports2) {
    "use strict";
    var __spreadArray2 = exports2 && exports2.__spreadArray || function(to, from) {
      for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
      return to;
    };
    exports2.__esModule = true;
    exports2.Adapt = void 0;
    function Adapt(adapter_) {
      var env3 = adapter_.env, osPaths = adapter_.osPaths, path62 = adapter_.path;
      var isMacOS = /^darwin$/i.test(adapter_.process.platform);
      var isWinOS = /^win/i.test(adapter_.process.platform);
      function baseDir() {
        return osPaths.home() || osPaths.temp();
      }
      function valOrPath(val, pathSegments) {
        return val || path62.join.apply(path62, pathSegments);
      }
      var linux = function() {
        var cache = function() {
          return valOrPath(env3.get("XDG_CACHE_HOME"), [baseDir(), ".cache"]);
        };
        var config = function() {
          return valOrPath(env3.get("XDG_CONFIG_HOME"), [baseDir(), ".config"]);
        };
        var data2 = function() {
          return valOrPath(env3.get("XDG_DATA_HOME"), [baseDir(), ".local", "share"]);
        };
        var runtime = function() {
          return env3.get("XDG_RUNTIME_DIR") || void 0;
        };
        var state = function() {
          return valOrPath(env3.get("XDG_STATE_HOME"), [baseDir(), ".local", "state"]);
        };
        return { cache, config, data: data2, runtime, state };
      };
      var macos = function() {
        var cache = function() {
          return valOrPath(env3.get("XDG_CACHE_HOME"), [baseDir(), "Library", "Caches"]);
        };
        var config = function() {
          return valOrPath(env3.get("XDG_CONFIG_HOME"), [baseDir(), "Library", "Preferences"]);
        };
        var data2 = function() {
          return valOrPath(env3.get("XDG_DATA_HOME"), [baseDir(), "Library", "Application Support"]);
        };
        var runtime = function() {
          return env3.get("XDG_RUNTIME_DIR") || void 0;
        };
        var state = function() {
          return valOrPath(env3.get("XDG_STATE_HOME"), [baseDir(), "Library", "State"]);
        };
        return { cache, config, data: data2, runtime, state };
      };
      var windows = function() {
        function appData() {
          return valOrPath(env3.get("APPDATA"), [baseDir(), "AppData", "Roaming"]);
        }
        function localAppData() {
          return valOrPath(env3.get("LOCALAPPDATA"), [baseDir(), "AppData", "Local"]);
        }
        var cache = function() {
          return valOrPath(env3.get("XDG_CACHE_HOME"), [localAppData(), "xdg.cache"]);
        };
        var config = function() {
          return valOrPath(env3.get("XDG_CONFIG_HOME"), [appData(), "xdg.config"]);
        };
        var data2 = function() {
          return valOrPath(env3.get("XDG_DATA_HOME"), [appData(), "xdg.data"]);
        };
        var runtime = function() {
          return env3.get("XDG_RUNTIME_DIR") || void 0;
        };
        var state = function() {
          return valOrPath(env3.get("XDG_STATE_HOME"), [localAppData(), "xdg.state"]);
        };
        return { cache, config, data: data2, runtime, state };
      };
      var XDG_ = /* @__PURE__ */ (function() {
        function XDG_2() {
          function XDG() {
            return new XDG_2();
          }
          var extension = isMacOS ? macos() : isWinOS ? windows() : linux();
          XDG.cache = extension.cache;
          XDG.config = extension.config;
          XDG.data = extension.data;
          XDG.runtime = extension.runtime;
          XDG.state = extension.state;
          XDG.configDirs = function configDirs() {
            var pathList = env3.get("XDG_CONFIG_DIRS");
            return __spreadArray2([extension.config()], pathList ? pathList.split(path62.delimiter) : []);
          };
          XDG.dataDirs = function dataDirs() {
            var pathList = env3.get("XDG_DATA_DIRS");
            return __spreadArray2([extension.data()], pathList ? pathList.split(path62.delimiter) : []);
          };
          return XDG;
        }
        return XDG_2;
      })();
      return { XDG: new XDG_() };
    }
    exports2.Adapt = Adapt;
  }
});

// ../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/lib/OSPaths.js
var require_OSPaths2 = __commonJS({
  "../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/lib/OSPaths.js"(exports2) {
    "use strict";
    var __spreadArray2 = exports2 && exports2.__spreadArray || function(to, from) {
      for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
      return to;
    };
    exports2.__esModule = true;
    exports2.Adapt = void 0;
    function isEmpty(s) {
      return !s;
    }
    function Adapt(adapter_) {
      var env3 = adapter_.env, os10 = adapter_.os, path62 = adapter_.path;
      var isWinOS = /^win/i.test(adapter_.process.platform);
      function normalizePath2(path_) {
        return path_ ? adapter_.path.normalize(adapter_.path.join(path_, ".")) : void 0;
      }
      function home() {
        var posix = function() {
          return normalizePath2((typeof os10.homedir === "function" ? os10.homedir() : void 0) || env3.get("HOME"));
        };
        var windows = function() {
          var priorityList = [
            typeof os10.homedir === "function" ? os10.homedir() : void 0,
            env3.get("USERPROFILE"),
            env3.get("HOME"),
            env3.get("HOMEDRIVE") || env3.get("HOMEPATH") ? path62.join(env3.get("HOMEDRIVE") || "", env3.get("HOMEPATH") || "") : void 0
          ];
          return normalizePath2(priorityList.find(function(v2) {
            return !isEmpty(v2);
          }));
        };
        return isWinOS ? windows() : posix();
      }
      function temp() {
        function joinPathToBase(base2, segments) {
          return base2 ? path62.join.apply(path62, __spreadArray2([base2], segments)) : void 0;
        }
        function posix() {
          var fallback = "/tmp";
          var priorityList = [
            typeof os10.tmpdir === "function" ? os10.tmpdir() : void 0,
            env3.get("TMPDIR"),
            env3.get("TEMP"),
            env3.get("TMP")
          ];
          return normalizePath2(priorityList.find(function(v2) {
            return !isEmpty(v2);
          })) || fallback;
        }
        function windows() {
          var fallback = "C:\\Temp";
          var priorityListLazy = [
            typeof os10.tmpdir === "function" ? os10.tmpdir : function() {
              return void 0;
            },
            function() {
              return env3.get("TEMP");
            },
            function() {
              return env3.get("TMP");
            },
            function() {
              return joinPathToBase(env3.get("LOCALAPPDATA"), ["Temp"]);
            },
            function() {
              return joinPathToBase(home(), ["AppData", "Local", "Temp"]);
            },
            function() {
              return joinPathToBase(env3.get("ALLUSERSPROFILE"), ["Temp"]);
            },
            function() {
              return joinPathToBase(env3.get("SystemRoot"), ["Temp"]);
            },
            function() {
              return joinPathToBase(env3.get("windir"), ["Temp"]);
            },
            function() {
              return joinPathToBase(env3.get("SystemDrive"), ["\\", "Temp"]);
            }
          ];
          var v2 = priorityListLazy.find(function(v3) {
            return v3 && !isEmpty(v3());
          });
          return v2 && normalizePath2(v2()) || fallback;
        }
        return isWinOS ? windows() : posix();
      }
      var OSPaths_ = /* @__PURE__ */ (function() {
        function OSPaths_2() {
          function OSPaths() {
            return new OSPaths_2();
          }
          OSPaths.home = home;
          OSPaths.temp = temp;
          return OSPaths;
        }
        return OSPaths_2;
      })();
      return { OSPaths: new OSPaths_() };
    }
    exports2.Adapt = Adapt;
  }
});

// ../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/platform-adapters/node.js
var require_node6 = __commonJS({
  "../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/platform-adapters/node.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      Object.defineProperty(o, k2, { enumerable: true, get: function() {
        return m2[k];
      } });
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    }) : function(o, v2) {
      o["default"] = v2;
    });
    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;
    };
    exports2.__esModule = true;
    exports2.adapter = void 0;
    var os10 = __importStar2(require("os"));
    var path62 = __importStar2(require("path"));
    exports2.adapter = {
      atImportPermissions: { env: true },
      env: {
        get: function(s) {
          return process.env[s];
        }
      },
      os: os10,
      path: path62,
      process
    };
  }
});

// ../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/mod.cjs.js
var require_mod_cjs4 = __commonJS({
  "../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/mod.cjs.js"(exports2, module2) {
    "use strict";
    var OSPaths_js_1 = require_OSPaths2();
    var node_js_1 = require_node6();
    module2.exports = OSPaths_js_1.Adapt(node_js_1.adapter).OSPaths;
  }
});

// ../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/platform-adapters/node.js
var require_node7 = __commonJS({
  "../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/platform-adapters/node.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      Object.defineProperty(o, k2, { enumerable: true, get: function() {
        return m2[k];
      } });
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    }) : function(o, v2) {
      o["default"] = v2;
    });
    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 };
    };
    exports2.__esModule = true;
    exports2.adapter = void 0;
    var path62 = __importStar2(require("path"));
    var os_paths_1 = __importDefault2(require_mod_cjs4());
    exports2.adapter = {
      atImportPermissions: { env: true },
      env: {
        get: function(s) {
          return process.env[s];
        }
      },
      osPaths: os_paths_1["default"],
      path: path62,
      process
    };
  }
});

// ../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/mod.cjs.js
var require_mod_cjs5 = __commonJS({
  "../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/mod.cjs.js"(exports2, module2) {
    "use strict";
    var XDG_js_1 = require_XDG2();
    var node_js_1 = require_node7();
    module2.exports = XDG_js_1.Adapt(node_js_1.adapter).XDG;
  }
});

// ../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/platform-adapters/node.js
var require_node8 = __commonJS({
  "../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/platform-adapters/node.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      Object.defineProperty(o, k2, { enumerable: true, get: function() {
        return m2[k];
      } });
    }) : (function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    }) : function(o, v2) {
      o["default"] = v2;
    });
    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 };
    };
    exports2.__esModule = true;
    exports2.adapter = void 0;
    var path62 = __importStar2(require("path"));
    var xdg_portable_1 = __importDefault2(require_mod_cjs5());
    exports2.adapter = {
      atImportPermissions: { env: true, read: true },
      meta: {
        mainFilename: function() {
          var requireMain = typeof require !== "undefined" && require !== null && require.main ? require.main : { filename: void 0 };
          var requireMainFilename = requireMain.filename;
          var filename = (requireMainFilename !== process.execArgv[0] ? requireMainFilename : void 0) || (typeof process._eval === "undefined" ? process.argv[1] : void 0);
          return filename;
        },
        pkgMainFilename: function() {
          return process.pkg ? process.execPath : void 0;
        }
      },
      path: path62,
      process,
      xdg: xdg_portable_1["default"]
    };
  }
});

// ../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/mod.cjs.js
var require_mod_cjs6 = __commonJS({
  "../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/mod.cjs.js"(exports2, module2) {
    "use strict";
    var XDGAppPaths_js_1 = require_XDGAppPaths2();
    var node_js_1 = require_node8();
    module2.exports = XDGAppPaths_js_1.Adapt(node_js_1.adapter).XDGAppPaths;
  }
});

// src/index.ts
var src_exports = {};
__export(src_exports, {
  AIOptionsSchema: () => AIOptionsSchema,
  AISearchOptionsSchema: () => AISearchOptionsSchema,
  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,
  ASSETS_PLUGIN: () => ASSETS_PLUGIN,
  AnalyticsEngineSchemaOptionsSchema: () => AnalyticsEngineSchemaOptionsSchema,
  AnalyticsEngineSchemaSharedOptionsSchema: () => AnalyticsEngineSchemaSharedOptionsSchema,
  AssetsOptionsSchema: () => AssetsOptionsSchema,
  BROWSER_RENDERING_PLUGIN: () => BROWSER_RENDERING_PLUGIN,
  BROWSER_RENDERING_PLUGIN_NAME: () => BROWSER_RENDERING_PLUGIN_NAME,
  BrowserRenderingOptionsSchema: () => BrowserRenderingOptionsSchema,
  CACHE_PLUGIN: () => CACHE_PLUGIN,
  CACHE_PLUGIN_NAME: () => CACHE_PLUGIN_NAME,
  CORE_PLUGIN: () => CORE_PLUGIN,
  CORE_PLUGIN_NAME: () => CORE_PLUGIN_NAME2,
  CacheBindings: () => CacheBindings,
  CacheHeaders: () => CacheHeaders,
  CacheOptionsSchema: () => CacheOptionsSchema,
  CacheSharedOptionsSchema: () => CacheSharedOptionsSchema,
  CloseEvent: () => CloseEvent,
  CoreBindings: () => CoreBindings,
  CoreHeaders: () => CoreHeaders,
  CoreOptionsSchema: () => CoreOptionsSchema,
  CorePaths: () => CorePaths,
  CoreSharedOptionsSchema: () => CoreSharedOptionsSchema,
  D1OptionsSchema: () => D1OptionsSchema,
  D1SharedOptionsSchema: () => D1SharedOptionsSchema,
  D1_PLUGIN: () => D1_PLUGIN,
  D1_PLUGIN_NAME: () => D1_PLUGIN_NAME,
  DEFAULT_PERSIST_ROOT: () => DEFAULT_PERSIST_ROOT,
  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,
  DispatchFetchDispatcher: () => DispatchFetchDispatcher,
  DispatchNamespaceOptionsSchema: () => DispatchNamespaceOptionsSchema,
  DurableObjectsOptionsSchema: () => DurableObjectsOptionsSchema,
  DurableObjectsSharedOptionsSchema: () => DurableObjectsSharedOptionsSchema,
  EMAIL_PLUGIN: () => EMAIL_PLUGIN,
  EMAIL_PLUGIN_NAME: () => EMAIL_PLUGIN_NAME,
  EmailOptionsSchema: () => EmailOptionsSchema,
  ErrorEvent: () => ErrorEvent,
  FLAGSHIP_PLUGIN: () => FLAGSHIP_PLUGIN,
  FLAGSHIP_PLUGIN_NAME: () => FLAGSHIP_PLUGIN_NAME,
  FlagshipOptionsSchema: () => FlagshipOptionsSchema,
  FormData: () => import_undici4.FormData,
  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_undici4.Headers,
  HelloWorldOptionsSchema: () => HelloWorldOptionsSchema,
  HelloWorldSharedOptionsSchema: () => HelloWorldSharedOptionsSchema,
  HttpOptions_Style: () => HttpOptions_Style,
  HyperdriveInputOptionsSchema: () => HyperdriveInputOptionsSchema,
  HyperdriveSchema: () => HyperdriveSchema,
  IMAGES_PLUGIN: () => IMAGES_PLUGIN,
  IMAGES_PLUGIN_NAME: () => IMAGES_PLUGIN_NAME,
  INTROSPECT_SQLITE_METHOD: () => INTROSPECT_SQLITE_METHOD,
  ImagesOptionsSchema: () => ImagesOptionsSchema,
  ImagesSharedOptionsSchema: () => ImagesSharedOptionsSchema,
  JsonSchema: () => JsonSchema,
  KVHeaders: () => KVHeaders,
  KVLimits: () => KVLimits,
  KVOptionsSchema: () => KVOptionsSchema,
  KVParams: () => KVParams,
  KVSharedOptionsSchema: () => KVSharedOptionsSchema,
  KV_NAMESPACE_OBJECT_CLASS_NAME: () => KV_NAMESPACE_OBJECT_CLASS_NAME,
  KV_PLUGIN: () => KV_PLUGIN,
  KV_PLUGIN_NAME: () => KV_PLUGIN_NAME,
  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,
  MediaOptionsSchema: () => MediaOptionsSchema,
  MessageEvent: () => MessageEvent,
  Miniflare: () => Miniflare,
  MiniflareCoreError: () => MiniflareCoreError,
  MiniflareError: () => MiniflareError,
  ModuleDefinitionSchema: () => ModuleDefinitionSchema,
  ModuleRuleSchema: () => ModuleRuleSchema,
  ModuleRuleTypeSchema: () => ModuleRuleTypeSchema,
  MtlsOptionsSchema: () => MtlsOptionsSchema,
  Mutex: () => Mutex,
  NoOpLog: () => NoOpLog,
  PIPELINES_PLUGIN_NAME: () => PIPELINES_PLUGIN_NAME,
  PIPELINE_PLUGIN: () => PIPELINE_PLUGIN,
  PLUGINS: () => PLUGINS,
  PLUGIN_ENTRIES: () => PLUGIN_ENTRIES,
  PathSchema: () => PathSchema,
  PeriodType: () => PeriodType,
  PersistenceSchema: () => PersistenceSchema,
  PipelineOptionsSchema: () => PipelineOptionsSchema,
  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,
  QueuesOptionsSchema: () => QueuesOptionsSchema,
  R2OptionsSchema: () => R2OptionsSchema,
  R2SharedOptionsSchema: () => R2SharedOptionsSchema,
  R2_PLUGIN: () => R2_PLUGIN,
  R2_PLUGIN_NAME: () => R2_PLUGIN_NAME,
  RATELIMIT_PLUGIN: () => RATELIMIT_PLUGIN,
  RATELIMIT_PLUGIN_NAME: () => RATELIMIT_PLUGIN_NAME,
  RatelimitConfigSchema: () => RatelimitConfigSchema,
  RatelimitOptionsSchema: () => RatelimitOptionsSchema,
  Request: () => Request,
  Response: () => Response2,
  RouterError: () => RouterError,
  Runtime: () => Runtime,
  SECRET_STORE_PLUGIN: () => SECRET_STORE_PLUGIN,
  SECRET_STORE_PLUGIN_NAME: () => SECRET_STORE_PLUGIN_NAME,
  SERVICE_ENTRY: () => SERVICE_ENTRY,
  SERVICE_LOOPBACK: () => SERVICE_LOOPBACK,
  SITES_NO_CACHE_PREFIX: () => SITES_NO_CACHE_PREFIX,
  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,
  SecretsStoreSecretsOptionsSchema: () => SecretsStoreSecretsOptionsSchema,
  SecretsStoreSecretsSharedOptionsSchema: () => SecretsStoreSecretsSharedOptionsSchema,
  SharedBindings: () => SharedBindings,
  SharedHeaders: () => SharedHeaders,
  SiteBindings: () => SiteBindings,
  SourceOptionsSchema: () => SourceOptionsSchema,
  StreamOptionsSchema: () => StreamOptionsSchema,
  StreamSharedOptionsSchema: () => StreamSharedOptionsSchema,
  TlsOptions_Version: () => TlsOptions_Version,
  TypedEventTarget: () => TypedEventTarget,
  USER_ERROR_CODES: () => USER_ERROR_CODES,
  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,
  VectorizeOptionsSchema: () => VectorizeOptionsSchema,
  VersionMetadataOptionsSchema: () => VersionMetadataOptionsSchema,
  VpcNetworksOptionsSchema: () => VpcNetworksOptionsSchema,
  VpcServicesOptionsSchema: () => VpcServicesOptionsSchema,
  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,
  WorkerLoaderConfigSchema: () => WorkerLoaderConfigSchema,
  WorkerLoaderOptionsSchema: () => WorkerLoaderOptionsSchema,
  Worker_Binding_CryptoKey_Usage: () => Worker_Binding_CryptoKey_Usage,
  WorkflowsOptionsSchema: () => WorkflowsOptionsSchema,
  WorkflowsSharedOptionsSchema: () => WorkflowsSharedOptionsSchema,
  __MiniflareFunctionWrapper: () => __MiniflareFunctionWrapper,
  _enableControlEndpoints: () => _enableControlEndpoints,
  _forceColour: () => _forceColour,
  _initialiseInstanceRegistry: () => _initialiseInstanceRegistry,
  _isCyclic: () => _isCyclic,
  _transformsForContentEncodingAndContentType: () => _transformsForContentEncodingAndContentType,
  base64Decode: () => base64Decode,
  base64Encode: () => base64Encode,
  buildAssetManifest: () => buildAssetManifest,
  compileModuleRules: () => compileModuleRules,
  coupleWebSocket: () => coupleWebSocket,
  createFetchMock: () => createFetchMock,
  createHTTPReducers: () => createHTTPReducers,
  createHTTPRevivers: () => createHTTPRevivers,
  decodeSitesKey: () => decodeSitesKey,
  deserialiseRegExps: () => deserialiseRegExps,
  deserialiseSiteRegExps: () => deserialiseSiteRegExps,
  encodeSitesKey: () => encodeSitesKey,
  fetch: () => fetch4,
  formatError: () => formatError,
  formatZodError: () => formatZodError,
  getAccessibleHosts: () => getAccessibleHosts,
  getAssetsBindingsNames: () => getAssetsBindingsNames,
  getCacheServiceName: () => getCacheServiceName,
  getDefaultDevRegistryPath: () => getDefaultDevRegistryPath,
  getDirectSocketName: () => getDirectSocketName,
  getEntrySocketHttpOptions: () => getEntrySocketHttpOptions,
  getFreshSourceMapSupport: () => getFreshSourceMapSupport,
  getGlobalServices: () => getGlobalServices,
  getMiniflareObjectBindings: () => getMiniflareObjectBindings,
  getNodeCompat: () => getNodeCompat,
  getPersistPath: () => getPersistPath,
  getRootPath: () => getRootPath,
  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,
  migrateDatabase: () => migrateDatabase,
  namespaceEntries: () => namespaceEntries,
  namespaceKeys: () => namespaceKeys,
  normaliseDurableObject: () => normaliseDurableObject,
  objectEntryWorker: () => objectEntryWorker,
  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,
  supportedCompatibilityDate: () => supportedCompatibilityDate,
  testRegExps: () => testRegExps,
  testSiteRegExps: () => testSiteRegExps,
  viewToBuffer: () => viewToBuffer,
  workerdStructuredLogSchema: () => WorkerdStructuredLogSchema,
  zAwaitable: () => zAwaitable
});
module.exports = __toCommonJS(src_exports);
var import_node_assert23 = __toESM(require("node:assert"));
var import_node_crypto7 = __toESM(require("node:crypto"));
var import_node_fs17 = __toESM(require("node:fs"));
var import_promises22 = require("node:fs/promises");
var import_node_http2 = __toESM(require("node:http"));
var import_node_net2 = __toESM(require("node:net"));
var import_node_os10 = __toESM(require("node:os"));
var import_node_path25 = __toESM(require("node:path"));
var import_web5 = require("node:stream/web");
var import_node_util6 = __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 = (offset2 = 0) => (code) => `\x1B[${code + offset2}m`;
var wrapAnsi256 = (offset2 = 0) => (code) => `\x1B[${38 + offset2};5;${code}m`;
var wrapAnsi16m = (offset2 = 0) => (red3, green3, blue3) => `\x1B[${38 + offset2};2;${red3};${green3};${blue3}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(red3, green3, blue3) {
        if (red3 === green3 && green3 === blue3) {
          if (red3 < 8) {
            return 16;
          }
          if (red3 > 248) {
            return 231;
          }
          return Math.round((red3 - 8) / 247 * 24) + 232;
        }
        return 16 + 36 * Math.round(red3 / 255 * 5) + 6 * Math.round(green3 / 255 * 5) + Math.round(blue3 / 255 * 5);
      },
      enumerable: false
    },
    hexToRgb: {
      value(hex) {
        const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches) {
          return [0, 0, 0];
        }
        let [colorString] = matches;
        if (colorString.length === 3) {
          colorString = [...colorString].map((character) => character + character).join("");
        }
        const integer = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer >> 16 & 255,
          integer >> 8 & 255,
          integer & 255
          /* eslint-enable no-bitwise */
        ];
      },
      enumerable: false
    },
    hexToAnsi256: {
      value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
      enumerable: false
    },
    ansi256ToAnsi: {
      value(code) {
        if (code < 8) {
          return 30 + code;
        }
        if (code < 16) {
          return 90 + (code - 8);
        }
        let red3;
        let green3;
        let blue3;
        if (code >= 232) {
          red3 = ((code - 232) * 10 + 8) / 255;
          green3 = red3;
          blue3 = red3;
        } else {
          code -= 16;
          const remainder = code % 36;
          red3 = Math.floor(code / 36) / 5;
          green3 = Math.floor(remainder / 6) / 5;
          blue3 = remainder % 6 / 5;
        }
        const value = Math.max(red3, green3, blue3) * 2;
        if (value === 0) {
          return 30;
        }
        let result = 30 + (Math.round(blue3) << 2 | Math.round(green3) << 1 | Math.round(red3));
        if (value === 2) {
          result += 60;
        }
        return result;
      },
      enumerable: false
    },
    rgbToAnsi: {
      value: (red3, green3, blue3) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red3, green3, blue3)),
      enumerable: false
    },
    hexToAnsi: {
      value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
      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 version3 = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
    switch (env.TERM_PROGRAM) {
      case "iTerm.app": {
        return version3 >= 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(string, substring, replacer) {
  let index = string.indexOf(substring);
  if (index === -1) {
    return string;
  }
  const substringLength = substring.length;
  let endIndex = 0;
  let returnValue = "";
  do {
    returnValue += string.slice(endIndex, index) + substring + replacer;
    endIndex = index + substringLength;
    index = string.indexOf(substring, endIndex);
  } while (index !== -1);
  returnValue += string.slice(endIndex);
  return returnValue;
}
function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
  let endIndex = 0;
  let returnValue = "";
  do {
    const gotCR = string[index - 1] === "\r";
    returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
    endIndex = index + 1;
    index = string.indexOf("\n", endIndex);
  } while (index !== -1);
  returnValue += string.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 = (object, 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;
  object.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 = (open2, close, parent) => {
  let openAll;
  let closeAll;
  if (parent === void 0) {
    openAll = open2;
    closeAll = close;
  } else {
    openAll = parent.openAll + open2;
    closeAll = close + parent.closeAll;
  }
  return {
    open: open2,
    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, string) => {
  if (self2.level <= 0 || !string) {
    return self2[IS_EMPTY] ? "" : string;
  }
  let styler = self2[STYLER];
  if (styler === void 0) {
    return string;
  }
  const { openAll, closeAll } = styler;
  if (string.includes("\x1B")) {
    while (styler !== void 0) {
      string = stringReplaceAll(string, styler.close, styler.open);
      styler = styler.parent;
    }
  }
  const lfIndex = string.indexOf("\n");
  if (lfIndex !== -1) {
    string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
  }
  return openAll + string + closeAll;
};
Object.defineProperties(createChalk.prototype, styles2);
var chalk = createChalk();
var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
var source_default = chalk;

// ../cli/colors.ts
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/streams.ts
var stdout = process.stdout;
var stderr = process.stderr;

// ../cli/check-macos-version.ts
var import_node_os3 = __toESM(require("node:os"));

// ../workers-utils/dist/chunk-OZQVB3L3.mjs
var SERVICE_TAG_PREFIX = "cf:service=";
var ENVIRONMENT_TAG_PREFIX = "cf:environment=";
var PATH_TO_DEPLOY_CONFIG = ".wrangler/deploy/config.json";

// ../workers-utils/dist/chunk-DCOBXSFB.mjs
var __create2 = Object.create;
var __defProp2 = Object.defineProperty;
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
var __getOwnPropNames2 = Object.getOwnPropertyNames;
var __getProtoOf2 = Object.getPrototypeOf;
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp2(target, "name", { value, configurable: true });
var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x2)(function(x2) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x2 + '" is not supported');
});
var __commonJS2 = (cb, mod) => function __require2() {
  return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export2 = (target, all2) => {
  for (var name in all2)
    __defProp2(target, name, { get: all2[name], enumerable: true });
};
var __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;
};
var __reExport2 = (target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default"));
var __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/chunk-S3JFRPJM.mjs
var import_node_assert = __toESM(require("node:assert"), 1);
function isCompatDate(str) {
  return /^\d{4}-\d{2}-\d{2}$/.test(str);
}
__name(isCompatDate, "isCompatDate");
function formatCompatibilityDate(date) {
  const compatDate = date.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");
function assertNever(_value) {
}
__name(assertNever, "assertNever");
function mapWorkerMetadataBindings(bindings) {
  return bindings.filter((binding) => binding.type !== "secret_text").reduce((configObj, binding) => {
    switch (binding.type) {
      case "plain_text":
        {
          configObj.vars = {
            ...configObj.vars ?? {},
            [binding.name]: binding.text
          };
        }
        break;
      case "json":
        {
          configObj.vars = {
            ...configObj.vars ?? {},
            name: binding.name,
            json: binding.json
          };
        }
        break;
      case "kv_namespace":
        {
          configObj.kv_namespaces = [
            ...configObj.kv_namespaces ?? [],
            { id: binding.namespace_id, binding: binding.name }
          ];
        }
        break;
      case "durable_object_namespace":
        {
          configObj.durable_objects = {
            bindings: [
              ...configObj.durable_objects?.bindings ?? [],
              {
                name: binding.name,
                class_name: binding.class_name,
                script_name: binding.script_name,
                environment: binding.environment
              }
            ]
          };
        }
        break;
      case "d1":
        {
          configObj.d1_databases = [
            ...configObj.d1_databases ?? [],
            {
              binding: binding.name,
              database_id: binding.id
            }
          ];
        }
        break;
      case "browser":
        {
          configObj.browser = {
            binding: binding.name
          };
        }
        break;
      case "ai":
        {
          configObj.ai = {
            binding: binding.name
          };
        }
        break;
      case "images":
        {
          configObj.images = {
            binding: binding.name
          };
        }
        break;
      case "stream":
        {
          configObj.stream = {
            binding: binding.name
          };
        }
        break;
      case "media":
        {
          configObj.media = {
            binding: binding.name
          };
        }
        break;
      case "r2_bucket":
        {
          configObj.r2_buckets = [
            ...configObj.r2_buckets ?? [],
            {
              binding: binding.name,
              bucket_name: binding.bucket_name,
              jurisdiction: binding.jurisdiction
            }
          ];
        }
        break;
      case "secrets_store_secret":
        {
          configObj.secrets_store_secrets = [
            ...configObj.secrets_store_secrets ?? [],
            {
              binding: binding.name,
              store_id: binding.store_id,
              secret_name: binding.secret_name
            }
          ];
        }
        break;
      case "unsafe_hello_world": {
        configObj.unsafe_hello_world = [
          ...configObj.unsafe_hello_world ?? [],
          {
            binding: binding.name,
            enable_timer: binding.enable_timer
          }
        ];
        break;
      }
      case "flagship": {
        configObj.flagship = [
          ...configObj.flagship ?? [],
          {
            binding: binding.name,
            app_id: binding.app_id
          }
        ];
        break;
      }
      case "service":
        {
          configObj.services = [
            ...configObj.services ?? [],
            {
              binding: binding.name,
              service: binding.service,
              environment: binding.environment,
              entrypoint: binding.entrypoint
            }
          ];
        }
        break;
      case "analytics_engine":
        {
          configObj.analytics_engine_datasets = [
            ...configObj.analytics_engine_datasets ?? [],
            { binding: binding.name, dataset: binding.dataset }
          ];
        }
        break;
      case "dispatch_namespace":
        {
          configObj.dispatch_namespaces = [
            ...configObj.dispatch_namespaces ?? [],
            {
              binding: binding.name,
              namespace: binding.namespace,
              ...binding.outbound && {
                outbound: {
                  service: binding.outbound.worker.service,
                  environment: binding.outbound.worker.environment,
                  parameters: binding.outbound.params?.map((p) => p.name) ?? []
                }
              }
            }
          ];
        }
        break;
      case "logfwdr":
        {
          configObj.logfwdr = {
            bindings: [
              ...configObj.logfwdr?.bindings ?? [],
              { name: binding.name, destination: binding.destination }
            ]
          };
        }
        break;
      case "wasm_module":
        {
          configObj.wasm_modules = {
            ...configObj.wasm_modules ?? {},
            [binding.name]: binding.part
          };
        }
        break;
      case "text_blob":
        {
          configObj.text_blobs = {
            ...configObj.text_blobs ?? {},
            [binding.name]: binding.part
          };
        }
        break;
      case "data_blob":
        {
          configObj.data_blobs = {
            ...configObj.data_blobs ?? {},
            [binding.name]: binding.part
          };
        }
        break;
      case "secret_text":
        break;
      case "version_metadata": {
        {
          configObj.version_metadata = {
            binding: binding.name
          };
        }
        break;
      }
      case "send_email": {
        configObj.send_email = [
          ...configObj.send_email ?? [],
          {
            name: binding.name,
            destination_address: binding.destination_address,
            allowed_destination_addresses: binding.allowed_destination_addresses,
            allowed_sender_addresses: binding.allowed_sender_addresses
          }
        ];
        break;
      }
      case "queue":
        configObj.queues ??= { producers: [] };
        configObj.queues.producers = [
          ...configObj.queues.producers ?? [],
          {
            binding: binding.name,
            queue: binding.queue_name,
            delivery_delay: binding.delivery_delay
          }
        ];
        break;
      case "vectorize":
        configObj.vectorize = [
          ...configObj.vectorize ?? [],
          {
            binding: binding.name,
            index_name: binding.index_name
          }
        ];
        break;
      case "ai_search_namespace":
        configObj.ai_search_namespaces = [
          ...configObj.ai_search_namespaces ?? [],
          {
            binding: binding.name,
            namespace: binding.namespace
          }
        ];
        break;
      case "ai_search":
        configObj.ai_search = [
          ...configObj.ai_search ?? [],
          {
            binding: binding.name,
            instance_name: binding.instance_name
          }
        ];
        break;
      case "hyperdrive":
        configObj.hyperdrive = [
          ...configObj.hyperdrive ?? [],
          {
            binding: binding.name,
            id: binding.id
          }
        ];
        break;
      case "mtls_certificate":
        configObj.mtls_certificates = [
          ...configObj.mtls_certificates ?? [],
          {
            binding: binding.name,
            certificate_id: binding.certificate_id
          }
        ];
        break;
      case "pipelines":
        configObj.pipelines = [
          ...configObj.pipelines ?? [],
          {
            binding: binding.name,
            pipeline: binding.pipeline
          }
        ];
        break;
      case "assets":
        configObj.assets = {
          binding: binding.name
          // Note: we currently don't get all the assets information from the
          //      API, so here we are only able to set the name of the binding
          //      hopefully in the future we can properly fully support the binding
        };
        break;
      case "inherit":
        configObj.unsafe = {
          bindings: [...configObj.unsafe?.bindings ?? [], binding],
          metadata: configObj.unsafe?.metadata ?? void 0
        };
        break;
      case "workflow":
        {
          configObj.workflows = [
            ...configObj.workflows ?? [],
            {
              binding: binding.name,
              name: binding.workflow_name,
              class_name: binding.class_name,
              script_name: binding.script_name
            }
          ];
        }
        break;
      case "worker_loader":
        {
          configObj.worker_loaders = [
            ...configObj.worker_loaders ?? [],
            {
              binding: binding.name
            }
          ];
        }
        break;
      case "ratelimit":
        {
          configObj.ratelimits = [
            ...configObj.ratelimits ?? [],
            {
              name: binding.name,
              namespace_id: binding.namespace_id,
              simple: {
                limit: binding.simple.limit,
                period: binding.simple.period
              }
            }
          ];
        }
        break;
      case "vpc_service":
        {
          configObj.vpc_services = [
            ...configObj.vpc_services ?? [],
            {
              binding: binding.name,
              service_id: binding.service_id
            }
          ];
        }
        break;
      case "vpc_network":
        {
          if (binding.tunnel_id !== void 0) {
            configObj.vpc_networks = [
              ...configObj.vpc_networks ?? [],
              { binding: binding.name, tunnel_id: binding.tunnel_id }
            ];
          } else if (binding.network_id !== void 0) {
            configObj.vpc_networks = [
              ...configObj.vpc_networks ?? [],
              { binding: binding.name, network_id: binding.network_id }
            ];
          }
        }
        break;
      default: {
        configObj.unsafe = {
          bindings: [...configObj.unsafe?.bindings ?? [], binding],
          metadata: configObj.unsafe?.metadata ?? void 0
        };
      }
    }
    return configObj;
  }, {});
}
__name(mapWorkerMetadataBindings, "mapWorkerMetadataBindings");
function convertWorkerToWranglerConfig(config) {
  const mappedBindings = mapWorkerMetadataBindings(config.bindings);
  const durableObjectClassNames = config.bindings.filter(
    (binding) => binding.type === "durable_object_namespace" && binding.script_name === config.name
  ).map(
    (durableObject) => durableObject.class_name
  );
  const allRoutes = [
    ...config.routes.map((r2) => ({
      pattern: r2.pattern,
      zone_name: r2.zone_name
    })),
    ...config.domains.map((c) => ({
      pattern: c.hostname,
      zone_name: c.zone_name,
      custom_domain: true
    }))
  ];
  return {
    name: config.name,
    main: config.entrypoint,
    workers_dev: config.subdomain.enabled,
    preview_urls: config.subdomain.previews_enabled,
    compatibility_date: config.compatibility_date ?? getTodaysCompatDate(),
    compatibility_flags: config.compatibility_flags,
    ...allRoutes.length ? { routes: allRoutes } : {},
    placement: config.placement?.mode === "smart" ? { mode: "smart" } : void 0,
    limits: config.limits,
    ...durableObjectClassNames.length && config.migration_tag ? {
      migrations: [
        {
          tag: config.migration_tag,
          new_classes: durableObjectClassNames
        }
      ]
    } : {},
    ...config.schedules.length ? {
      triggers: {
        crons: config.schedules.map((scheduled) => scheduled.cron)
      }
    } : {},
    tail_consumers: config.tail_consumers ?? void 0,
    observability: config.observability,
    ...mappedBindings
  };
}
__name(convertWorkerToWranglerConfig, "convertWorkerToWranglerConfig");
function constructWranglerConfig(workerOrWorkers) {
  let workers;
  if (Array.isArray(workerOrWorkers)) {
    workers = workerOrWorkers;
  } else {
    workers = [workerOrWorkers];
  }
  const topLevelEnv = workers.find(
    (w2) => !w2.tags?.some((t) => t.startsWith(ENVIRONMENT_TAG_PREFIX))
  );
  const workerName = topLevelEnv?.name ?? workers[0].name;
  const entrypoint = topLevelEnv?.entrypoint ?? workers[0].entrypoint;
  let combinedConfig;
  if (topLevelEnv) {
    combinedConfig = convertWorkerToWranglerConfig(topLevelEnv);
  } else {
    combinedConfig = {
      name: workerName,
      main: entrypoint
    };
  }
  for (const env3 of workers) {
    const serviceTag = env3.tags?.find(
      (t) => t === `${SERVICE_TAG_PREFIX}${workerName}`
    );
    const envTag = env3.tags?.find((t) => t.startsWith(ENVIRONMENT_TAG_PREFIX));
    if (serviceTag !== `${SERVICE_TAG_PREFIX}${workerName}` || envTag === void 0) {
      continue;
    }
    const [_2, envName] = envTag.split("=");
    combinedConfig.env ??= {};
    combinedConfig.env[envName] = convertWorkerToWranglerConfig(env3);
  }
  return combinedConfig;
}
__name(constructWranglerConfig, "constructWranglerConfig");

// ../workers-utils/dist/chunk-O4YGOZSW.mjs
var MetricsRegistry = class {
  static {
    __name(this, "MetricsRegistry");
  }
  counters = [];
  /**
   * Create and register a new counter metric.
   *
   * @param name - The metric name (e.g. "service_request_total")
   * @param help - A human-readable description of the metric
   * @returns A Counter that can be incremented
   */
  createCounter(name, help) {
    const entry = { name, help, value: 0 };
    this.counters.push(entry);
    return {
      inc: /* @__PURE__ */ __name(() => {
        entry.value++;
      }, "inc"),
      add: /* @__PURE__ */ __name((amount) => {
        if (amount < 0) {
          throw new Error("Counter value cannot decrease");
        }
        entry.value += amount;
      }, "add")
    };
  }
  /**
   * Serialize all registered metrics in Prometheus text exposition format.
   *
   * @see https://prometheus.io/docs/instrumenting/exposition_formats/#text-based-format
   */
  metrics() {
    return this.counters.map((c) => {
      let result = "";
      if (c.help.length > 0) {
        result += `# HELP ${c.name} ${c.help}
`;
      }
      result += `# TYPE ${c.name} counter
`;
      result += `${c.name} ${c.value}
`;
      return result;
    }).join("");
  }
};

// ../workers-utils/dist/chunk-A4F3D336.mjs
var import_node_fs = __toESM(require("node:fs"), 1);
var import_node_path = __toESM(require("node:path"), 1);
var UserError = class extends Error {
  static {
    __name(this, "UserError");
  }
  telemetryMessage;
  constructor(message, options) {
    super(message, options);
    Object.setPrototypeOf(this, new.target.prototype);
    this.telemetryMessage = options?.telemetryMessage === true ? message : options?.telemetryMessage;
  }
};
var DeprecationError = class extends UserError {
  static {
    __name(this, "DeprecationError");
  }
  constructor(message, options) {
    super(`Deprecation:
${message}`, options);
  }
};
var FatalError = class extends UserError {
  constructor(message, code, options) {
    super(message, options);
    this.code = code;
  }
  static {
    __name(this, "FatalError");
  }
};
var CommandLineArgsError = class extends UserError {
  static {
    __name(this, "CommandLineArgsError");
  }
};
var JsonFriendlyFatalError = class extends FatalError {
  constructor(message, code, options) {
    super(message, code, options);
    this.code = code;
  }
  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, code, telemetryMessage) {
  if (isJson) {
    return new JsonFriendlyFatalError(
      JSON.stringify(message),
      code,
      telemetryMessage
    );
  } else {
    return new FatalError(`${message}`, code, telemetryMessage);
  }
}
__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(CharacterCodes2) {
  CharacterCodes2[CharacterCodes2["lineFeed"] = 10] = "lineFeed";
  CharacterCodes2[CharacterCodes2["carriageReturn"] = 13] = "carriageReturn";
  CharacterCodes2[CharacterCodes2["space"] = 32] = "space";
  CharacterCodes2[CharacterCodes2["_0"] = 48] = "_0";
  CharacterCodes2[CharacterCodes2["_1"] = 49] = "_1";
  CharacterCodes2[CharacterCodes2["_2"] = 50] = "_2";
  CharacterCodes2[CharacterCodes2["_3"] = 51] = "_3";
  CharacterCodes2[CharacterCodes2["_4"] = 52] = "_4";
  CharacterCodes2[CharacterCodes2["_5"] = 53] = "_5";
  CharacterCodes2[CharacterCodes2["_6"] = 54] = "_6";
  CharacterCodes2[CharacterCodes2["_7"] = 55] = "_7";
  CharacterCodes2[CharacterCodes2["_8"] = 56] = "_8";
  CharacterCodes2[CharacterCodes2["_9"] = 57] = "_9";
  CharacterCodes2[CharacterCodes2["a"] = 97] = "a";
  CharacterCodes2[CharacterCodes2["b"] = 98] = "b";
  CharacterCodes2[CharacterCodes2["c"] = 99] = "c";
  CharacterCodes2[CharacterCodes2["d"] = 100] = "d";
  CharacterCodes2[CharacterCodes2["e"] = 101] = "e";
  CharacterCodes2[CharacterCodes2["f"] = 102] = "f";
  CharacterCodes2[CharacterCodes2["g"] = 103] = "g";
  CharacterCodes2[CharacterCodes2["h"] = 104] = "h";
  CharacterCodes2[CharacterCodes2["i"] = 105] = "i";
  CharacterCodes2[CharacterCodes2["j"] = 106] = "j";
  CharacterCodes2[CharacterCodes2["k"] = 107] = "k";
  CharacterCodes2[CharacterCodes2["l"] = 108] = "l";
  CharacterCodes2[CharacterCodes2["m"] = 109] = "m";
  CharacterCodes2[CharacterCodes2["n"] = 110] = "n";
  CharacterCodes2[CharacterCodes2["o"] = 111] = "o";
  CharacterCodes2[CharacterCodes2["p"] = 112] = "p";
  CharacterCodes2[CharacterCodes2["q"] = 113] = "q";
  CharacterCodes2[CharacterCodes2["r"] = 114] = "r";
  CharacterCodes2[CharacterCodes2["s"] = 115] = "s";
  CharacterCodes2[CharacterCodes2["t"] = 116] = "t";
  CharacterCodes2[CharacterCodes2["u"] = 117] = "u";
  CharacterCodes2[CharacterCodes2["v"] = 118] = "v";
  CharacterCodes2[CharacterCodes2["w"] = 119] = "w";
  CharacterCodes2[CharacterCodes2["x"] = 120] = "x";
  CharacterCodes2[CharacterCodes2["y"] = 121] = "y";
  CharacterCodes2[CharacterCodes2["z"] = 122] = "z";
  CharacterCodes2[CharacterCodes2["A"] = 65] = "A";
  CharacterCodes2[CharacterCodes2["B"] = 66] = "B";
  CharacterCodes2[CharacterCodes2["C"] = 67] = "C";
  CharacterCodes2[CharacterCodes2["D"] = 68] = "D";
  CharacterCodes2[CharacterCodes2["E"] = 69] = "E";
  CharacterCodes2[CharacterCodes2["F"] = 70] = "F";
  CharacterCodes2[CharacterCodes2["G"] = 71] = "G";
  CharacterCodes2[CharacterCodes2["H"] = 72] = "H";
  CharacterCodes2[CharacterCodes2["I"] = 73] = "I";
  CharacterCodes2[CharacterCodes2["J"] = 74] = "J";
  CharacterCodes2[CharacterCodes2["K"] = 75] = "K";
  CharacterCodes2[CharacterCodes2["L"] = 76] = "L";
  CharacterCodes2[CharacterCodes2["M"] = 77] = "M";
  CharacterCodes2[CharacterCodes2["N"] = 78] = "N";
  CharacterCodes2[CharacterCodes2["O"] = 79] = "O";
  CharacterCodes2[CharacterCodes2["P"] = 80] = "P";
  CharacterCodes2[CharacterCodes2["Q"] = 81] = "Q";
  CharacterCodes2[CharacterCodes2["R"] = 82] = "R";
  CharacterCodes2[CharacterCodes2["S"] = 83] = "S";
  CharacterCodes2[CharacterCodes2["T"] = 84] = "T";
  CharacterCodes2[CharacterCodes2["U"] = 85] = "U";
  CharacterCodes2[CharacterCodes2["V"] = 86] = "V";
  CharacterCodes2[CharacterCodes2["W"] = 87] = "W";
  CharacterCodes2[CharacterCodes2["X"] = 88] = "X";
  CharacterCodes2[CharacterCodes2["Y"] = 89] = "Y";
  CharacterCodes2[CharacterCodes2["Z"] = 90] = "Z";
  CharacterCodes2[CharacterCodes2["asterisk"] = 42] = "asterisk";
  CharacterCodes2[CharacterCodes2["backslash"] = 92] = "backslash";
  CharacterCodes2[CharacterCodes2["closeBrace"] = 125] = "closeBrace";
  CharacterCodes2[CharacterCodes2["closeBracket"] = 93] = "closeBracket";
  CharacterCodes2[CharacterCodes2["colon"] = 58] = "colon";
  CharacterCodes2[CharacterCodes2["comma"] = 44] = "comma";
  CharacterCodes2[CharacterCodes2["dot"] = 46] = "dot";
  CharacterCodes2[CharacterCodes2["doubleQuote"] = 34] = "doubleQuote";
  CharacterCodes2[CharacterCodes2["minus"] = 45] = "minus";
  CharacterCodes2[CharacterCodes2["openBrace"] = 123] = "openBrace";
  CharacterCodes2[CharacterCodes2["openBracket"] = 91] = "openBracket";
  CharacterCodes2[CharacterCodes2["plus"] = 43] = "plus";
  CharacterCodes2[CharacterCodes2["slash"] = 47] = "slash";
  CharacterCodes2[CharacterCodes2["formFeed"] = 12] = "formFeed";
  CharacterCodes2[CharacterCodes2["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, offset2) {
  return "\r\n".indexOf(text.charAt(offset2)) !== -1;
}
__name(isEOL, "isEOL");
var ParseOptions;
(function(ParseOptions2) {
  ParseOptions2.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 object = {};
      onValue(object);
      previousParents.push(currentParent);
      currentParent = object;
      currentProperty = null;
    }, "onObjectBegin"),
    onObjectProperty: /* @__PURE__ */ __name((name) => {
      currentProperty = name;
    }, "onObjectProperty"),
    onObjectEnd: /* @__PURE__ */ __name(() => {
      currentParent = previousParents.pop();
    }, "onObjectEnd"),
    onArrayBegin: /* @__PURE__ */ __name(() => {
      const array = [];
      onValue(array);
      previousParents.push(currentParent);
      currentParent = array;
      currentProperty = null;
    }, "onArrayBegin"),
    onArrayEnd: /* @__PURE__ */ __name(() => {
      currentParent = previousParents.pop();
    }, "onArrayEnd"),
    onLiteralValue: onValue,
    onError: /* @__PURE__ */ __name((error, offset2, length) => {
      errors.push({ error, offset: offset2, 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((offset2) => {
      currentParent = onValue({ type: "object", offset: offset2, length: -1, parent: currentParent, children: [] });
    }, "onObjectBegin"),
    onObjectProperty: /* @__PURE__ */ __name((name, offset2, length) => {
      currentParent = onValue({ type: "property", offset: offset2, length: -1, parent: currentParent, children: [] });
      currentParent.children.push({ type: "string", value: name, offset: offset2, length, parent: currentParent });
    }, "onObjectProperty"),
    onObjectEnd: /* @__PURE__ */ __name((offset2, length) => {
      ensurePropertyComplete(offset2 + length);
      currentParent.length = offset2 + length - currentParent.offset;
      currentParent = currentParent.parent;
      ensurePropertyComplete(offset2 + length);
    }, "onObjectEnd"),
    onArrayBegin: /* @__PURE__ */ __name((offset2, length) => {
      currentParent = onValue({ type: "array", offset: offset2, length: -1, parent: currentParent, children: [] });
    }, "onArrayBegin"),
    onArrayEnd: /* @__PURE__ */ __name((offset2, length) => {
      currentParent.length = offset2 + length - currentParent.offset;
      currentParent = currentParent.parent;
      ensurePropertyComplete(offset2 + length);
    }, "onArrayEnd"),
    onLiteralValue: /* @__PURE__ */ __name((value, offset2, length) => {
      onValue({ type: getNodeType(value), offset: offset2, length, parent: currentParent, value });
      ensurePropertyComplete(offset2 + length);
    }, "onLiteralValue"),
    onSeparator: /* @__PURE__ */ __name((sep2, offset2, length) => {
      if (currentParent.type === "property") {
        if (sep2 === ":") {
          currentParent.colonOffset = offset2;
        } else if (sep2 === ",") {
          ensurePropertyComplete(offset2);
        }
      }
    }, "onSeparator"),
    onError: /* @__PURE__ */ __name((error, offset2, length) => {
      errors.push({ error, offset: offset2, 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(error, skipUntilAfter = [], skipUntil2 = []) {
    onError(error);
    if (skipUntilAfter.length + skipUntil2.length > 0) {
      let token = _scanner.getToken();
      while (token !== 17) {
        if (skipUntilAfter.indexOf(token) !== -1) {
          scanNext();
          break;
        } else if (skipUntil2.indexOf(token) !== -1) {
          break;
        }
        token = scanNext();
      }
    }
  }
  __name(handleError, "handleError");
  function parseString2(isValue) {
    const value = _scanner.getTokenValue();
    if (isValue) {
      onLiteralValue(value);
    } else {
      onObjectProperty(value);
      _jsonPath.push(value);
    }
    scanNext();
    return true;
  }
  __name(parseString2, "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;
    }
    parseString2(false);
    if (_scanner.getToken() === 6) {
      onSeparator(":");
      scanNext();
      if (!parseValue2()) {
        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 parseArray2() {
    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 (!parseValue2()) {
        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(parseArray2, "parseArray");
  function parseValue2() {
    switch (_scanner.getToken()) {
      case 3:
        return parseArray2();
      case 1:
        return parseObject();
      case 10:
        return parseString2(true);
      default:
        return parseLiteral();
    }
  }
  __name(parseValue2, "parseValue");
  scanNext();
  if (_scanner.getToken() === 17) {
    if (options.allowEmptyContent) {
      return true;
    }
    handleError(4, [], []);
    return false;
  }
  if (!parseValue2()) {
    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((p) => p.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 offset2 = previous.offset + previous.length;
        let parentEndOffset = parent.offset + parent.length;
        edit = { offset: offset2, length: parentEndOffset - 2 - offset2, 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(ScanError2) {
  ScanError2[ScanError2["None"] = 0] = "None";
  ScanError2[ScanError2["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
  ScanError2[ScanError2["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
  ScanError2[ScanError2["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
  ScanError2[ScanError2["InvalidUnicode"] = 4] = "InvalidUnicode";
  ScanError2[ScanError2["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
  ScanError2[ScanError2["InvalidCharacter"] = 6] = "InvalidCharacter";
})(ScanError || (ScanError = {}));
var SyntaxKind;
(function(SyntaxKind2) {
  SyntaxKind2[SyntaxKind2["OpenBraceToken"] = 1] = "OpenBraceToken";
  SyntaxKind2[SyntaxKind2["CloseBraceToken"] = 2] = "CloseBraceToken";
  SyntaxKind2[SyntaxKind2["OpenBracketToken"] = 3] = "OpenBracketToken";
  SyntaxKind2[SyntaxKind2["CloseBracketToken"] = 4] = "CloseBracketToken";
  SyntaxKind2[SyntaxKind2["CommaToken"] = 5] = "CommaToken";
  SyntaxKind2[SyntaxKind2["ColonToken"] = 6] = "ColonToken";
  SyntaxKind2[SyntaxKind2["NullKeyword"] = 7] = "NullKeyword";
  SyntaxKind2[SyntaxKind2["TrueKeyword"] = 8] = "TrueKeyword";
  SyntaxKind2[SyntaxKind2["FalseKeyword"] = 9] = "FalseKeyword";
  SyntaxKind2[SyntaxKind2["StringLiteral"] = 10] = "StringLiteral";
  SyntaxKind2[SyntaxKind2["NumericLiteral"] = 11] = "NumericLiteral";
  SyntaxKind2[SyntaxKind2["LineCommentTrivia"] = 12] = "LineCommentTrivia";
  SyntaxKind2[SyntaxKind2["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
  SyntaxKind2[SyntaxKind2["LineBreakTrivia"] = 14] = "LineBreakTrivia";
  SyntaxKind2[SyntaxKind2["Trivia"] = 15] = "Trivia";
  SyntaxKind2[SyntaxKind2["Unknown"] = 16] = "Unknown";
  SyntaxKind2[SyntaxKind2["EOF"] = 17] = "EOF";
})(SyntaxKind || (SyntaxKind = {}));
var parse2 = parse;
var ParseErrorCode;
(function(ParseErrorCode2) {
  ParseErrorCode2[ParseErrorCode2["InvalidSymbol"] = 1] = "InvalidSymbol";
  ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
  ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"] = 3] = "PropertyNameExpected";
  ParseErrorCode2[ParseErrorCode2["ValueExpected"] = 4] = "ValueExpected";
  ParseErrorCode2[ParseErrorCode2["ColonExpected"] = 5] = "ColonExpected";
  ParseErrorCode2[ParseErrorCode2["CommaExpected"] = 6] = "CommaExpected";
  ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"] = 7] = "CloseBraceExpected";
  ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"] = 8] = "CloseBracketExpected";
  ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"] = 9] = "EndOfFileExpected";
  ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"] = 10] = "InvalidCommentToken";
  ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
  ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
  ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
  ParseErrorCode2[ParseErrorCode2["InvalidUnicode"] = 14] = "InvalidUnicode";
  ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
  ParseErrorCode2[ParseErrorCode2["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(string, ptr) {
  let lines = string.slice(0, ptr).split(/\r\n|\n|\r/g);
  return [lines.length, lines.pop().length + 1];
}
__name(getLineColFromPtr, "getLineColFromPtr");
function makeCodeBlock(string, line, column) {
  let lines = string.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 c = str[i];
    if (c === "\n")
      return i;
    if (c === "\r" && str[i + 1] === "\n")
      return i + 1;
    if (c < " " && c !== "	" || c === "\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 c;
  while ((c = str[ptr]) === " " || c === "	" || !banNewLines && (c === "\n" || c === "\r" && str[ptr + 1] === "\n"))
    ptr++;
  return banComments || c !== "#" ? 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 c = str[i];
    if (c === "#") {
      i = indexOfNewline(str, i);
    } else if (c === sep2) {
      return i + 1;
    } else if (c === end || banNewLines && (c === "\n" || c === "\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(date) {
    let hasDate = true;
    let hasTime = true;
    let offset2 = "Z";
    if (typeof date === "string") {
      let match = date.match(DATE_TIME_RE);
      if (match) {
        if (!match[1]) {
          hasDate = false;
          date = `0000-01-01T${date}`;
        }
        hasTime = !!match[2];
        hasTime && date[10] === " " && (date = date.replace(" ", "T"));
        if (match[2] && +match[2] > 23) {
          date = "";
        } else {
          offset2 = match[3] || null;
          date = date.toUpperCase();
          if (!offset2 && hasTime)
            date += "Z";
        }
      } else {
        date = "";
      }
    }
    super(date);
    if (!isNaN(this.getTime())) {
      this.#hasDate = hasDate;
      this.#hasTime = hasTime;
      this.#offset = offset2;
    }
  }
  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 offset2 = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
    offset2 = this.#offset[0] === "-" ? offset2 : -offset2;
    let offsetDate = new Date(this.getTime() - offset2 * 6e4);
    return offsetDate.toISOString().slice(0, -1) + this.#offset;
  }
  static wrapAsOffsetDateTime(jsDate, offset2 = "Z") {
    let date = new _TomlDate(jsDate);
    date.#offset = offset2;
    return date;
  }
  static wrapAsLocalDateTime(jsDate) {
    let date = new _TomlDate(jsDate);
    date.#offset = null;
    return date;
  }
  static wrapAsLocalDate(jsDate) {
    let date = new _TomlDate(jsDate);
    date.#hasTime = false;
    date.#offset = null;
    return date;
  }
  static wrapAsLocalTime(jsDate) {
    let date = new _TomlDate(jsDate);
    date.#hasDate = false;
    date.#offset = null;
    return date;
  }
};
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 c = str[ptr++];
    if (c === "\n" || c === "\r" && str[ptr] === "\n") {
      if (!isMultiline) {
        throw new TomlError("newlines are not allowed in strings", {
          toml: str,
          ptr: ptr - 1
        });
      }
    } else if (c < " " && c !== "	" || c === "\x7F") {
      throw new TomlError("control characters are not allowed in strings", {
        toml: str,
        ptr: ptr - 1
      });
    }
    if (isEscape) {
      isEscape = false;
      if (c === "u" || c === "U") {
        let code = str.slice(ptr, ptr += c === "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 && (c === "\n" || c === " " || c === "	" || c === "\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 (c in ESC_MAP) {
        parsed += ESC_MAP[c];
      } else {
        throw new TomlError("unrecognized escape sequence", {
          toml: str,
          ptr: tmp
        });
      }
      sliceStart = ptr;
    } else if (!isLiteral && c === "\\") {
      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 date = new TomlDate(value);
  if (!date.isValid()) {
    throw new TomlError("invalid value", {
      toml,
      ptr
    });
  }
  return date;
}
__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 c = str[ptr];
  if (c === "[" || c === "{") {
    let [value, endPtr2] = c === "[" ? 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 (c === '"' || c === "'") {
    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 c = str[ptr = ++dot];
    if (c !== " " && c !== "	") {
      if (c === '"' || c === "'") {
        if (c === str[ptr + 1] && c === 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 c;
  let comma = 0;
  ptr++;
  while ((c = str[ptr++]) !== "}" && c) {
    let err = { toml: str, ptr: ptr - 1 };
    if (c === "\n") {
      throw new TomlError("newlines are not allowed in inline tables", err);
    } else if (c === "#") {
      throw new TomlError("inline tables cannot contain comments", err);
    } else if (c === ",") {
      throw new TomlError("expected key-value, found comma", err);
    } else if (c !== " " && c !== "	") {
      let k;
      let t = res;
      let hasOwn2 = false;
      let [key, keyEndPtr] = parseKey(str, ptr - 1);
      for (let i = 0; i < key.length; i++) {
        if (i)
          t = hasOwn2 ? t[k] : t[k] = {};
        k = key[i];
        if ((hasOwn2 = 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 (!hasOwn2 && k === "__proto__") {
          Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
        }
      }
      if (hasOwn2) {
        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 (!c) {
    throw new TomlError("unfinished table encountered", {
      toml: str,
      ptr
    });
  }
  return [res, ptr];
}
__name(parseInlineTable, "parseInlineTable");
function parseArray(str, ptr, depth, integersAsBigInt) {
  let res = [];
  let c;
  ptr++;
  while ((c = str[ptr++]) !== "]" && c) {
    if (c === ",") {
      throw new TomlError("expected value, found comma", {
        toml: str,
        ptr: ptr - 1
      });
    } else if (c === "#")
      ptr = skipComment(str, ptr);
    else if (c !== " " && c !== "	" && c !== "\n" && c !== "\r") {
      let e = extractValue(str, ptr - 1, "]", depth - 1, integersAsBigInt);
      res.push(e[0]);
      ptr = e[1];
    }
  }
  if (!c) {
    throw new TomlError("unfinished array encountered", {
      toml: str,
      ptr
    });
  }
  return [res, ptr];
}
__name(parseArray, "parseArray");
function peekTable(key, table, meta, type) {
  let t = table;
  let m2 = meta;
  let k;
  let hasOwn2 = false;
  let state;
  for (let i = 0; i < key.length; i++) {
    if (i) {
      t = hasOwn2 ? t[k] : t[k] = {};
      m2 = (state = m2[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];
        m2 = m2[l].c;
      }
    }
    k = key[i];
    if ((hasOwn2 = Object.hasOwn(t, k)) && m2[k]?.t === 0 && m2[k]?.d) {
      return null;
    }
    if (!hasOwn2) {
      if (k === "__proto__") {
        Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
        Object.defineProperty(m2, k, { enumerable: true, configurable: true, writable: true });
      }
      m2[k] = {
        t: i < key.length - 1 && type === 2 ? 3 : type,
        d: false,
        i: 0,
        c: {}
      };
    }
  }
  state = m2[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 = hasOwn2 ? t[k] : t[k] = {};
  } else if (type === 0 && hasOwn2) {
    return null;
  }
  return [k, t, state.c];
}
__name(peekTable, "peekTable");
function parse3(toml, { maxDepth = 1e3, integersAsBigInt } = {}) {
  let res = {};
  let meta = {};
  let tbl = res;
  let m2 = meta;
  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 p = peekTable(
        k[0],
        res,
        meta,
        isTableArray ? 2 : 1
        /* Type.EXPLICIT */
      );
      if (!p) {
        throw new TomlError("trying to redefine an already defined table or value", {
          toml,
          ptr
        });
      }
      m2 = p[2];
      tbl = p[1];
      ptr = k[1];
    } else {
      let k = parseKey(toml, ptr);
      let p = peekTable(
        k[0],
        tbl,
        m2,
        0
        /* Type.DOTTED */
      );
      if (!p) {
        throw new TomlError("trying to redefine an already defined table or value", {
          toml,
          ptr
        });
      }
      let v2 = extractValue(toml, k[1], void 0, maxDepth, integersAsBigInt);
      p[1][p[0]] = v2[0];
      ptr = v2[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(array, depth, numberAsFloat) {
  if (array.length === 0)
    return "[]";
  let res = "[ ";
  for (let i = 0; i < array.length; i++) {
    if (i)
      res += ", ";
    if (array[i] === null || array[i] === void 0) {
      throw new TypeError("arrays cannot contain null or undefined values");
    }
    res += stringifyValue(array[i], extendedTypeOf(array[i]), depth - 1, numberAsFloat);
  }
  return res + " ]";
}
__name(stringifyArray, "stringifyArray");
function stringifyArrayTable(array, 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 < array.length; i++) {
    res += `${res && "\n"}[[${key}]]
`;
    res += stringifyTable(0, array[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;
  constructor({ status: status2, ...rest }) {
    super(rest);
    this.name = this.constructor.name;
    this.#status = status2;
  }
  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, file2) {
  return parseJSON(input, file2);
}
__name(parsePackageJSON, "parsePackageJSON");
function parseJSON(input, file2) {
  return parseJSONC(input, file2, {
    allowEmptyContent: false,
    allowTrailingComma: false,
    disallowComments: true
  });
}
__name(parseJSON, "parseJSON");
function parseJSONC(input, file2, options = { allowTrailingComma: true }) {
  const errors = [];
  const data2 = parse2(input, errors, options);
  if (errors.length) {
    throw new ParseError({
      text: printParseErrorCode(errors[0].error),
      location: {
        ...indexLocation({ file: file2, fileText: input }, errors[0].offset + 1),
        length: errors[0].length
      },
      telemetryMessage: "JSON(C) parse error"
    });
  }
  return data2;
}
__name(parseJSONC, "parseJSONC");
function readFileSyncToBuffer(file2) {
  try {
    return (0, import_node_fs.readFileSync)(file2);
  } catch (err) {
    const { message } = err;
    throw new ParseError({
      text: `Could not read file: ${file2}`,
      notes: [
        {
          text: message.replace(file2, (0, import_node_path.resolve)(file2))
        }
      ]
    });
  }
}
__name(readFileSyncToBuffer, "readFileSyncToBuffer");
function readFileSync(file2) {
  try {
    const buffer = (0, import_node_fs.readFileSync)(file2);
    return removeBOMAndValidate(buffer, file2);
  } catch (err) {
    if (err instanceof ParseError) {
      throw err;
    }
    const { message } = err;
    throw new ParseError({
      text: `Could not read file: ${file2}`,
      notes: [
        {
          text: message.replace(file2, (0, import_node_path.resolve)(file2))
        }
      ],
      telemetryMessage: "Could not read file"
    });
  }
}
__name(readFileSync, "readFileSync");
function indexLocation(file2, index) {
  let lineText, line = 0, column = 0, cursor = 0;
  const { fileText = "" } = file2;
  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, ...file2 };
}
__name(indexLocation, "indexLocation");
function searchLocation(file2, query) {
  let lineText, length, line = 0, column = 0;
  const queryText = String(query);
  const { fileText = "" } = file2;
  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, ...file2 };
}
__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 base2 = 1;
  for (const [name, _2] of unitsMap) {
    if (s.endsWith(name)) {
      s = s.substring(0, s.length - name.length);
      base2 = unitsMap.get(name) || 1;
      break;
    }
  }
  return Number(s) * base2;
}
__name(parseHumanDuration, "parseHumanDuration");
function parseNonHyphenedUuid(uuid) {
  if (uuid == null || uuid.includes("-")) {
    return uuid;
  }
  if (uuid.length != 32) {
    return null;
  }
  const uuid_parts = [];
  uuid_parts.push(uuid.slice(0, 8));
  uuid_parts.push(uuid.slice(8, 12));
  uuid_parts.push(uuid.slice(12, 16));
  uuid_parts.push(uuid.slice(16, 20));
  uuid_parts.push(uuid.slice(20));
  let hyphenated = "";
  uuid_parts.forEach((part) => hyphenated += part + "-");
  return hyphenated.slice(0, 36);
}
__name(parseNonHyphenedUuid, "parseNonHyphenedUuid");
function parseByteSize(s, base2 = 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(base2 ?? (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, file2) {
  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 "${file2}" appears to be encoded as ${bom.encoding}. Please save the file as UTF-8 without BOM.`
          }
        ],
        location: { file: file2, 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");
function absolute(input, root) {
  return (0, import_node_path.isAbsolute)(input) ? input : (0, import_node_path.resolve)(root || ".", input);
}
__name(absolute, "absolute");
function up(base2, options) {
  let { last, cwd: cwd2 } = options || {};
  let tmp = absolute(base2, cwd2);
  let root = absolute(last || "/", cwd2);
  let prev, arr = [];
  while (prev !== root) {
    arr.push(tmp);
    tmp = (0, import_node_path.dirname)(prev = tmp);
    if (tmp === prev) break;
  }
  return arr;
}
__name(up, "up");
function file(name, options) {
  let dir, tmp;
  let start = options && options.cwd || "";
  for (dir of up(start, options)) {
    try {
      tmp = (0, import_node_path.join)(dir, name);
      if ((0, import_node_fs.statSync)(tmp).isFile()) return tmp;
    } catch {
    }
  }
}
__name(file, "file");
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 _a, _b;
        return (_b = (_a = match.match(/[\t ]/g)) === null || _a === void 0 ? void 0 : _a.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 string = strings[0];
  values.forEach(function(value, i) {
    var endentations = string.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");
    }
    string += indentedValue + strings[i + 1];
  });
  return string;
}
__name(dedent, "dedent");
var esm_default = dedent;
function resolveWranglerConfigPath({
  config,
  script
}, options) {
  if (config !== void 0) {
    return {
      userConfigPath: config,
      configPath: config,
      deployConfigPath: void 0,
      redirected: false
    };
  }
  const leafPath = script !== void 0 ? import_node_path.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_path.default.resolve(import_node_path.default.dirname(deployConfigPath), deployConfig.configPath);
  } catch (e) {
    throw new UserError(
      `Failed to parse the deploy configuration file at ${import_node_path.default.relative(".", deployConfigPath)}`,
      { cause: e }
    );
  }
  if (!redirectedConfigPath) {
    throw new UserError(esm_default`
			A deploy configuration file was found at "${import_node_path.default.relative(".", deployConfigPath)}".
			But this is not valid - the required "configPath" property was not found.
			Instead this file contains:
			\`\`\`
			${deployConfigFile}
			\`\`\`
		`);
  }
  if (!(0, import_node_fs.existsSync)(redirectedConfigPath)) {
    throw new UserError(esm_default`
				There is a deploy configuration at "${import_node_path.default.relative(".", deployConfigPath)}".
				But the redirected configuration path it points to, "${import_node_path.default.relative(".", redirectedConfigPath)}", does not exist.
			`);
  }
  if (userConfigPath) {
    if (import_node_path.default.join(import_node_path.default.dirname(userConfigPath), PATH_TO_DEPLOY_CONFIG) !== deployConfigPath) {
      throw new UserError(esm_default`
					Found both a user configuration file at "${import_node_path.default.relative(".", userConfigPath)}"
					and a deploy configuration file at "${import_node_path.default.relative(".", deployConfigPath)}".
					But these do not share the same base path so it is not clear which should be used.
				`);
    }
  }
  return {
    configPath: redirectedConfigPath,
    deployConfigPath,
    redirected: true
  };
}
__name(findRedirectedWranglerConfig, "findRedirectedWranglerConfig");
function isRedirectedRawConfig(rawConfig, configPath, userConfigPath) {
  return configPath !== void 0 && 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");
function isDirectory(path210) {
  return import_node_fs.default.statSync(path210, { 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/index.mjs
var import_node_fs2 = __toESM(require("node:fs"), 1);
var import_node_assert2 = __toESM(require("node:assert"), 1);
var import_node_path2 = __toESM(require("node:path"), 1);
var import_node_os2 = __toESM(require("node:os"), 1);
var require_XDGAppPaths = __commonJS2({
  "../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/lib/XDGAppPaths.js"(exports2) {
    exports2.__esModule = true;
    exports2.Adapt = void 0;
    function isBoolean2(t2) {
      return typeOf(t2) === "boolean";
    }
    __name(isBoolean2, "isBoolean");
    function isObject(t2) {
      return typeOf(t2) === "object";
    }
    __name(isObject, "isObject");
    function isString2(t2) {
      return typeOf(t2) === "string";
    }
    __name(isString2, "isString");
    function typeOf(t2) {
      return typeof t2;
    }
    __name(typeOf, "typeOf");
    function Adapt(adapter_) {
      var meta = adapter_.meta, path410 = adapter_.path, xdg = adapter_.xdg;
      var XDGAppPaths_ = /* @__PURE__ */ (function() {
        function XDGAppPaths_2(options_) {
          if (options_ === void 0) {
            options_ = {};
          }
          var _a, _b, _c;
          function XDGAppPaths(options2) {
            if (options2 === void 0) {
              options2 = {};
            }
            return new XDGAppPaths_2(options2);
          }
          __name(XDGAppPaths, "XDGAppPaths");
          var options = isObject(options_) ? options_ : { name: options_ };
          var suffix = (_a = options.suffix) !== null && _a !== void 0 ? _a : "";
          var isolated_ = (_b = options.isolated) !== null && _b !== void 0 ? _b : true;
          var namePriorityList = [
            options.name,
            meta.pkgMainFilename(),
            meta.mainFilename()
          ];
          var nameFallback = "$eval";
          var name = path410.parse(((_c = namePriorityList.find(function(e2) {
            return isString2(e2);
          })) !== null && _c !== void 0 ? _c : nameFallback) + suffix).name;
          XDGAppPaths.$name = /* @__PURE__ */ __name(function $name() {
            return name;
          }, "$name");
          XDGAppPaths.$isolated = /* @__PURE__ */ __name(function $isolated() {
            return isolated_;
          }, "$isolated");
          function isIsolated(dirOptions) {
            var _a2;
            dirOptions = dirOptions !== null && dirOptions !== void 0 ? dirOptions : { isolated: isolated_ };
            var isolated = isBoolean2(dirOptions) ? dirOptions : (_a2 = dirOptions.isolated) !== null && _a2 !== void 0 ? _a2 : isolated_;
            return isolated;
          }
          __name(isIsolated, "isIsolated");
          function finalPathSegment(dirOptions) {
            return isIsolated(dirOptions) ? name : "";
          }
          __name(finalPathSegment, "finalPathSegment");
          XDGAppPaths.cache = /* @__PURE__ */ __name(function cache(dirOptions) {
            return path410.join(xdg.cache(), finalPathSegment(dirOptions));
          }, "cache");
          XDGAppPaths.config = /* @__PURE__ */ __name(function config(dirOptions) {
            return path410.join(xdg.config(), finalPathSegment(dirOptions));
          }, "config");
          XDGAppPaths.data = /* @__PURE__ */ __name(function data2(dirOptions) {
            return path410.join(xdg.data(), finalPathSegment(dirOptions));
          }, "data");
          XDGAppPaths.runtime = /* @__PURE__ */ __name(function runtime(dirOptions) {
            return xdg.runtime() ? path410.join(xdg.runtime(), finalPathSegment(dirOptions)) : void 0;
          }, "runtime");
          XDGAppPaths.state = /* @__PURE__ */ __name(function state(dirOptions) {
            return path410.join(xdg.state(), finalPathSegment(dirOptions));
          }, "state");
          XDGAppPaths.configDirs = /* @__PURE__ */ __name(function configDirs(dirOptions) {
            return xdg.configDirs().map(function(s) {
              return path410.join(s, finalPathSegment(dirOptions));
            });
          }, "configDirs");
          XDGAppPaths.dataDirs = /* @__PURE__ */ __name(function dataDirs(dirOptions) {
            return xdg.dataDirs().map(function(s) {
              return path410.join(s, finalPathSegment(dirOptions));
            });
          }, "dataDirs");
          return XDGAppPaths;
        }
        __name(XDGAppPaths_2, "XDGAppPaths_");
        return XDGAppPaths_2;
      })();
      return { XDGAppPaths: new XDGAppPaths_() };
    }
    __name(Adapt, "Adapt");
    exports2.Adapt = Adapt;
  }
});
var require_XDG = __commonJS2({
  "../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/lib/XDG.js"(exports2) {
    var __spreadArray2 = exports2 && exports2.__spreadArray || function(to, from) {
      for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
      return to;
    };
    exports2.__esModule = true;
    exports2.Adapt = void 0;
    function Adapt(adapter_) {
      var env3 = adapter_.env, osPaths = adapter_.osPaths, path410 = adapter_.path;
      var isMacOS = /^darwin$/i.test(adapter_.process.platform);
      var isWinOS = /^win/i.test(adapter_.process.platform);
      function baseDir() {
        return osPaths.home() || osPaths.temp();
      }
      __name(baseDir, "baseDir");
      function valOrPath(val, pathSegments) {
        return val || path410.join.apply(path410, pathSegments);
      }
      __name(valOrPath, "valOrPath");
      var linux = /* @__PURE__ */ __name(function() {
        var cache = /* @__PURE__ */ __name(function() {
          return valOrPath(env3.get("XDG_CACHE_HOME"), [baseDir(), ".cache"]);
        }, "cache");
        var config = /* @__PURE__ */ __name(function() {
          return valOrPath(env3.get("XDG_CONFIG_HOME"), [baseDir(), ".config"]);
        }, "config");
        var data2 = /* @__PURE__ */ __name(function() {
          return valOrPath(env3.get("XDG_DATA_HOME"), [baseDir(), ".local", "share"]);
        }, "data");
        var runtime = /* @__PURE__ */ __name(function() {
          return env3.get("XDG_RUNTIME_DIR") || void 0;
        }, "runtime");
        var state = /* @__PURE__ */ __name(function() {
          return valOrPath(env3.get("XDG_STATE_HOME"), [baseDir(), ".local", "state"]);
        }, "state");
        return { cache, config, data: data2, runtime, state };
      }, "linux");
      var macos = /* @__PURE__ */ __name(function() {
        var cache = /* @__PURE__ */ __name(function() {
          return valOrPath(env3.get("XDG_CACHE_HOME"), [baseDir(), "Library", "Caches"]);
        }, "cache");
        var config = /* @__PURE__ */ __name(function() {
          return valOrPath(env3.get("XDG_CONFIG_HOME"), [baseDir(), "Library", "Preferences"]);
        }, "config");
        var data2 = /* @__PURE__ */ __name(function() {
          return valOrPath(env3.get("XDG_DATA_HOME"), [baseDir(), "Library", "Application Support"]);
        }, "data");
        var runtime = /* @__PURE__ */ __name(function() {
          return env3.get("XDG_RUNTIME_DIR") || void 0;
        }, "runtime");
        var state = /* @__PURE__ */ __name(function() {
          return valOrPath(env3.get("XDG_STATE_HOME"), [baseDir(), "Library", "State"]);
        }, "state");
        return { cache, config, data: data2, runtime, state };
      }, "macos");
      var windows = /* @__PURE__ */ __name(function() {
        function appData() {
          return valOrPath(env3.get("APPDATA"), [baseDir(), "AppData", "Roaming"]);
        }
        __name(appData, "appData");
        function localAppData() {
          return valOrPath(env3.get("LOCALAPPDATA"), [baseDir(), "AppData", "Local"]);
        }
        __name(localAppData, "localAppData");
        var cache = /* @__PURE__ */ __name(function() {
          return valOrPath(env3.get("XDG_CACHE_HOME"), [localAppData(), "xdg.cache"]);
        }, "cache");
        var config = /* @__PURE__ */ __name(function() {
          return valOrPath(env3.get("XDG_CONFIG_HOME"), [appData(), "xdg.config"]);
        }, "config");
        var data2 = /* @__PURE__ */ __name(function() {
          return valOrPath(env3.get("XDG_DATA_HOME"), [appData(), "xdg.data"]);
        }, "data");
        var runtime = /* @__PURE__ */ __name(function() {
          return env3.get("XDG_RUNTIME_DIR") || void 0;
        }, "runtime");
        var state = /* @__PURE__ */ __name(function() {
          return valOrPath(env3.get("XDG_STATE_HOME"), [localAppData(), "xdg.state"]);
        }, "state");
        return { cache, config, data: data2, runtime, state };
      }, "windows");
      var XDG_ = /* @__PURE__ */ (function() {
        function XDG_2() {
          function XDG() {
            return new XDG_2();
          }
          __name(XDG, "XDG");
          var extension = isMacOS ? macos() : isWinOS ? windows() : linux();
          XDG.cache = extension.cache;
          XDG.config = extension.config;
          XDG.data = extension.data;
          XDG.runtime = extension.runtime;
          XDG.state = extension.state;
          XDG.configDirs = /* @__PURE__ */ __name(function configDirs() {
            var pathList = env3.get("XDG_CONFIG_DIRS");
            return __spreadArray2([extension.config()], pathList ? pathList.split(path410.delimiter) : []);
          }, "configDirs");
          XDG.dataDirs = /* @__PURE__ */ __name(function dataDirs() {
            var pathList = env3.get("XDG_DATA_DIRS");
            return __spreadArray2([extension.data()], pathList ? pathList.split(path410.delimiter) : []);
          }, "dataDirs");
          return XDG;
        }
        __name(XDG_2, "XDG_");
        return XDG_2;
      })();
      return { XDG: new XDG_() };
    }
    __name(Adapt, "Adapt");
    exports2.Adapt = Adapt;
  }
});
var require_OSPaths = __commonJS2({
  "../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/lib/OSPaths.js"(exports2) {
    var __spreadArray2 = exports2 && exports2.__spreadArray || function(to, from) {
      for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
      return to;
    };
    exports2.__esModule = true;
    exports2.Adapt = void 0;
    function isEmpty(s) {
      return !s;
    }
    __name(isEmpty, "isEmpty");
    function Adapt(adapter_) {
      var env3 = adapter_.env, os22 = adapter_.os, path410 = adapter_.path;
      var isWinOS = /^win/i.test(adapter_.process.platform);
      function normalizePath2(path_) {
        return path_ ? adapter_.path.normalize(adapter_.path.join(path_, ".")) : void 0;
      }
      __name(normalizePath2, "normalizePath");
      function home() {
        var posix = /* @__PURE__ */ __name(function() {
          return normalizePath2((typeof os22.homedir === "function" ? os22.homedir() : void 0) || env3.get("HOME"));
        }, "posix");
        var windows = /* @__PURE__ */ __name(function() {
          var priorityList = [
            typeof os22.homedir === "function" ? os22.homedir() : void 0,
            env3.get("USERPROFILE"),
            env3.get("HOME"),
            env3.get("HOMEDRIVE") || env3.get("HOMEPATH") ? path410.join(env3.get("HOMEDRIVE") || "", env3.get("HOMEPATH") || "") : void 0
          ];
          return normalizePath2(priorityList.find(function(v2) {
            return !isEmpty(v2);
          }));
        }, "windows");
        return isWinOS ? windows() : posix();
      }
      __name(home, "home");
      function temp() {
        function joinPathToBase(base2, segments) {
          return base2 ? path410.join.apply(path410, __spreadArray2([base2], segments)) : void 0;
        }
        __name(joinPathToBase, "joinPathToBase");
        function posix() {
          var fallback = "/tmp";
          var priorityList = [
            typeof os22.tmpdir === "function" ? os22.tmpdir() : void 0,
            env3.get("TMPDIR"),
            env3.get("TEMP"),
            env3.get("TMP")
          ];
          return normalizePath2(priorityList.find(function(v2) {
            return !isEmpty(v2);
          })) || fallback;
        }
        __name(posix, "posix");
        function windows() {
          var fallback = "C:\\Temp";
          var priorityListLazy = [
            typeof os22.tmpdir === "function" ? os22.tmpdir : function() {
              return void 0;
            },
            function() {
              return env3.get("TEMP");
            },
            function() {
              return env3.get("TMP");
            },
            function() {
              return joinPathToBase(env3.get("LOCALAPPDATA"), ["Temp"]);
            },
            function() {
              return joinPathToBase(home(), ["AppData", "Local", "Temp"]);
            },
            function() {
              return joinPathToBase(env3.get("ALLUSERSPROFILE"), ["Temp"]);
            },
            function() {
              return joinPathToBase(env3.get("SystemRoot"), ["Temp"]);
            },
            function() {
              return joinPathToBase(env3.get("windir"), ["Temp"]);
            },
            function() {
              return joinPathToBase(env3.get("SystemDrive"), ["\\", "Temp"]);
            }
          ];
          var v2 = priorityListLazy.find(function(v22) {
            return v22 && !isEmpty(v22());
          });
          return v2 && normalizePath2(v2()) || fallback;
        }
        __name(windows, "windows");
        return isWinOS ? windows() : posix();
      }
      __name(temp, "temp");
      var OSPaths_ = /* @__PURE__ */ (function() {
        function OSPaths_2() {
          function OSPaths() {
            return new OSPaths_2();
          }
          __name(OSPaths, "OSPaths");
          OSPaths.home = home;
          OSPaths.temp = temp;
          return OSPaths;
        }
        __name(OSPaths_2, "OSPaths_");
        return OSPaths_2;
      })();
      return { OSPaths: new OSPaths_() };
    }
    __name(Adapt, "Adapt");
    exports2.Adapt = Adapt;
  }
});
var require_node = __commonJS2({
  "../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/platform-adapters/node.js"(exports2) {
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      Object.defineProperty(o, k2, { enumerable: true, get: /* @__PURE__ */ __name(function() {
        return m2[k];
      }, "get") });
    } : function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    } : function(o, v2) {
      o["default"] = v2;
    });
    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;
    };
    exports2.__esModule = true;
    exports2.adapter = void 0;
    var os22 = __importStar2(__require("os"));
    var path410 = __importStar2(__require("path"));
    exports2.adapter = {
      atImportPermissions: { env: true },
      env: {
        get: /* @__PURE__ */ __name(function(s) {
          return process.env[s];
        }, "get")
      },
      os: os22,
      path: path410,
      process
    };
  }
});
var require_mod_cjs = __commonJS2({
  "../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/mod.cjs.js"(exports2, module2) {
    var OSPaths_js_1 = require_OSPaths();
    var node_js_1 = require_node();
    module2.exports = OSPaths_js_1.Adapt(node_js_1.adapter).OSPaths;
  }
});
var require_node2 = __commonJS2({
  "../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/platform-adapters/node.js"(exports2) {
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      Object.defineProperty(o, k2, { enumerable: true, get: /* @__PURE__ */ __name(function() {
        return m2[k];
      }, "get") });
    } : function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    } : function(o, v2) {
      o["default"] = v2;
    });
    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 };
    };
    exports2.__esModule = true;
    exports2.adapter = void 0;
    var path410 = __importStar2(__require("path"));
    var os_paths_1 = __importDefault2(require_mod_cjs());
    exports2.adapter = {
      atImportPermissions: { env: true },
      env: {
        get: /* @__PURE__ */ __name(function(s) {
          return process.env[s];
        }, "get")
      },
      osPaths: os_paths_1["default"],
      path: path410,
      process
    };
  }
});
var require_mod_cjs2 = __commonJS2({
  "../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/mod.cjs.js"(exports2, module2) {
    var XDG_js_1 = require_XDG();
    var node_js_1 = require_node2();
    module2.exports = XDG_js_1.Adapt(node_js_1.adapter).XDG;
  }
});
var require_node3 = __commonJS2({
  "../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/platform-adapters/node.js"(exports2) {
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      Object.defineProperty(o, k2, { enumerable: true, get: /* @__PURE__ */ __name(function() {
        return m2[k];
      }, "get") });
    } : function(o, m2, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m2[k];
    });
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v2) {
      Object.defineProperty(o, "default", { enumerable: true, value: v2 });
    } : function(o, v2) {
      o["default"] = v2;
    });
    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 };
    };
    exports2.__esModule = true;
    exports2.adapter = void 0;
    var path410 = __importStar2(__require("path"));
    var xdg_portable_1 = __importDefault2(require_mod_cjs2());
    exports2.adapter = {
      atImportPermissions: { env: true, read: true },
      meta: {
        mainFilename: /* @__PURE__ */ __name(function() {
          var requireMain = typeof __require !== "undefined" && __require !== null && __require.main ? __require.main : { filename: void 0 };
          var requireMainFilename = requireMain.filename;
          var filename = (requireMainFilename !== process.execArgv[0] ? requireMainFilename : void 0) || (typeof process._eval === "undefined" ? process.argv[1] : void 0);
          return filename;
        }, "mainFilename"),
        pkgMainFilename: /* @__PURE__ */ __name(function() {
          return process.pkg ? process.execPath : void 0;
        }, "pkgMainFilename")
      },
      path: path410,
      process,
      xdg: xdg_portable_1["default"]
    };
  }
});
var require_mod_cjs3 = __commonJS2({
  "../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/mod.cjs.js"(exports2, module2) {
    var XDGAppPaths_js_1 = require_XDGAppPaths();
    var node_js_1 = require_node3();
    module2.exports = XDGAppPaths_js_1.Adapt(node_js_1.adapter).XDGAppPaths;
  }
});
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,
  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: [],
  hyperdrive: [],
  workflows: [],
  secrets_store_secrets: [],
  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 */
  legacy_env: true,
  site: void 0,
  wasm_modules: void 0,
  text_blobs: void 0,
  data_blobs: void 0,
  keep_vars: void 0,
  alias: 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: [],
  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 },
  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 util;
(function(util22) {
  util22.assertEqual = (val) => val;
  function assertIs(_arg) {
  }
  __name(assertIs, "assertIs");
  util22.assertIs = assertIs;
  function assertNever22(_x) {
    throw new Error();
  }
  __name(assertNever22, "assertNever");
  util22.assertNever = assertNever22;
  util22.arrayToEnum = (items) => {
    const obj = {};
    for (const item of items) {
      obj[item] = item;
    }
    return obj;
  };
  util22.getValidEnumValues = (obj) => {
    const validKeys = util22.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
    const filtered = {};
    for (const k of validKeys) {
      filtered[k] = obj[k];
    }
    return util22.objectValues(filtered);
  };
  util22.objectValues = (obj) => {
    return util22.objectKeys(obj).map(function(e2) {
      return obj[e2];
    });
  };
  util22.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
    const keys = [];
    for (const key in object) {
      if (Object.prototype.hasOwnProperty.call(object, key)) {
        keys.push(key);
      }
    }
    return keys;
  };
  util22.find = (arr, checker) => {
    for (const item of arr) {
      if (checker(item))
        return item;
    }
    return void 0;
  };
  util22.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
  function joinValues(array, separator = " | ") {
    return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
  }
  __name(joinValues, "joinValues");
  util22.joinValues = joinValues;
  util22.jsonStringifyReplacer = (_2, value) => {
    if (typeof value === "bigint") {
      return value.toString();
    }
    return value;
  };
})(util || (util = {}));
var objectUtil;
(function(objectUtil22) {
  objectUtil22.mergeShapes = (first, second) => {
    return {
      ...first,
      ...second
      // second overwrites first
    };
  };
})(objectUtil || (objectUtil = {}));
var ZodParsedType = util.arrayToEnum([
  "string",
  "nan",
  "number",
  "integer",
  "float",
  "boolean",
  "date",
  "bigint",
  "symbol",
  "function",
  "undefined",
  "null",
  "array",
  "object",
  "unknown",
  "promise",
  "void",
  "never",
  "map",
  "set"
]);
var getParsedType = /* @__PURE__ */ __name((data2) => {
  const t2 = typeof data2;
  switch (t2) {
    case "undefined":
      return ZodParsedType.undefined;
    case "string":
      return ZodParsedType.string;
    case "number":
      return isNaN(data2) ? ZodParsedType.nan : ZodParsedType.number;
    case "boolean":
      return ZodParsedType.boolean;
    case "function":
      return ZodParsedType.function;
    case "bigint":
      return ZodParsedType.bigint;
    case "symbol":
      return ZodParsedType.symbol;
    case "object":
      if (Array.isArray(data2)) {
        return ZodParsedType.array;
      }
      if (data2 === null) {
        return ZodParsedType.null;
      }
      if (data2.then && typeof data2.then === "function" && data2.catch && typeof data2.catch === "function") {
        return ZodParsedType.promise;
      }
      if (typeof Map !== "undefined" && data2 instanceof Map) {
        return ZodParsedType.map;
      }
      if (typeof Set !== "undefined" && data2 instanceof Set) {
        return ZodParsedType.set;
      }
      if (typeof Date !== "undefined" && data2 instanceof Date) {
        return ZodParsedType.date;
      }
      return ZodParsedType.object;
    default:
      return ZodParsedType.unknown;
  }
}, "getParsedType");
var ZodIssueCode = util.arrayToEnum([
  "invalid_type",
  "invalid_literal",
  "custom",
  "invalid_union",
  "invalid_union_discriminator",
  "invalid_enum_value",
  "unrecognized_keys",
  "invalid_arguments",
  "invalid_return_type",
  "invalid_date",
  "invalid_string",
  "too_small",
  "too_big",
  "invalid_intersection_types",
  "not_multiple_of",
  "not_finite"
]);
var quotelessJson = /* @__PURE__ */ __name((obj) => {
  const json = JSON.stringify(obj, null, 2);
  return json.replace(/"([^"]+)":/g, "$1:");
}, "quotelessJson");
var ZodError = class extends Error {
  static {
    __name(this, "ZodError");
  }
  constructor(issues) {
    super();
    this.issues = [];
    this.addIssue = (sub) => {
      this.issues = [...this.issues, sub];
    };
    this.addIssues = (subs = []) => {
      this.issues = [...this.issues, ...subs];
    };
    const actualProto = new.target.prototype;
    if (Object.setPrototypeOf) {
      Object.setPrototypeOf(this, actualProto);
    } else {
      this.__proto__ = actualProto;
    }
    this.name = "ZodError";
    this.issues = issues;
  }
  get errors() {
    return this.issues;
  }
  format(_mapper) {
    const mapper = _mapper || function(issue) {
      return issue.message;
    };
    const fieldErrors = { _errors: [] };
    const processError = /* @__PURE__ */ __name((error) => {
      for (const issue of error.issues) {
        if (issue.code === "invalid_union") {
          issue.unionErrors.map(processError);
        } else if (issue.code === "invalid_return_type") {
          processError(issue.returnTypeError);
        } else if (issue.code === "invalid_arguments") {
          processError(issue.argumentsError);
        } else if (issue.path.length === 0) {
          fieldErrors._errors.push(mapper(issue));
        } else {
          let curr = fieldErrors;
          let i = 0;
          while (i < issue.path.length) {
            const el = issue.path[i];
            const terminal = i === issue.path.length - 1;
            if (!terminal) {
              curr[el] = curr[el] || { _errors: [] };
            } else {
              curr[el] = curr[el] || { _errors: [] };
              curr[el]._errors.push(mapper(issue));
            }
            curr = curr[el];
            i++;
          }
        }
      }
    }, "processError");
    processError(this);
    return fieldErrors;
  }
  toString() {
    return this.message;
  }
  get message() {
    return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
  }
  get isEmpty() {
    return this.issues.length === 0;
  }
  flatten(mapper = (issue) => issue.message) {
    const fieldErrors = {};
    const formErrors = [];
    for (const sub of this.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 };
  }
  get formErrors() {
    return this.flatten();
  }
};
ZodError.create = (issues) => {
  const error = new ZodError(issues);
  return error;
};
var errorMap = /* @__PURE__ */ __name((issue, _ctx) => {
  let message;
  switch (issue.code) {
    case ZodIssueCode.invalid_type:
      if (issue.received === ZodParsedType.undefined) {
        message = "Required";
      } else {
        message = `Expected ${issue.expected}, received ${issue.received}`;
      }
      break;
    case ZodIssueCode.invalid_literal:
      message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
      break;
    case ZodIssueCode.unrecognized_keys:
      message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
      break;
    case ZodIssueCode.invalid_union:
      message = `Invalid input`;
      break;
    case ZodIssueCode.invalid_union_discriminator:
      message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
      break;
    case ZodIssueCode.invalid_enum_value:
      message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
      break;
    case ZodIssueCode.invalid_arguments:
      message = `Invalid function arguments`;
      break;
    case ZodIssueCode.invalid_return_type:
      message = `Invalid function return type`;
      break;
    case ZodIssueCode.invalid_date:
      message = `Invalid date`;
      break;
    case ZodIssueCode.invalid_string:
      if (typeof issue.validation === "object") {
        if ("includes" in issue.validation) {
          message = `Invalid input: must include "${issue.validation.includes}"`;
          if (typeof issue.validation.position === "number") {
            message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
          }
        } else if ("startsWith" in issue.validation) {
          message = `Invalid input: must start with "${issue.validation.startsWith}"`;
        } else if ("endsWith" in issue.validation) {
          message = `Invalid input: must end with "${issue.validation.endsWith}"`;
        } else {
          util.assertNever(issue.validation);
        }
      } else if (issue.validation !== "regex") {
        message = `Invalid ${issue.validation}`;
      } else {
        message = "Invalid";
      }
      break;
    case ZodIssueCode.too_small:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.too_big:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "bigint")
        message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.custom:
      message = `Invalid input`;
      break;
    case ZodIssueCode.invalid_intersection_types:
      message = `Intersection results could not be merged`;
      break;
    case ZodIssueCode.not_multiple_of:
      message = `Number must be a multiple of ${issue.multipleOf}`;
      break;
    case ZodIssueCode.not_finite:
      message = "Number must be finite";
      break;
    default:
      message = _ctx.defaultError;
      util.assertNever(issue);
  }
  return { message };
}, "errorMap");
var overrideErrorMap = errorMap;
function setErrorMap(map) {
  overrideErrorMap = map;
}
__name(setErrorMap, "setErrorMap");
function getErrorMap() {
  return overrideErrorMap;
}
__name(getErrorMap, "getErrorMap");
var makeIssue = /* @__PURE__ */ __name((params) => {
  const { data: data2, path: path410, errorMaps, issueData } = params;
  const fullPath = [...path410, ...issueData.path || []];
  const fullIssue = {
    ...issueData,
    path: fullPath
  };
  let errorMessage = "";
  const maps = errorMaps.filter((m2) => !!m2).slice().reverse();
  for (const map of maps) {
    errorMessage = map(fullIssue, { data: data2, defaultError: errorMessage }).message;
  }
  return {
    ...issueData,
    path: fullPath,
    message: issueData.message || errorMessage
  };
}, "makeIssue");
var EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
  const issue = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      ctx.schemaErrorMap,
      getErrorMap(),
      errorMap
      // then global default map
    ].filter((x2) => !!x2)
  });
  ctx.common.issues.push(issue);
}
__name(addIssueToContext, "addIssueToContext");
var ParseStatus = class _ParseStatus {
  static {
    __name(this, "ParseStatus");
  }
  constructor() {
    this.value = "valid";
  }
  dirty() {
    if (this.value === "valid")
      this.value = "dirty";
  }
  abort() {
    if (this.value !== "aborted")
      this.value = "aborted";
  }
  static mergeArray(status2, results) {
    const arrayValue = [];
    for (const s of results) {
      if (s.status === "aborted")
        return INVALID;
      if (s.status === "dirty")
        status2.dirty();
      arrayValue.push(s.value);
    }
    return { status: status2.value, value: arrayValue };
  }
  static async mergeObjectAsync(status2, pairs) {
    const syncPairs = [];
    for (const pair of pairs) {
      syncPairs.push({
        key: await pair.key,
        value: await pair.value
      });
    }
    return _ParseStatus.mergeObjectSync(status2, syncPairs);
  }
  static mergeObjectSync(status2, pairs) {
    const finalObject = {};
    for (const pair of pairs) {
      const { key, value } = pair;
      if (key.status === "aborted")
        return INVALID;
      if (value.status === "aborted")
        return INVALID;
      if (key.status === "dirty")
        status2.dirty();
      if (value.status === "dirty")
        status2.dirty();
      if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
        finalObject[key.value] = value.value;
      }
    }
    return { status: status2.value, value: finalObject };
  }
};
var INVALID = Object.freeze({
  status: "aborted"
});
var DIRTY = /* @__PURE__ */ __name((value) => ({ status: "dirty", value }), "DIRTY");
var OK = /* @__PURE__ */ __name((value) => ({ status: "valid", value }), "OK");
var isAborted = /* @__PURE__ */ __name((x2) => x2.status === "aborted", "isAborted");
var isDirty = /* @__PURE__ */ __name((x2) => x2.status === "dirty", "isDirty");
var isValid = /* @__PURE__ */ __name((x2) => x2.status === "valid", "isValid");
var isAsync = /* @__PURE__ */ __name((x2) => typeof Promise !== "undefined" && x2 instanceof Promise, "isAsync");
var errorUtil;
(function(errorUtil22) {
  errorUtil22.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  errorUtil22.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
})(errorUtil || (errorUtil = {}));
var ParseInputLazyPath = class {
  static {
    __name(this, "ParseInputLazyPath");
  }
  constructor(parent, value, path410, key) {
    this._cachedPath = [];
    this.parent = parent;
    this.data = value;
    this._path = path410;
    this._key = key;
  }
  get path() {
    if (!this._cachedPath.length) {
      if (this._key instanceof Array) {
        this._cachedPath.push(...this._path, ...this._key);
      } else {
        this._cachedPath.push(...this._path, this._key);
      }
    }
    return this._cachedPath;
  }
};
var handleResult = /* @__PURE__ */ __name((ctx, result) => {
  if (isValid(result)) {
    return { success: true, data: result.value };
  } else {
    if (!ctx.common.issues.length) {
      throw new Error("Validation failed but no issues detected.");
    }
    return {
      success: false,
      get error() {
        if (this._error)
          return this._error;
        const error = new ZodError(ctx.common.issues);
        this._error = error;
        return this._error;
      }
    };
  }
}, "handleResult");
function processCreateParams(params) {
  if (!params)
    return {};
  const { errorMap: errorMap22, invalid_type_error, required_error, description } = params;
  if (errorMap22 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap22)
    return { errorMap: errorMap22, description };
  const customMap = /* @__PURE__ */ __name((iss, ctx) => {
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    if (typeof ctx.data === "undefined") {
      return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
    }
    return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
  }, "customMap");
  return { errorMap: customMap, description };
}
__name(processCreateParams, "processCreateParams");
var ZodType = class {
  static {
    __name(this, "ZodType");
  }
  constructor(def) {
    this.spa = this.safeParseAsync;
    this._def = def;
    this.parse = this.parse.bind(this);
    this.safeParse = this.safeParse.bind(this);
    this.parseAsync = this.parseAsync.bind(this);
    this.safeParseAsync = this.safeParseAsync.bind(this);
    this.spa = this.spa.bind(this);
    this.refine = this.refine.bind(this);
    this.refinement = this.refinement.bind(this);
    this.superRefine = this.superRefine.bind(this);
    this.optional = this.optional.bind(this);
    this.nullable = this.nullable.bind(this);
    this.nullish = this.nullish.bind(this);
    this.array = this.array.bind(this);
    this.promise = this.promise.bind(this);
    this.or = this.or.bind(this);
    this.and = this.and.bind(this);
    this.transform = this.transform.bind(this);
    this.brand = this.brand.bind(this);
    this.default = this.default.bind(this);
    this.catch = this.catch.bind(this);
    this.describe = this.describe.bind(this);
    this.pipe = this.pipe.bind(this);
    this.readonly = this.readonly.bind(this);
    this.isNullable = this.isNullable.bind(this);
    this.isOptional = this.isOptional.bind(this);
  }
  get description() {
    return this._def.description;
  }
  _getType(input) {
    return getParsedType(input.data);
  }
  _getOrReturnCtx(input, ctx) {
    return ctx || {
      common: input.parent.common,
      data: input.data,
      parsedType: getParsedType(input.data),
      schemaErrorMap: this._def.errorMap,
      path: input.path,
      parent: input.parent
    };
  }
  _processInputParams(input) {
    return {
      status: new ParseStatus(),
      ctx: {
        common: input.parent.common,
        data: input.data,
        parsedType: getParsedType(input.data),
        schemaErrorMap: this._def.errorMap,
        path: input.path,
        parent: input.parent
      }
    };
  }
  _parseSync(input) {
    const result = this._parse(input);
    if (isAsync(result)) {
      throw new Error("Synchronous parse encountered promise.");
    }
    return result;
  }
  _parseAsync(input) {
    const result = this._parse(input);
    return Promise.resolve(result);
  }
  parse(data2, params) {
    const result = this.safeParse(data2, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  safeParse(data2, params) {
    var _a;
    const ctx = {
      common: {
        issues: [],
        async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
        contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
      },
      path: (params === null || params === void 0 ? void 0 : params.path) || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data: data2,
      parsedType: getParsedType(data2)
    };
    const result = this._parseSync({ data: data2, path: ctx.path, parent: ctx });
    return handleResult(ctx, result);
  }
  async parseAsync(data2, params) {
    const result = await this.safeParseAsync(data2, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  async safeParseAsync(data2, params) {
    const ctx = {
      common: {
        issues: [],
        contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
        async: true
      },
      path: (params === null || params === void 0 ? void 0 : params.path) || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data: data2,
      parsedType: getParsedType(data2)
    };
    const maybeAsyncResult = this._parse({ data: data2, path: ctx.path, parent: ctx });
    const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
    return handleResult(ctx, result);
  }
  refine(check, message) {
    const getIssueProperties = /* @__PURE__ */ __name((val) => {
      if (typeof message === "string" || typeof message === "undefined") {
        return { message };
      } else if (typeof message === "function") {
        return message(val);
      } else {
        return message;
      }
    }, "getIssueProperties");
    return this._refinement((val, ctx) => {
      const result = check(val);
      const setError = /* @__PURE__ */ __name(() => ctx.addIssue({
        code: ZodIssueCode.custom,
        ...getIssueProperties(val)
      }), "setError");
      if (typeof Promise !== "undefined" && result instanceof Promise) {
        return result.then((data2) => {
          if (!data2) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      if (!result) {
        setError();
        return false;
      } else {
        return true;
      }
    });
  }
  refinement(check, refinementData) {
    return this._refinement((val, ctx) => {
      if (!check(val)) {
        ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
        return false;
      } else {
        return true;
      }
    });
  }
  _refinement(refinement) {
    return new ZodEffects({
      schema: this,
      typeName: ZodFirstPartyTypeKind.ZodEffects,
      effect: { type: "refinement", refinement }
    });
  }
  superRefine(refinement) {
    return this._refinement(refinement);
  }
  optional() {
    return ZodOptional.create(this, this._def);
  }
  nullable() {
    return ZodNullable.create(this, this._def);
  }
  nullish() {
    return this.nullable().optional();
  }
  array() {
    return ZodArray.create(this, this._def);
  }
  promise() {
    return ZodPromise.create(this, this._def);
  }
  or(option) {
    return ZodUnion.create([this, option], this._def);
  }
  and(incoming) {
    return ZodIntersection.create(this, incoming, this._def);
  }
  transform(transform) {
    return new ZodEffects({
      ...processCreateParams(this._def),
      schema: this,
      typeName: ZodFirstPartyTypeKind.ZodEffects,
      effect: { type: "transform", transform }
    });
  }
  default(def) {
    const defaultValueFunc = typeof def === "function" ? def : () => def;
    return new ZodDefault({
      ...processCreateParams(this._def),
      innerType: this,
      defaultValue: defaultValueFunc,
      typeName: ZodFirstPartyTypeKind.ZodDefault
    });
  }
  brand() {
    return new ZodBranded({
      typeName: ZodFirstPartyTypeKind.ZodBranded,
      type: this,
      ...processCreateParams(this._def)
    });
  }
  catch(def) {
    const catchValueFunc = typeof def === "function" ? def : () => def;
    return new ZodCatch({
      ...processCreateParams(this._def),
      innerType: this,
      catchValue: catchValueFunc,
      typeName: ZodFirstPartyTypeKind.ZodCatch
    });
  }
  describe(description) {
    const This = this.constructor;
    return new This({
      ...this._def,
      description
    });
  }
  pipe(target) {
    return ZodPipeline.create(this, target);
  }
  readonly() {
    return ZodReadonly.create(this);
  }
  isOptional() {
    return this.safeParse(void 0).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
};
var cuidRegex = /^c[^\s-]{8,}$/i;
var cuid2Regex = /^[a-z][a-z0-9]*$/;
var ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/;
var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u;
var ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
var ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
var datetimeRegex = /* @__PURE__ */ __name((args) => {
  if (args.precision) {
    if (args.offset) {
      return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
    } else {
      return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`);
    }
  } else if (args.precision === 0) {
    if (args.offset) {
      return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
    } else {
      return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
    }
  } else {
    if (args.offset) {
      return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
    } else {
      return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`);
    }
  }
}, "datetimeRegex");
function isValidIP(ip, version3) {
  if ((version3 === "v4" || !version3) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version3 === "v6" || !version3) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
__name(isValidIP, "isValidIP");
var ZodString = class _ZodString extends ZodType {
  static {
    __name(this, "ZodString");
  }
  constructor() {
    super(...arguments);
    this._regex = (regex2, validation, message) => this.refinement((data2) => regex2.test(data2), {
      validation,
      code: ZodIssueCode.invalid_string,
      ...errorUtil.errToObj(message)
    });
    this.nonempty = (message) => this.min(1, errorUtil.errToObj(message));
    this.trim = () => new _ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "trim" }]
    });
    this.toLowerCase = () => new _ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "toLowerCase" }]
    });
    this.toUpperCase = () => new _ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "toUpperCase" }]
    });
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = String(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.string) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(
        ctx2,
        {
          code: ZodIssueCode.invalid_type,
          expected: ZodParsedType.string,
          received: ctx2.parsedType
        }
        //
      );
      return INVALID;
    }
    const status2 = new ParseStatus();
    let ctx = void 0;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.length < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.length > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "length") {
        const tooBig = input.data.length > check.value;
        const tooSmall = input.data.length < check.value;
        if (tooBig || tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          if (tooBig) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          } else if (tooSmall) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          }
          status2.dirty();
        }
      } else if (check.kind === "email") {
        if (!emailRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "email",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "emoji") {
        if (!emojiRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "emoji",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "uuid") {
        if (!uuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "uuid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "cuid") {
        if (!cuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "cuid2") {
        if (!cuid2Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid2",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "ulid") {
        if (!ulidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ulid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "url") {
        try {
          new URL(input.data);
        } catch (_a) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "url",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "regex") {
        check.regex.lastIndex = 0;
        const testResult = check.regex.test(input.data);
        if (!testResult) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "regex",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "trim") {
        input.data = input.data.trim();
      } else if (check.kind === "includes") {
        if (!input.data.includes(check.value, check.position)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { includes: check.value, position: check.position },
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "toLowerCase") {
        input.data = input.data.toLowerCase();
      } else if (check.kind === "toUpperCase") {
        input.data = input.data.toUpperCase();
      } else if (check.kind === "startsWith") {
        if (!input.data.startsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { startsWith: check.value },
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "endsWith") {
        if (!input.data.endsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { endsWith: check.value },
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "datetime") {
        const regex2 = datetimeRegex(check);
        if (!regex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "datetime",
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "ip") {
        if (!isValidIP(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ip",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status2.value, value: input.data };
  }
  _addCheck(check) {
    return new _ZodString({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  email(message) {
    return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
  }
  url(message) {
    return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
  }
  emoji(message) {
    return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
  }
  uuid(message) {
    return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
  }
  cuid(message) {
    return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
  }
  cuid2(message) {
    return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
  }
  ulid(message) {
    return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
  }
  ip(options) {
    return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
  }
  datetime(options) {
    var _a;
    if (typeof options === "string") {
      return this._addCheck({
        kind: "datetime",
        precision: null,
        offset: false,
        message: options
      });
    }
    return this._addCheck({
      kind: "datetime",
      precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
      offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
      ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
    });
  }
  regex(regex2, message) {
    return this._addCheck({
      kind: "regex",
      regex: regex2,
      ...errorUtil.errToObj(message)
    });
  }
  includes(value, options) {
    return this._addCheck({
      kind: "includes",
      value,
      position: options === null || options === void 0 ? void 0 : options.position,
      ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
    });
  }
  startsWith(value, message) {
    return this._addCheck({
      kind: "startsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  endsWith(value, message) {
    return this._addCheck({
      kind: "endsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  min(minLength, message) {
    return this._addCheck({
      kind: "min",
      value: minLength,
      ...errorUtil.errToObj(message)
    });
  }
  max(maxLength, message) {
    return this._addCheck({
      kind: "max",
      value: maxLength,
      ...errorUtil.errToObj(message)
    });
  }
  length(len, message) {
    return this._addCheck({
      kind: "length",
      value: len,
      ...errorUtil.errToObj(message)
    });
  }
  get isDatetime() {
    return !!this._def.checks.find((ch) => ch.kind === "datetime");
  }
  get isEmail() {
    return !!this._def.checks.find((ch) => ch.kind === "email");
  }
  get isURL() {
    return !!this._def.checks.find((ch) => ch.kind === "url");
  }
  get isEmoji() {
    return !!this._def.checks.find((ch) => ch.kind === "emoji");
  }
  get isUUID() {
    return !!this._def.checks.find((ch) => ch.kind === "uuid");
  }
  get isCUID() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid");
  }
  get isCUID2() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid2");
  }
  get isULID() {
    return !!this._def.checks.find((ch) => ch.kind === "ulid");
  }
  get isIP() {
    return !!this._def.checks.find((ch) => ch.kind === "ip");
  }
  get minLength() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxLength() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
};
ZodString.create = (params) => {
  var _a;
  return new ZodString({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodString,
    coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
    ...processCreateParams(params)
  });
};
function floatSafeRemainder(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / Math.pow(10, decCount);
}
__name(floatSafeRemainder, "floatSafeRemainder");
var ZodNumber = class _ZodNumber extends ZodType {
  static {
    __name(this, "ZodNumber");
  }
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
    this.step = this.multipleOf;
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = Number(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.number) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.number,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    let ctx = void 0;
    const status2 = new ParseStatus();
    for (const check of this._def.checks) {
      if (check.kind === "int") {
        if (!util.isInteger(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: "integer",
            received: "float",
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (floatSafeRemainder(input.data, check.value) !== 0) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "finite") {
        if (!Number.isFinite(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_finite,
            message: check.message
          });
          status2.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status2.value, value: input.data };
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new _ZodNumber({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new _ZodNumber({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  int(message) {
    return this._addCheck({
      kind: "int",
      message: errorUtil.toString(message)
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  finite(message) {
    return this._addCheck({
      kind: "finite",
      message: errorUtil.toString(message)
    });
  }
  safe(message) {
    return this._addCheck({
      kind: "min",
      inclusive: true,
      value: Number.MIN_SAFE_INTEGER,
      message: errorUtil.toString(message)
    })._addCheck({
      kind: "max",
      inclusive: true,
      value: Number.MAX_SAFE_INTEGER,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxValue() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
  get isInt() {
    return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
  }
  get isFinite() {
    let max = null, min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
        return true;
      } else if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      } else if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return Number.isFinite(min) && Number.isFinite(max);
  }
};
ZodNumber.create = (params) => {
  return new ZodNumber({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodNumber,
    coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
    ...processCreateParams(params)
  });
};
var ZodBigInt = class _ZodBigInt extends ZodType {
  static {
    __name(this, "ZodBigInt");
  }
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = BigInt(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.bigint) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.bigint,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    let ctx = void 0;
    const status2 = new ParseStatus();
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            type: "bigint",
            minimum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            type: "bigint",
            maximum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (input.data % check.value !== BigInt(0)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status2.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status2.value, value: input.data };
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new _ZodBigInt({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new _ZodBigInt({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxValue() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
};
ZodBigInt.create = (params) => {
  var _a;
  return new ZodBigInt({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodBigInt,
    coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
    ...processCreateParams(params)
  });
};
var ZodBoolean = class extends ZodType {
  static {
    __name(this, "ZodBoolean");
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = Boolean(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.boolean) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.boolean,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodBoolean.create = (params) => {
  return new ZodBoolean({
    typeName: ZodFirstPartyTypeKind.ZodBoolean,
    coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
    ...processCreateParams(params)
  });
};
var ZodDate = class _ZodDate extends ZodType {
  static {
    __name(this, "ZodDate");
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = new Date(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.date) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.date,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    if (isNaN(input.data.getTime())) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_date
      });
      return INVALID;
    }
    const status2 = new ParseStatus();
    let ctx = void 0;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.getTime() < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            message: check.message,
            inclusive: true,
            exact: false,
            minimum: check.value,
            type: "date"
          });
          status2.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.getTime() > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            message: check.message,
            inclusive: true,
            exact: false,
            maximum: check.value,
            type: "date"
          });
          status2.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return {
      status: status2.value,
      value: new Date(input.data.getTime())
    };
  }
  _addCheck(check) {
    return new _ZodDate({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  min(minDate, message) {
    return this._addCheck({
      kind: "min",
      value: minDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  max(maxDate, message) {
    return this._addCheck({
      kind: "max",
      value: maxDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  get minDate() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min != null ? new Date(min) : null;
  }
  get maxDate() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max != null ? new Date(max) : null;
  }
};
ZodDate.create = (params) => {
  return new ZodDate({
    checks: [],
    coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
    typeName: ZodFirstPartyTypeKind.ZodDate,
    ...processCreateParams(params)
  });
};
var ZodSymbol = class extends ZodType {
  static {
    __name(this, "ZodSymbol");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.symbol) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.symbol,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodSymbol.create = (params) => {
  return new ZodSymbol({
    typeName: ZodFirstPartyTypeKind.ZodSymbol,
    ...processCreateParams(params)
  });
};
var ZodUndefined = class extends ZodType {
  static {
    __name(this, "ZodUndefined");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.undefined,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodUndefined.create = (params) => {
  return new ZodUndefined({
    typeName: ZodFirstPartyTypeKind.ZodUndefined,
    ...processCreateParams(params)
  });
};
var ZodNull = class extends ZodType {
  static {
    __name(this, "ZodNull");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.null) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.null,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodNull.create = (params) => {
  return new ZodNull({
    typeName: ZodFirstPartyTypeKind.ZodNull,
    ...processCreateParams(params)
  });
};
var ZodAny = class extends ZodType {
  static {
    __name(this, "ZodAny");
  }
  constructor() {
    super(...arguments);
    this._any = true;
  }
  _parse(input) {
    return OK(input.data);
  }
};
ZodAny.create = (params) => {
  return new ZodAny({
    typeName: ZodFirstPartyTypeKind.ZodAny,
    ...processCreateParams(params)
  });
};
var ZodUnknown = class extends ZodType {
  static {
    __name(this, "ZodUnknown");
  }
  constructor() {
    super(...arguments);
    this._unknown = true;
  }
  _parse(input) {
    return OK(input.data);
  }
};
ZodUnknown.create = (params) => {
  return new ZodUnknown({
    typeName: ZodFirstPartyTypeKind.ZodUnknown,
    ...processCreateParams(params)
  });
};
var ZodNever = class extends ZodType {
  static {
    __name(this, "ZodNever");
  }
  _parse(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.never,
      received: ctx.parsedType
    });
    return INVALID;
  }
};
ZodNever.create = (params) => {
  return new ZodNever({
    typeName: ZodFirstPartyTypeKind.ZodNever,
    ...processCreateParams(params)
  });
};
var ZodVoid = class extends ZodType {
  static {
    __name(this, "ZodVoid");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.void,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
};
ZodVoid.create = (params) => {
  return new ZodVoid({
    typeName: ZodFirstPartyTypeKind.ZodVoid,
    ...processCreateParams(params)
  });
};
var ZodArray = class _ZodArray extends ZodType {
  static {
    __name(this, "ZodArray");
  }
  _parse(input) {
    const { ctx, status: status2 } = this._processInputParams(input);
    const def = this._def;
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (def.exactLength !== null) {
      const tooBig = ctx.data.length > def.exactLength.value;
      const tooSmall = ctx.data.length < def.exactLength.value;
      if (tooBig || tooSmall) {
        addIssueToContext(ctx, {
          code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
          minimum: tooSmall ? def.exactLength.value : void 0,
          maximum: tooBig ? def.exactLength.value : void 0,
          type: "array",
          inclusive: true,
          exact: true,
          message: def.exactLength.message
        });
        status2.dirty();
      }
    }
    if (def.minLength !== null) {
      if (ctx.data.length < def.minLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_small,
          minimum: def.minLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.minLength.message
        });
        status2.dirty();
      }
    }
    if (def.maxLength !== null) {
      if (ctx.data.length > def.maxLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_big,
          maximum: def.maxLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.maxLength.message
        });
        status2.dirty();
      }
    }
    if (ctx.common.async) {
      return Promise.all([...ctx.data].map((item, i) => {
        return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
      })).then((result2) => {
        return ParseStatus.mergeArray(status2, result2);
      });
    }
    const result = [...ctx.data].map((item, i) => {
      return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
    });
    return ParseStatus.mergeArray(status2, result);
  }
  get element() {
    return this._def.type;
  }
  min(minLength, message) {
    return new _ZodArray({
      ...this._def,
      minLength: { value: minLength, message: errorUtil.toString(message) }
    });
  }
  max(maxLength, message) {
    return new _ZodArray({
      ...this._def,
      maxLength: { value: maxLength, message: errorUtil.toString(message) }
    });
  }
  length(len, message) {
    return new _ZodArray({
      ...this._def,
      exactLength: { value: len, message: errorUtil.toString(message) }
    });
  }
  nonempty(message) {
    return this.min(1, message);
  }
};
ZodArray.create = (schema, params) => {
  return new ZodArray({
    type: schema,
    minLength: null,
    maxLength: null,
    exactLength: null,
    typeName: ZodFirstPartyTypeKind.ZodArray,
    ...processCreateParams(params)
  });
};
function deepPartialify(schema) {
  if (schema instanceof ZodObject) {
    const newShape = {};
    for (const key in schema.shape) {
      const fieldSchema = schema.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema._def,
      shape: /* @__PURE__ */ __name(() => newShape, "shape")
    });
  } else if (schema instanceof ZodArray) {
    return new ZodArray({
      ...schema._def,
      type: deepPartialify(schema.element)
    });
  } else if (schema instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodTuple) {
    return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
  } else {
    return schema;
  }
}
__name(deepPartialify, "deepPartialify");
var ZodObject = class _ZodObject extends ZodType {
  static {
    __name(this, "ZodObject");
  }
  constructor() {
    super(...arguments);
    this._cached = null;
    this.nonstrict = this.passthrough;
    this.augment = this.extend;
  }
  _getCached() {
    if (this._cached !== null)
      return this._cached;
    const shape = this._def.shape();
    const keys = util.objectKeys(shape);
    return this._cached = { shape, keys };
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.object) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const { status: status2, ctx } = this._processInputParams(input);
    const { shape, keys: shapeKeys } = this._getCached();
    const extraKeys = [];
    if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
      for (const key in ctx.data) {
        if (!shapeKeys.includes(key)) {
          extraKeys.push(key);
        }
      }
    }
    const pairs = [];
    for (const key of shapeKeys) {
      const keyValidator = shape[key];
      const value = ctx.data[key];
      pairs.push({
        key: { status: "valid", value: key },
        value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (this._def.catchall instanceof ZodNever) {
      const unknownKeys = this._def.unknownKeys;
      if (unknownKeys === "passthrough") {
        for (const key of extraKeys) {
          pairs.push({
            key: { status: "valid", value: key },
            value: { status: "valid", value: ctx.data[key] }
          });
        }
      } else if (unknownKeys === "strict") {
        if (extraKeys.length > 0) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.unrecognized_keys,
            keys: extraKeys
          });
          status2.dirty();
        }
      } else if (unknownKeys === "strip") ;
      else {
        throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
      }
    } else {
      const catchall = this._def.catchall;
      for (const key of extraKeys) {
        const value = ctx.data[key];
        pairs.push({
          key: { status: "valid", value: key },
          value: catchall._parse(
            new ParseInputLazyPath(ctx, value, ctx.path, key)
            //, ctx.child(key), value, getParsedType(value)
          ),
          alwaysSet: key in ctx.data
        });
      }
    }
    if (ctx.common.async) {
      return Promise.resolve().then(async () => {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          syncPairs.push({
            key,
            value: await pair.value,
            alwaysSet: pair.alwaysSet
          });
        }
        return syncPairs;
      }).then((syncPairs) => {
        return ParseStatus.mergeObjectSync(status2, syncPairs);
      });
    } else {
      return ParseStatus.mergeObjectSync(status2, pairs);
    }
  }
  get shape() {
    return this._def.shape();
  }
  strict(message) {
    errorUtil.errToObj;
    return new _ZodObject({
      ...this._def,
      unknownKeys: "strict",
      ...message !== void 0 ? {
        errorMap: /* @__PURE__ */ __name((issue, ctx) => {
          var _a, _b, _c, _d;
          const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
          if (issue.code === "unrecognized_keys")
            return {
              message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError
            };
          return {
            message: defaultError
          };
        }, "errorMap")
      } : {}
    });
  }
  strip() {
    return new _ZodObject({
      ...this._def,
      unknownKeys: "strip"
    });
  }
  passthrough() {
    return new _ZodObject({
      ...this._def,
      unknownKeys: "passthrough"
    });
  }
  // const AugmentFactory =
  //   <Def extends ZodObjectDef>(def: Def) =>
  //   <Augmentation extends ZodRawShape>(
  //     augmentation: Augmentation
  //   ): ZodObject<
  //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
  //     Def["unknownKeys"],
  //     Def["catchall"]
  //   > => {
  //     return new ZodObject({
  //       ...def,
  //       shape: () => ({
  //         ...def.shape(),
  //         ...augmentation,
  //       }),
  //     }) as any;
  //   };
  extend(augmentation) {
    return new _ZodObject({
      ...this._def,
      shape: /* @__PURE__ */ __name(() => ({
        ...this._def.shape(),
        ...augmentation
      }), "shape")
    });
  }
  /**
   * Prior to zod@1.0.12 there was a bug in the
   * inferred type of merged objects. Please
   * upgrade if you are experiencing issues.
   */
  merge(merging) {
    const merged = new _ZodObject({
      unknownKeys: merging._def.unknownKeys,
      catchall: merging._def.catchall,
      shape: /* @__PURE__ */ __name(() => ({
        ...this._def.shape(),
        ...merging._def.shape()
      }), "shape"),
      typeName: ZodFirstPartyTypeKind.ZodObject
    });
    return merged;
  }
  // merge<
  //   Incoming extends AnyZodObject,
  //   Augmentation extends Incoming["shape"],
  //   NewOutput extends {
  //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  //       ? Augmentation[k]["_output"]
  //       : k extends keyof Output
  //       ? Output[k]
  //       : never;
  //   },
  //   NewInput extends {
  //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  //       ? Augmentation[k]["_input"]
  //       : k extends keyof Input
  //       ? Input[k]
  //       : never;
  //   }
  // >(
  //   merging: Incoming
  // ): ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"],
  //   NewOutput,
  //   NewInput
  // > {
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  setKey(key, schema) {
    return this.augment({ [key]: schema });
  }
  // merge<Incoming extends AnyZodObject>(
  //   merging: Incoming
  // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
  // ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"]
  // > {
  //   // const mergedShape = objectUtil.mergeShapes(
  //   //   this._def.shape(),
  //   //   merging._def.shape()
  //   // );
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  catchall(index) {
    return new _ZodObject({
      ...this._def,
      catchall: index
    });
  }
  pick(mask) {
    const shape = {};
    util.objectKeys(mask).forEach((key) => {
      if (mask[key] && this.shape[key]) {
        shape[key] = this.shape[key];
      }
    });
    return new _ZodObject({
      ...this._def,
      shape: /* @__PURE__ */ __name(() => shape, "shape")
    });
  }
  omit(mask) {
    const shape = {};
    util.objectKeys(this.shape).forEach((key) => {
      if (!mask[key]) {
        shape[key] = this.shape[key];
      }
    });
    return new _ZodObject({
      ...this._def,
      shape: /* @__PURE__ */ __name(() => shape, "shape")
    });
  }
  /**
   * @deprecated
   */
  deepPartial() {
    return deepPartialify(this);
  }
  partial(mask) {
    const newShape = {};
    util.objectKeys(this.shape).forEach((key) => {
      const fieldSchema = this.shape[key];
      if (mask && !mask[key]) {
        newShape[key] = fieldSchema;
      } else {
        newShape[key] = fieldSchema.optional();
      }
    });
    return new _ZodObject({
      ...this._def,
      shape: /* @__PURE__ */ __name(() => newShape, "shape")
    });
  }
  required(mask) {
    const newShape = {};
    util.objectKeys(this.shape).forEach((key) => {
      if (mask && !mask[key]) {
        newShape[key] = this.shape[key];
      } else {
        const fieldSchema = this.shape[key];
        let newField = fieldSchema;
        while (newField instanceof ZodOptional) {
          newField = newField._def.innerType;
        }
        newShape[key] = newField;
      }
    });
    return new _ZodObject({
      ...this._def,
      shape: /* @__PURE__ */ __name(() => newShape, "shape")
    });
  }
  keyof() {
    return createZodEnum(util.objectKeys(this.shape));
  }
};
ZodObject.create = (shape, params) => {
  return new ZodObject({
    shape: /* @__PURE__ */ __name(() => shape, "shape"),
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject.strictCreate = (shape, params) => {
  return new ZodObject({
    shape: /* @__PURE__ */ __name(() => shape, "shape"),
    unknownKeys: "strict",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject.lazycreate = (shape, params) => {
  return new ZodObject({
    shape,
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
var ZodUnion = class extends ZodType {
  static {
    __name(this, "ZodUnion");
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const options = this._def.options;
    function handleResults(results) {
      for (const result of results) {
        if (result.result.status === "valid") {
          return result.result;
        }
      }
      for (const result of results) {
        if (result.result.status === "dirty") {
          ctx.common.issues.push(...result.ctx.common.issues);
          return result.result;
        }
      }
      const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
    __name(handleResults, "handleResults");
    if (ctx.common.async) {
      return Promise.all(options.map(async (option) => {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        return {
          result: await option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: childCtx
          }),
          ctx: childCtx
        };
      })).then(handleResults);
    } else {
      let dirty = void 0;
      const issues = [];
      for (const option of options) {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        const result = option._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: childCtx
        });
        if (result.status === "valid") {
          return result;
        } else if (result.status === "dirty" && !dirty) {
          dirty = { result, ctx: childCtx };
        }
        if (childCtx.common.issues.length) {
          issues.push(childCtx.common.issues);
        }
      }
      if (dirty) {
        ctx.common.issues.push(...dirty.ctx.common.issues);
        return dirty.result;
      }
      const unionErrors = issues.map((issues2) => new ZodError(issues2));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
  }
  get options() {
    return this._def.options;
  }
};
ZodUnion.create = (types4, params) => {
  return new ZodUnion({
    options: types4,
    typeName: ZodFirstPartyTypeKind.ZodUnion,
    ...processCreateParams(params)
  });
};
var getDiscriminator = /* @__PURE__ */ __name((type) => {
  if (type instanceof ZodLazy) {
    return getDiscriminator(type.schema);
  } else if (type instanceof ZodEffects) {
    return getDiscriminator(type.innerType());
  } else if (type instanceof ZodLiteral) {
    return [type.value];
  } else if (type instanceof ZodEnum) {
    return type.options;
  } else if (type instanceof ZodNativeEnum) {
    return Object.keys(type.enum);
  } else if (type instanceof ZodDefault) {
    return getDiscriminator(type._def.innerType);
  } else if (type instanceof ZodUndefined) {
    return [void 0];
  } else if (type instanceof ZodNull) {
    return [null];
  } else {
    return null;
  }
}, "getDiscriminator");
var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
  static {
    __name(this, "ZodDiscriminatedUnion");
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const discriminator = this.discriminator;
    const discriminatorValue = ctx.data[discriminator];
    const option = this.optionsMap.get(discriminatorValue);
    if (!option) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union_discriminator,
        options: Array.from(this.optionsMap.keys()),
        path: [discriminator]
      });
      return INVALID;
    }
    if (ctx.common.async) {
      return option._parseAsync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    } else {
      return option._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    }
  }
  get discriminator() {
    return this._def.discriminator;
  }
  get options() {
    return this._def.options;
  }
  get optionsMap() {
    return this._def.optionsMap;
  }
  /**
   * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
   * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
   * have a different value for each object in the union.
   * @param discriminator the name of the discriminator property
   * @param types an array of object schemas
   * @param params
   */
  static create(discriminator, options, params) {
    const optionsMap = /* @__PURE__ */ new Map();
    for (const type of options) {
      const discriminatorValues = getDiscriminator(type.shape[discriminator]);
      if (!discriminatorValues) {
        throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
      }
      for (const value of discriminatorValues) {
        if (optionsMap.has(value)) {
          throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
        }
        optionsMap.set(value, type);
      }
    }
    return new _ZodDiscriminatedUnion({
      typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
      discriminator,
      options,
      optionsMap,
      ...processCreateParams(params)
    });
  }
};
function mergeValues(a, b) {
  const aType = getParsedType(a);
  const bType = getParsedType(b);
  if (a === b) {
    return { valid: true, data: a };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b);
    const sharedKeys = util.objectKeys(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 };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
    if (a.length !== b.length) {
      return { valid: false };
    }
    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 };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
    return { valid: true, data: a };
  } else {
    return { valid: false };
  }
}
__name(mergeValues, "mergeValues");
var ZodIntersection = class extends ZodType {
  static {
    __name(this, "ZodIntersection");
  }
  _parse(input) {
    const { status: status2, ctx } = this._processInputParams(input);
    const handleParsed = /* @__PURE__ */ __name((parsedLeft, parsedRight) => {
      if (isAborted(parsedLeft) || isAborted(parsedRight)) {
        return INVALID;
      }
      const merged = mergeValues(parsedLeft.value, parsedRight.value);
      if (!merged.valid) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_intersection_types
        });
        return INVALID;
      }
      if (isDirty(parsedLeft) || isDirty(parsedRight)) {
        status2.dirty();
      }
      return { status: status2.value, value: merged.data };
    }, "handleParsed");
    if (ctx.common.async) {
      return Promise.all([
        this._def.left._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        }),
        this._def.right._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        })
      ]).then(([left, right]) => handleParsed(left, right));
    } else {
      return handleParsed(this._def.left._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }), this._def.right._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }));
    }
  }
};
ZodIntersection.create = (left, right, params) => {
  return new ZodIntersection({
    left,
    right,
    typeName: ZodFirstPartyTypeKind.ZodIntersection,
    ...processCreateParams(params)
  });
};
var ZodTuple = class _ZodTuple extends ZodType {
  static {
    __name(this, "ZodTuple");
  }
  _parse(input) {
    const { status: status2, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (ctx.data.length < this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_small,
        minimum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      return INVALID;
    }
    const rest = this._def.rest;
    if (!rest && ctx.data.length > this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_big,
        maximum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      status2.dirty();
    }
    const items = [...ctx.data].map((item, itemIndex) => {
      const schema = this._def.items[itemIndex] || this._def.rest;
      if (!schema)
        return null;
      return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
    }).filter((x2) => !!x2);
    if (ctx.common.async) {
      return Promise.all(items).then((results) => {
        return ParseStatus.mergeArray(status2, results);
      });
    } else {
      return ParseStatus.mergeArray(status2, items);
    }
  }
  get items() {
    return this._def.items;
  }
  rest(rest) {
    return new _ZodTuple({
      ...this._def,
      rest
    });
  }
};
ZodTuple.create = (schemas, params) => {
  if (!Array.isArray(schemas)) {
    throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  }
  return new ZodTuple({
    items: schemas,
    typeName: ZodFirstPartyTypeKind.ZodTuple,
    rest: null,
    ...processCreateParams(params)
  });
};
var ZodRecord = class _ZodRecord extends ZodType {
  static {
    __name(this, "ZodRecord");
  }
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status: status2, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const pairs = [];
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    for (const key in ctx.data) {
      pairs.push({
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
        value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key))
      });
    }
    if (ctx.common.async) {
      return ParseStatus.mergeObjectAsync(status2, pairs);
    } else {
      return ParseStatus.mergeObjectSync(status2, pairs);
    }
  }
  get element() {
    return this._def.valueType;
  }
  static create(first, second, third) {
    if (second instanceof ZodType) {
      return new _ZodRecord({
        keyType: first,
        valueType: second,
        typeName: ZodFirstPartyTypeKind.ZodRecord,
        ...processCreateParams(third)
      });
    }
    return new _ZodRecord({
      keyType: ZodString.create(),
      valueType: first,
      typeName: ZodFirstPartyTypeKind.ZodRecord,
      ...processCreateParams(second)
    });
  }
};
var ZodMap = class extends ZodType {
  static {
    __name(this, "ZodMap");
  }
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status: status2, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.map) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.map,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    const pairs = [...ctx.data.entries()].map(([key, value], index) => {
      return {
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
        value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
      };
    });
    if (ctx.common.async) {
      const finalMap = /* @__PURE__ */ new Map();
      return Promise.resolve().then(async () => {
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          if (key.status === "aborted" || value.status === "aborted") {
            return INVALID;
          }
          if (key.status === "dirty" || value.status === "dirty") {
            status2.dirty();
          }
          finalMap.set(key.value, value.value);
        }
        return { status: status2.value, value: finalMap };
      });
    } else {
      const finalMap = /* @__PURE__ */ new Map();
      for (const pair of pairs) {
        const key = pair.key;
        const value = pair.value;
        if (key.status === "aborted" || value.status === "aborted") {
          return INVALID;
        }
        if (key.status === "dirty" || value.status === "dirty") {
          status2.dirty();
        }
        finalMap.set(key.value, value.value);
      }
      return { status: status2.value, value: finalMap };
    }
  }
};
ZodMap.create = (keyType, valueType, params) => {
  return new ZodMap({
    valueType,
    keyType,
    typeName: ZodFirstPartyTypeKind.ZodMap,
    ...processCreateParams(params)
  });
};
var ZodSet = class _ZodSet extends ZodType {
  static {
    __name(this, "ZodSet");
  }
  _parse(input) {
    const { status: status2, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.set) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.set,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const def = this._def;
    if (def.minSize !== null) {
      if (ctx.data.size < def.minSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_small,
          minimum: def.minSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.minSize.message
        });
        status2.dirty();
      }
    }
    if (def.maxSize !== null) {
      if (ctx.data.size > def.maxSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_big,
          maximum: def.maxSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.maxSize.message
        });
        status2.dirty();
      }
    }
    const valueType = this._def.valueType;
    function finalizeSet(elements2) {
      const parsedSet = /* @__PURE__ */ new Set();
      for (const element of elements2) {
        if (element.status === "aborted")
          return INVALID;
        if (element.status === "dirty")
          status2.dirty();
        parsedSet.add(element.value);
      }
      return { status: status2.value, value: parsedSet };
    }
    __name(finalizeSet, "finalizeSet");
    const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
    if (ctx.common.async) {
      return Promise.all(elements).then((elements2) => finalizeSet(elements2));
    } else {
      return finalizeSet(elements);
    }
  }
  min(minSize, message) {
    return new _ZodSet({
      ...this._def,
      minSize: { value: minSize, message: errorUtil.toString(message) }
    });
  }
  max(maxSize, message) {
    return new _ZodSet({
      ...this._def,
      maxSize: { value: maxSize, message: errorUtil.toString(message) }
    });
  }
  size(size, message) {
    return this.min(size, message).max(size, message);
  }
  nonempty(message) {
    return this.min(1, message);
  }
};
ZodSet.create = (valueType, params) => {
  return new ZodSet({
    valueType,
    minSize: null,
    maxSize: null,
    typeName: ZodFirstPartyTypeKind.ZodSet,
    ...processCreateParams(params)
  });
};
var ZodFunction = class _ZodFunction extends ZodType {
  static {
    __name(this, "ZodFunction");
  }
  constructor() {
    super(...arguments);
    this.validate = this.implement;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.function) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.function,
        received: ctx.parsedType
      });
      return INVALID;
    }
    function makeArgsIssue(args, error) {
      return makeIssue({
        data: args,
        path: ctx.path,
        errorMaps: [
          ctx.common.contextualErrorMap,
          ctx.schemaErrorMap,
          getErrorMap(),
          errorMap
        ].filter((x2) => !!x2),
        issueData: {
          code: ZodIssueCode.invalid_arguments,
          argumentsError: error
        }
      });
    }
    __name(makeArgsIssue, "makeArgsIssue");
    function makeReturnsIssue(returns, error) {
      return makeIssue({
        data: returns,
        path: ctx.path,
        errorMaps: [
          ctx.common.contextualErrorMap,
          ctx.schemaErrorMap,
          getErrorMap(),
          errorMap
        ].filter((x2) => !!x2),
        issueData: {
          code: ZodIssueCode.invalid_return_type,
          returnTypeError: error
        }
      });
    }
    __name(makeReturnsIssue, "makeReturnsIssue");
    const params = { errorMap: ctx.common.contextualErrorMap };
    const fn = ctx.data;
    if (this._def.returns instanceof ZodPromise) {
      const me = this;
      return OK(async function(...args) {
        const error = new ZodError([]);
        const parsedArgs = await me._def.args.parseAsync(args, params).catch((e2) => {
          error.addIssue(makeArgsIssue(args, e2));
          throw error;
        });
        const result = await Reflect.apply(fn, this, parsedArgs);
        const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e2) => {
          error.addIssue(makeReturnsIssue(result, e2));
          throw error;
        });
        return parsedReturns;
      });
    } else {
      const me = this;
      return OK(function(...args) {
        const parsedArgs = me._def.args.safeParse(args, params);
        if (!parsedArgs.success) {
          throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
        }
        const result = Reflect.apply(fn, this, parsedArgs.data);
        const parsedReturns = me._def.returns.safeParse(result, params);
        if (!parsedReturns.success) {
          throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
        }
        return parsedReturns.data;
      });
    }
  }
  parameters() {
    return this._def.args;
  }
  returnType() {
    return this._def.returns;
  }
  args(...items) {
    return new _ZodFunction({
      ...this._def,
      args: ZodTuple.create(items).rest(ZodUnknown.create())
    });
  }
  returns(returnType) {
    return new _ZodFunction({
      ...this._def,
      returns: returnType
    });
  }
  implement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  strictImplement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  static create(args, returns, params) {
    return new _ZodFunction({
      args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
      returns: returns || ZodUnknown.create(),
      typeName: ZodFirstPartyTypeKind.ZodFunction,
      ...processCreateParams(params)
    });
  }
};
var ZodLazy = class extends ZodType {
  static {
    __name(this, "ZodLazy");
  }
  get schema() {
    return this._def.getter();
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const lazySchema = this._def.getter();
    return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  }
};
ZodLazy.create = (getter, params) => {
  return new ZodLazy({
    getter,
    typeName: ZodFirstPartyTypeKind.ZodLazy,
    ...processCreateParams(params)
  });
};
var ZodLiteral = class extends ZodType {
  static {
    __name(this, "ZodLiteral");
  }
  _parse(input) {
    if (input.data !== this._def.value) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_literal,
        expected: this._def.value
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
  get value() {
    return this._def.value;
  }
};
ZodLiteral.create = (value, params) => {
  return new ZodLiteral({
    value,
    typeName: ZodFirstPartyTypeKind.ZodLiteral,
    ...processCreateParams(params)
  });
};
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
__name(createZodEnum, "createZodEnum");
var ZodEnum = class _ZodEnum extends ZodType {
  static {
    __name(this, "ZodEnum");
  }
  _parse(input) {
    if (typeof input.data !== "string") {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (this._def.values.indexOf(input.data) === -1) {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get options() {
    return this._def.values;
  }
  get enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Values() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  extract(values) {
    return _ZodEnum.create(values);
  }
  exclude(values) {
    return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
  }
};
ZodEnum.create = createZodEnum;
var ZodNativeEnum = class extends ZodType {
  static {
    __name(this, "ZodNativeEnum");
  }
  _parse(input) {
    const nativeEnumValues = util.getValidEnumValues(this._def.values);
    const ctx = this._getOrReturnCtx(input);
    if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (nativeEnumValues.indexOf(input.data) === -1) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get enum() {
    return this._def.values;
  }
};
ZodNativeEnum.create = (values, params) => {
  return new ZodNativeEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
    ...processCreateParams(params)
  });
};
var ZodPromise = class extends ZodType {
  static {
    __name(this, "ZodPromise");
  }
  unwrap() {
    return this._def.type;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.promise,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
    return OK(promisified.then((data2) => {
      return this._def.type.parseAsync(data2, {
        path: ctx.path,
        errorMap: ctx.common.contextualErrorMap
      });
    }));
  }
};
ZodPromise.create = (schema, params) => {
  return new ZodPromise({
    type: schema,
    typeName: ZodFirstPartyTypeKind.ZodPromise,
    ...processCreateParams(params)
  });
};
var ZodEffects = class extends ZodType {
  static {
    __name(this, "ZodEffects");
  }
  innerType() {
    return this._def.schema;
  }
  sourceType() {
    return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  }
  _parse(input) {
    const { status: status2, ctx } = this._processInputParams(input);
    const effect = this._def.effect || null;
    const checkCtx = {
      addIssue: /* @__PURE__ */ __name((arg) => {
        addIssueToContext(ctx, arg);
        if (arg.fatal) {
          status2.abort();
        } else {
          status2.dirty();
        }
      }, "addIssue"),
      get path() {
        return ctx.path;
      }
    };
    checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
    if (effect.type === "preprocess") {
      const processed = effect.transform(ctx.data, checkCtx);
      if (ctx.common.issues.length) {
        return {
          status: "dirty",
          value: ctx.data
        };
      }
      if (ctx.common.async) {
        return Promise.resolve(processed).then((processed2) => {
          return this._def.schema._parseAsync({
            data: processed2,
            path: ctx.path,
            parent: ctx
          });
        });
      } else {
        return this._def.schema._parseSync({
          data: processed,
          path: ctx.path,
          parent: ctx
        });
      }
    }
    if (effect.type === "refinement") {
      const executeRefinement = /* @__PURE__ */ __name((acc) => {
        const result = effect.refinement(acc, checkCtx);
        if (ctx.common.async) {
          return Promise.resolve(result);
        }
        if (result instanceof Promise) {
          throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
        }
        return acc;
      }, "executeRefinement");
      if (ctx.common.async === false) {
        const inner = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inner.status === "aborted")
          return INVALID;
        if (inner.status === "dirty")
          status2.dirty();
        executeRefinement(inner.value);
        return { status: status2.value, value: inner.value };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
          if (inner.status === "aborted")
            return INVALID;
          if (inner.status === "dirty")
            status2.dirty();
          return executeRefinement(inner.value).then(() => {
            return { status: status2.value, value: inner.value };
          });
        });
      }
    }
    if (effect.type === "transform") {
      if (ctx.common.async === false) {
        const base2 = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (!isValid(base2))
          return base2;
        const result = effect.transform(base2.value, checkCtx);
        if (result instanceof Promise) {
          throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
        }
        return { status: status2.value, value: result };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base2) => {
          if (!isValid(base2))
            return base2;
          return Promise.resolve(effect.transform(base2.value, checkCtx)).then((result) => ({ status: status2.value, value: result }));
        });
      }
    }
    util.assertNever(effect);
  }
};
ZodEffects.create = (schema, effect, params) => {
  return new ZodEffects({
    schema,
    typeName: ZodFirstPartyTypeKind.ZodEffects,
    effect,
    ...processCreateParams(params)
  });
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
  return new ZodEffects({
    schema,
    effect: { type: "preprocess", transform: preprocess },
    typeName: ZodFirstPartyTypeKind.ZodEffects,
    ...processCreateParams(params)
  });
};
var ZodOptional = class extends ZodType {
  static {
    __name(this, "ZodOptional");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.undefined) {
      return OK(void 0);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodOptional.create = (type, params) => {
  return new ZodOptional({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodOptional,
    ...processCreateParams(params)
  });
};
var ZodNullable = class extends ZodType {
  static {
    __name(this, "ZodNullable");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.null) {
      return OK(null);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodNullable.create = (type, params) => {
  return new ZodNullable({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodNullable,
    ...processCreateParams(params)
  });
};
var ZodDefault = class extends ZodType {
  static {
    __name(this, "ZodDefault");
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    let data2 = ctx.data;
    if (ctx.parsedType === ZodParsedType.undefined) {
      data2 = this._def.defaultValue();
    }
    return this._def.innerType._parse({
      data: data2,
      path: ctx.path,
      parent: ctx
    });
  }
  removeDefault() {
    return this._def.innerType;
  }
};
ZodDefault.create = (type, params) => {
  return new ZodDefault({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodDefault,
    defaultValue: typeof params.default === "function" ? params.default : () => params.default,
    ...processCreateParams(params)
  });
};
var ZodCatch = class extends ZodType {
  static {
    __name(this, "ZodCatch");
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const newCtx = {
      ...ctx,
      common: {
        ...ctx.common,
        issues: []
      }
    };
    const result = this._def.innerType._parse({
      data: newCtx.data,
      path: newCtx.path,
      parent: {
        ...newCtx
      }
    });
    if (isAsync(result)) {
      return result.then((result2) => {
        return {
          status: "valid",
          value: result2.status === "valid" ? result2.value : this._def.catchValue({
            get error() {
              return new ZodError(newCtx.common.issues);
            },
            input: newCtx.data
          })
        };
      });
    } else {
      return {
        status: "valid",
        value: result.status === "valid" ? result.value : this._def.catchValue({
          get error() {
            return new ZodError(newCtx.common.issues);
          },
          input: newCtx.data
        })
      };
    }
  }
  removeCatch() {
    return this._def.innerType;
  }
};
ZodCatch.create = (type, params) => {
  return new ZodCatch({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodCatch,
    catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
    ...processCreateParams(params)
  });
};
var ZodNaN = class extends ZodType {
  static {
    __name(this, "ZodNaN");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.nan) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.nan,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
};
ZodNaN.create = (params) => {
  return new ZodNaN({
    typeName: ZodFirstPartyTypeKind.ZodNaN,
    ...processCreateParams(params)
  });
};
var BRAND = /* @__PURE__ */ Symbol("zod_brand");
var ZodBranded = class extends ZodType {
  static {
    __name(this, "ZodBranded");
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const data2 = ctx.data;
    return this._def.type._parse({
      data: data2,
      path: ctx.path,
      parent: ctx
    });
  }
  unwrap() {
    return this._def.type;
  }
};
var ZodPipeline = class _ZodPipeline extends ZodType {
  static {
    __name(this, "ZodPipeline");
  }
  _parse(input) {
    const { status: status2, ctx } = this._processInputParams(input);
    if (ctx.common.async) {
      const handleAsync = /* @__PURE__ */ __name(async () => {
        const inResult = await this._def.in._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inResult.status === "aborted")
          return INVALID;
        if (inResult.status === "dirty") {
          status2.dirty();
          return DIRTY(inResult.value);
        } else {
          return this._def.out._parseAsync({
            data: inResult.value,
            path: ctx.path,
            parent: ctx
          });
        }
      }, "handleAsync");
      return handleAsync();
    } else {
      const inResult = this._def.in._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
      if (inResult.status === "aborted")
        return INVALID;
      if (inResult.status === "dirty") {
        status2.dirty();
        return {
          status: "dirty",
          value: inResult.value
        };
      } else {
        return this._def.out._parseSync({
          data: inResult.value,
          path: ctx.path,
          parent: ctx
        });
      }
    }
  }
  static create(a, b) {
    return new _ZodPipeline({
      in: a,
      out: b,
      typeName: ZodFirstPartyTypeKind.ZodPipeline
    });
  }
};
var ZodReadonly = class extends ZodType {
  static {
    __name(this, "ZodReadonly");
  }
  _parse(input) {
    const result = this._def.innerType._parse(input);
    if (isValid(result)) {
      result.value = Object.freeze(result.value);
    }
    return result;
  }
};
ZodReadonly.create = (type, params) => {
  return new ZodReadonly({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodReadonly,
    ...processCreateParams(params)
  });
};
var custom = /* @__PURE__ */ __name((check, params = {}, fatal) => {
  if (check)
    return ZodAny.create().superRefine((data2, ctx) => {
      var _a, _b;
      if (!check(data2)) {
        const p = typeof params === "function" ? params(data2) : typeof params === "string" ? { message: params } : params;
        const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
        const p2 = typeof p === "string" ? { message: p } : p;
        ctx.addIssue({ code: "custom", ...p2, fatal: _fatal });
      }
    });
  return ZodAny.create();
}, "custom");
var late = {
  object: ZodObject.lazycreate
};
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind22) {
  ZodFirstPartyTypeKind22["ZodString"] = "ZodString";
  ZodFirstPartyTypeKind22["ZodNumber"] = "ZodNumber";
  ZodFirstPartyTypeKind22["ZodNaN"] = "ZodNaN";
  ZodFirstPartyTypeKind22["ZodBigInt"] = "ZodBigInt";
  ZodFirstPartyTypeKind22["ZodBoolean"] = "ZodBoolean";
  ZodFirstPartyTypeKind22["ZodDate"] = "ZodDate";
  ZodFirstPartyTypeKind22["ZodSymbol"] = "ZodSymbol";
  ZodFirstPartyTypeKind22["ZodUndefined"] = "ZodUndefined";
  ZodFirstPartyTypeKind22["ZodNull"] = "ZodNull";
  ZodFirstPartyTypeKind22["ZodAny"] = "ZodAny";
  ZodFirstPartyTypeKind22["ZodUnknown"] = "ZodUnknown";
  ZodFirstPartyTypeKind22["ZodNever"] = "ZodNever";
  ZodFirstPartyTypeKind22["ZodVoid"] = "ZodVoid";
  ZodFirstPartyTypeKind22["ZodArray"] = "ZodArray";
  ZodFirstPartyTypeKind22["ZodObject"] = "ZodObject";
  ZodFirstPartyTypeKind22["ZodUnion"] = "ZodUnion";
  ZodFirstPartyTypeKind22["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  ZodFirstPartyTypeKind22["ZodIntersection"] = "ZodIntersection";
  ZodFirstPartyTypeKind22["ZodTuple"] = "ZodTuple";
  ZodFirstPartyTypeKind22["ZodRecord"] = "ZodRecord";
  ZodFirstPartyTypeKind22["ZodMap"] = "ZodMap";
  ZodFirstPartyTypeKind22["ZodSet"] = "ZodSet";
  ZodFirstPartyTypeKind22["ZodFunction"] = "ZodFunction";
  ZodFirstPartyTypeKind22["ZodLazy"] = "ZodLazy";
  ZodFirstPartyTypeKind22["ZodLiteral"] = "ZodLiteral";
  ZodFirstPartyTypeKind22["ZodEnum"] = "ZodEnum";
  ZodFirstPartyTypeKind22["ZodEffects"] = "ZodEffects";
  ZodFirstPartyTypeKind22["ZodNativeEnum"] = "ZodNativeEnum";
  ZodFirstPartyTypeKind22["ZodOptional"] = "ZodOptional";
  ZodFirstPartyTypeKind22["ZodNullable"] = "ZodNullable";
  ZodFirstPartyTypeKind22["ZodDefault"] = "ZodDefault";
  ZodFirstPartyTypeKind22["ZodCatch"] = "ZodCatch";
  ZodFirstPartyTypeKind22["ZodPromise"] = "ZodPromise";
  ZodFirstPartyTypeKind22["ZodBranded"] = "ZodBranded";
  ZodFirstPartyTypeKind22["ZodPipeline"] = "ZodPipeline";
  ZodFirstPartyTypeKind22["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
var instanceOfType = /* @__PURE__ */ __name((cls, params = {
  message: `Input not instance of ${cls.name}`
}) => custom((data2) => data2 instanceof cls, params), "instanceOfType");
var stringType = ZodString.create;
var numberType = ZodNumber.create;
var nanType = ZodNaN.create;
var bigIntType = ZodBigInt.create;
var booleanType = ZodBoolean.create;
var dateType = ZodDate.create;
var symbolType = ZodSymbol.create;
var undefinedType = ZodUndefined.create;
var nullType = ZodNull.create;
var anyType = ZodAny.create;
var unknownType = ZodUnknown.create;
var neverType = ZodNever.create;
var voidType = ZodVoid.create;
var arrayType = ZodArray.create;
var objectType = ZodObject.create;
var strictObjectType = ZodObject.strictCreate;
var unionType = ZodUnion.create;
var discriminatedUnionType = ZodDiscriminatedUnion.create;
var intersectionType = ZodIntersection.create;
var tupleType = ZodTuple.create;
var recordType = ZodRecord.create;
var mapType = ZodMap.create;
var setType = ZodSet.create;
var functionType = ZodFunction.create;
var lazyType = ZodLazy.create;
var literalType = ZodLiteral.create;
var enumType = ZodEnum.create;
var nativeEnumType = ZodNativeEnum.create;
var promiseType = ZodPromise.create;
var effectsType = ZodEffects.create;
var optionalType = ZodOptional.create;
var nullableType = ZodNullable.create;
var preprocessType = ZodEffects.createWithPreprocess;
var pipelineType = ZodPipeline.create;
var ostring = /* @__PURE__ */ __name(() => stringType().optional(), "ostring");
var onumber = /* @__PURE__ */ __name(() => numberType().optional(), "onumber");
var oboolean = /* @__PURE__ */ __name(() => booleanType().optional(), "oboolean");
var coerce = {
  string: /* @__PURE__ */ __name((arg) => ZodString.create({ ...arg, coerce: true }), "string"),
  number: /* @__PURE__ */ __name((arg) => ZodNumber.create({ ...arg, coerce: true }), "number"),
  boolean: /* @__PURE__ */ __name((arg) => ZodBoolean.create({
    ...arg,
    coerce: true
  }), "boolean"),
  bigint: /* @__PURE__ */ __name((arg) => ZodBigInt.create({ ...arg, coerce: true }), "bigint"),
  date: /* @__PURE__ */ __name((arg) => ZodDate.create({ ...arg, coerce: true }), "date")
};
var NEVER = INVALID;
var z = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  defaultErrorMap: errorMap,
  setErrorMap,
  getErrorMap,
  makeIssue,
  EMPTY_PATH,
  addIssueToContext,
  ParseStatus,
  INVALID,
  DIRTY,
  OK,
  isAborted,
  isDirty,
  isValid,
  isAsync,
  get util() {
    return util;
  },
  get objectUtil() {
    return objectUtil;
  },
  ZodParsedType,
  getParsedType,
  ZodType,
  ZodString,
  ZodNumber,
  ZodBigInt,
  ZodBoolean,
  ZodDate,
  ZodSymbol,
  ZodUndefined,
  ZodNull,
  ZodAny,
  ZodUnknown,
  ZodNever,
  ZodVoid,
  ZodArray,
  ZodObject,
  ZodUnion,
  ZodDiscriminatedUnion,
  ZodIntersection,
  ZodTuple,
  ZodRecord,
  ZodMap,
  ZodSet,
  ZodFunction,
  ZodLazy,
  ZodLiteral,
  ZodEnum,
  ZodNativeEnum,
  ZodPromise,
  ZodEffects,
  ZodTransformer: ZodEffects,
  ZodOptional,
  ZodNullable,
  ZodDefault,
  ZodCatch,
  ZodNaN,
  BRAND,
  ZodBranded,
  ZodPipeline,
  ZodReadonly,
  custom,
  Schema: ZodType,
  ZodSchema: ZodType,
  late,
  get ZodFirstPartyTypeKind() {
    return ZodFirstPartyTypeKind;
  },
  coerce,
  any: anyType,
  array: arrayType,
  bigint: bigIntType,
  boolean: booleanType,
  date: dateType,
  discriminatedUnion: discriminatedUnionType,
  effect: effectsType,
  "enum": enumType,
  "function": functionType,
  "instanceof": instanceOfType,
  intersection: intersectionType,
  lazy: lazyType,
  literal: literalType,
  map: mapType,
  nan: nanType,
  nativeEnum: nativeEnumType,
  never: neverType,
  "null": nullType,
  nullable: nullableType,
  number: numberType,
  object: objectType,
  oboolean,
  onumber,
  optional: optionalType,
  ostring,
  pipeline: pipelineType,
  preprocess: preprocessType,
  promise: promiseType,
  record: recordType,
  set: setType,
  strictObject: strictObjectType,
  string: stringType,
  symbol: symbolType,
  transformer: effectsType,
  tuple: tupleType,
  "undefined": undefinedType,
  union: unionType,
  unknown: unknownType,
  "void": voidType,
  NEVER,
  ZodIssueCode,
  quotelessJson,
  ZodError
});
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");
z.object({
  retries: z.object({
    delay: z.number().gte(0).or(z.string()),
    limit: z.number().gte(0),
    backoff: z.enum(["constant", "linear", "exponential"]).optional()
  }).strict().optional(),
  timeout: z.number().gte(0).or(z.string()).optional()
}).strict();
var mod_esm_exports = {};
__export2(mod_esm_exports, {
  default: () => mod_esm_default
});
var import_mod_cjs = __toESM2(require_mod_cjs3(), 1);
__reExport2(mod_esm_exports, __toESM2(require_mod_cjs3(), 1));
var mod_esm_default = import_mod_cjs.default;
function getGlobalWranglerConfigPath() {
  const configDir = mod_esm_default(".wrangler").config();
  const legacyConfigDir = import_node_path2.default.join(import_node_os2.default.homedir(), ".wrangler");
  if (isDirectory(legacyConfigDir)) {
    return legacyConfigDir;
  } else {
    return configDir;
  }
}
__name(getGlobalWranglerConfigPath, "getGlobalWranglerConfigPath");
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]
          )}`
        );
    }
  };
}
__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)}`
    );
  }
}
__name(assertOneOf, "assertOneOf");
var getC3CommandFromEnv = getEnvironmentVariableFactory({
  variableName: "WRANGLER_C3_COMMAND",
  defaultValue: /* @__PURE__ */ __name(() => "create cloudflare", "defaultValue")
});
var getWranglerSendMetricsFromEnv = getBooleanEnvironmentVariableFactory({
  variableName: "WRANGLER_SEND_METRICS"
});
var getWranglerSendErrorReportsFromEnv = getBooleanEnvironmentVariableFactory({
  variableName: "WRANGLER_SEND_ERROR_REPORTS"
});
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}\`
			`);
  }
  return complianceRegionFromEnv || complianceConfig?.compliance_region || "public";
}, "getCloudflareComplianceRegion");
var getCloudflareApiBaseUrlFromEnv = getEnvironmentVariableFactory({
  variableName: "CLOUDFLARE_API_BASE_URL",
  deprecatedName: "CF_API_BASE_URL"
});
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_path2.default.join(getGlobalWranglerConfigPath(), "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 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, config, 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(config, 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, config, fieldPath) {
  const result = unwindPropertyPath(config, 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 = (v2) => v2) {
  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");
function inheritableInWranglerEnvironments(diagnostics, useServiceEnvironments, topLevelEnv, rawEnv, field, validate2, transformFn = (v2) => v2, defaultValue) {
  const usingServiceEnvironments = useServiceEnvironments && topLevelEnv !== void 0;
  return usingServiceEnvironments ? notAllowedInNamedServiceEnvironment(
    diagnostics,
    topLevelEnv,
    rawEnv,
    field
  ) : inheritable(
    diagnostics,
    topLevelEnv,
    rawEnv,
    field,
    validate2,
    defaultValue,
    transformFn
  );
}
__name(inheritableInWranglerEnvironments, "inheritableInWranglerEnvironments");
var appendEnvName = /* @__PURE__ */ __name((envName) => (fieldValue) => fieldValue ? `${fieldValue}-${envName}` : void 0, "appendEnvName");
function notAllowedInNamedServiceEnvironment(diagnostics, topLevelEnv, rawEnv, field) {
  if (field in rawEnv) {
    diagnostics.errors.push(
      `The "${field}" field is not allowed in named service environments.
Please remove the field from this environment.`
    );
  }
  return topLevelEnv[field];
}
__name(notAllowedInNamedServiceEnvironment, "notAllowedInNamedServiceEnvironment");
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, path410) {
  let container = root;
  const parts = path410.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 isValid22 = 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).`
    );
    isValid22 = false;
  }
  const data2 = new Date(value.replaceAll(/–|—/g, "-"));
  if (isNaN(data2.getTime())) {
    diagnostics.errors.push(
      `"${field}" field should be a valid ISO-8601 date (YYYY-MM-DD), but got ${JSON.stringify(value)}.`
    );
    isValid22 = false;
  }
  return isValid22;
}, "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, config) => {
    let passedValidations = true;
    for (const validate2 of validations) {
      if (!validate2(diagnostics, field, value, config)) {
        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 isValid22 = true;
  if (!Array.isArray(value)) {
    diagnostics.errors.push(
      `Expected "${container}" to be an array of ${type}s but got ${JSON.stringify(
        value
      )}`
    );
    isValid22 = false;
  } else {
    for (let i = 0; i < value.length; i++) {
      isValid22 = validateRequiredProperty(
        diagnostics,
        container,
        `[${i}]`,
        value[i],
        type
      ) && isValid22;
    }
  }
  return isValid22;
}, "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(([_2, entry]) => {
      nameCount.set(entry.name, (nameCount.get(entry.name) ?? 0) + 1);
    });
    const duplicates = Array.from(nameCount.entries()).filter(([_2, 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",
  hyperdrive: "Hyperdrive Config",
  r2_buckets: "R2 Bucket",
  logfwdr: "logfwdr",
  services: "Worker",
  analytics_engine_datasets: "Analytics Engine Dataset",
  text_blobs: "Text Blob",
  browser: "Browser",
  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",
  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",
  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",
  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",
  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_path2.default.relative(process.cwd(), configPath) : "wrangler"} configuration:`
  );
  validateOptionalProperty(
    diagnostics,
    "",
    "legacy_env",
    rawConfig.legacy_env,
    "boolean"
  );
  validateOptionalProperty(
    diagnostics,
    "",
    "send_metrics",
    rawConfig.send_metrics,
    "boolean"
  );
  validateOptionalProperty(
    diagnostics,
    "",
    "keep_vars",
    rawConfig.keep_vars,
    "boolean"
  );
  validateOptionalProperty(
    diagnostics,
    "",
    "pages_build_output_dir",
    rawConfig.pages_build_output_dir,
    "string"
  );
  validateOptionalProperty(
    diagnostics,
    "",
    "$schema",
    rawConfig.$schema,
    "string"
  );
  const useServiceEnvironments = !(args["legacy-env"] ?? rawConfig.legacy_env ?? true);
  if (useServiceEnvironments) {
    diagnostics.warnings.push(
      "Service environments are deprecated, and will be removed in the future. DO NOT USE IN PRODUCTION."
    );
  }
  const isDispatchNamespace = typeof args["dispatch-namespace"] === "string" && args["dispatch-namespace"].trim() !== "";
  const topLevelEnv = normalizeAndValidateEnvironment(
    diagnostics,
    configPath,
    rawConfig,
    isDispatchNamespace,
    preserveOriginalMain
  );
  const isRedirectedConfig = isRedirectedRawConfig(
    rawConfig,
    configPath,
    userConfigPath
  );
  const definedEnvironments = Object.keys(rawConfig.env ?? {});
  if (isRedirectedConfig && 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_assert2.default)(envName === void 0 || typeof envName === "string");
  let activeEnv = topLevelEnv;
  if (envName) {
    if (isRedirectedConfig) {
      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,
          useServiceEnvironments,
          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,
          useServiceEnvironments,
          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 config = {
    configPath,
    userConfigPath,
    topLevelName: isRedirectedConfig ? rawConfig.topLevelName : rawConfig.name,
    definedEnvironments: isRedirectedConfig ? rawConfig.definedEnvironments : definedEnvironments,
    targetEnvironment: isRedirectedConfig ? rawConfig.targetEnvironment : envName,
    pages_build_output_dir: normalizeAndValidatePagesBuildOutputDir(
      configPath,
      rawConfig.pages_build_output_dir
    ),
    /** Legacy_env is wrangler environments, as opposed to service environments. Wrangler environments is not legacy.  */
    legacy_env: !useServiceEnvironments,
    send_metrics: rawConfig.send_metrics,
    keep_vars: rawConfig.keep_vars,
    ...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, config);
  validateAdditionalProperties(
    diagnostics,
    "top-level",
    Object.keys(rawConfig),
    [...Object.keys(config), "env", "$schema"]
  );
  applyPythonConfig(config, args);
  return { config, diagnostics };
}
__name(normalizeAndValidateConfig, "normalizeAndValidateConfig");
function applyPythonConfig(config, args) {
  const mainModule = args.script ?? config.main;
  if (typeof mainModule === "string" && mainModule.endsWith(".py")) {
    config.no_bundle = true;
    if (!config.rules.some((rule) => rule.type === "PythonModule")) {
      config.rules.push({ type: "PythonModule", globs: ["**/*.py"] });
    }
    if (!config.compatibility_flags.includes("python_workers")) {
      throw new UserError(
        "The `python_workers` compatibility flag is required to use Python."
      );
    }
  }
}
__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(
        (dir) => import_node_path2.default.relative(
          process.cwd(),
          import_node_path2.default.join(import_node_path2.default.dirname(configPath), `${dir}`)
        )
      ) : import_node_path2.default.relative(
        process.cwd(),
        import_node_path2.default.join(import_node_path2.default.dirname(configPath), `${watch_dir}`)
      ) : watch_dir
    ),
    cwd: cwd2
  };
}
__name(normalizeAndValidateBuild, "normalizeAndValidateBuild");
function normalizeAndValidateMainField(configPath, rawMain) {
  const configDir = import_node_path2.default.dirname(configPath ?? "wrangler.toml");
  if (rawMain !== void 0) {
    if (typeof rawMain === "string") {
      const directory = import_node_path2.default.resolve(configDir);
      return import_node_path2.default.resolve(directory, rawMain);
    } else {
      return rawMain;
    }
  } else {
    return;
  }
}
__name(normalizeAndValidateMainField, "normalizeAndValidateMainField");
function normalizeAndValidateBaseDirField(configPath, rawDir) {
  const configDir = import_node_path2.default.dirname(configPath ?? "wrangler.toml");
  if (rawDir !== void 0) {
    if (typeof rawDir === "string") {
      const directory = import_node_path2.default.resolve(configDir);
      return import_node_path2.default.resolve(directory, rawDir);
    } else {
      return rawDir;
    }
  } else {
    return;
  }
}
__name(normalizeAndValidateBaseDirField, "normalizeAndValidateBaseDirField");
function normalizeAndValidatePagesBuildOutputDir(configPath, rawPagesDir) {
  const configDir = import_node_path2.default.dirname(configPath ?? "wrangler.toml");
  if (rawPagesDir !== void 0) {
    if (typeof rawPagesDir === "string") {
      const directory = import_node_path2.default.resolve(configDir);
      return import_node_path2.default.resolve(directory, rawPagesDir);
    } else {
      return rawPagesDir;
    }
  } else {
    return;
  }
}
__name(normalizeAndValidatePagesBuildOutputDir, "normalizeAndValidatePagesBuildOutputDir");
function normalizeAndValidateDev(diagnostics, rawDev, args) {
  (0, import_node_assert2.default)(typeof args === "object" && args !== null && !Array.isArray(args));
  const {
    localProtocol: localProtocolArg,
    upstreamProtocol: upstreamProtocolArg,
    remote: remoteArg,
    enableContainers: enableContainersArg,
    generateTypes: generateTypesArg
  } = args;
  (0, import_node_assert2.default)(
    localProtocolArg === void 0 || localProtocolArg === "http" || localProtocolArg === "https"
  );
  (0, import_node_assert2.default)(
    upstreamProtocolArg === void 0 || upstreamProtocolArg === "http" || upstreamProtocolArg === "https"
  );
  (0, import_node_assert2.default)(remoteArg === void 0 || typeof remoteArg === "boolean");
  (0, import_node_assert2.default)(
    enableContainersArg === void 0 || typeof enableContainersArg === "boolean"
  );
  (0, import_node_assert2.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");
    validateOptionalProperty(
      diagnostics,
      "site",
      "entry-point",
      rawConfig.site["entry-point"],
      "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_path2.default.join(
        String(rawConfig.site["entry-point"]) || "workers-site",
        import_node_path2.default.extname(String(rawConfig.site["entry-point"]) || "workers-site") ? "" : "index.js"
      )}"
\`\`\``,
      false,
      void 0,
      "warning"
    );
    let siteEntryPoint = rawConfig.site["entry-point"];
    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_path2.default.relative(
        process.cwd(),
        import_node_path2.default.join(import_node_path2.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 isValid22 = 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}`
      );
      isValid22 = false;
    }
  }
  if (isValid22) {
    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_path2.default.relative(
          process.cwd(),
          import_node_path2.default.join(import_node_path2.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 otherKeys = Object.keys(item).length - 1;
    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";
    if (otherKeys === 2 && hasCustomDomainFlag && (hasZoneId || hasZoneName)) {
      return true;
    } else if (otherKeys === 1 && (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 }, 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 }, 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) {
  return inheritable(
    diagnostics,
    topLevelEnv,
    rawEnv,
    "routes",
    all(isRouteArray, isMutuallyExclusiveWith(rawEnv, "route")),
    void 0
  );
}
__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 isValid22 = true;
  isValid22 = isValid22 && validateRequiredProperty(
    diagnostics,
    field,
    "service",
    value.service,
    "string"
  );
  isValid22 = isValid22 && validateOptionalProperty(
    diagnostics,
    field,
    "environment",
    value.environment,
    "string"
  );
  return isValid22;
}
__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 isValid22 = true;
  for (let i = 0; i < value.length; i++) {
    isValid22 = validateTailConsumer(diagnostics, `${field}[${i}]`, value[i]) && isValid22;
  }
  return isValid22;
}, "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 isValid22 = true;
  for (let i = 0; i < value.length; i++) {
    isValid22 = validateStreamingTailConsumer(diagnostics, `${field}[${i}]`, value[i]) && isValid22;
  }
  return isValid22;
}, "validateStreamingTailConsumers");
function normalizeAndValidateEnvironment(diagnostics, configPath, rawEnv, isDispatchNamespace, preserveOriginalMain, envName = "top level", topLevelEnv, useServiceEnvironments, 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"
  );
  experimental(diagnostics, rawEnv, "unsafe");
  experimental(diagnostics, rawEnv, "secrets");
  const route = normalizeAndValidateRoute(diagnostics, topLevelEnv, rawEnv);
  const account_id = inheritableInWranglerEnvironments(
    diagnostics,
    useServiceEnvironments,
    topLevelEnv,
    mutateEmptyStringAccountIDValue(diagnostics, rawEnv),
    "account_id",
    isString,
    void 0,
    void 0
  );
  const routes = validateRoutes(diagnostics, topLevelEnv, rawEnv);
  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: inheritableInWranglerEnvironments(
      diagnostics,
      useServiceEnvironments,
      topLevelEnv,
      rawEnv,
      "name",
      isDispatchNamespace ? isString : isValidName,
      appendEnvName(envName),
      void 0
    ),
    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,
      []
    ),
    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",
      validateContainerApp(envName, rawEnv.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),
      []
    ),
    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),
      []
    ),
    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
    ),
    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
    )
  };
  warnIfDurableObjectsHaveNoMigrations(
    diagnostics,
    environment.durable_objects,
    environment.migrations,
    configPath
  );
  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_path2.default.relative(
    process.cwd(),
    import_node_path2.default.join(import_node_path2.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 validateTriggers = /* @__PURE__ */ __name((diagnostics, triggersFieldName, triggersValue) => {
  if (triggersValue === void 0 || triggersValue === null) {
    return true;
  }
  if (typeof triggersValue !== "object") {
    diagnostics.errors.push(
      `Expected "${triggersFieldName}" to be of type object but got ${JSON.stringify(
        triggersValue
      )}.`
    );
    return false;
  }
  let isValid22 = 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)}.`
    );
    isValid22 = false;
  }
  isValid22 = validateAdditionalProperties(
    diagnostics,
    triggersFieldName,
    Object.keys(triggersValue),
    ["crons"]
  ) && isValid22;
  return isValid22;
}, "validateTriggers");
var validateRules = /* @__PURE__ */ __name((envName) => (diagnostics, field, envValue, config) => {
  if (!envValue) {
    return true;
  }
  const fieldPath = config === 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 isValid22 = true;
  for (let i = 0; i < envValue.length; i++) {
    isValid22 = validateRule(diagnostics, `${fieldPath}[${i}]`, envValue[i], config) && isValid22;
  }
  return isValid22;
}, "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 isValid22 = 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".`
    );
    isValid22 = false;
  }
  isValid22 = validateTypedArray(diagnostics, `${field}.globs`, rule.globs, "string") && isValid22;
  if (!isOptionalProperty(rule, "fallthrough", "boolean")) {
    diagnostics.errors.push(
      `the field "fallthrough", when present, should be a boolean.`
    );
    isValid22 = false;
  }
  return isValid22;
}, "validateRule");
var validateDefines = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config) => {
  let isValid22 = true;
  const fieldPath = config === 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]
          )}.`
        );
        isValid22 = false;
      }
    }
  } else {
    if (value !== void 0) {
      diagnostics.errors.push(
        `The field "${fieldPath}" should be an object but got ${JSON.stringify(
          value
        )}.
`
      );
      isValid22 = false;
    }
  }
  const configDefines = Object.keys(config?.define ?? {});
  if (configDefines.length > 0) {
    if (typeof value === "object" && value !== null) {
      const configEnvDefines = config === void 0 ? [] : Object.keys(value);
      for (const varName of configDefines) {
        if (!(varName in value)) {
          diagnostics.warnings.push(
            `"define.${varName}" exists at the top level, but not on "${fieldPath}".
This is not what you probably want, since "define" configuration is not inherited by environments.
Please add "define.${varName}" to "env.${envName}".`
          );
        }
      }
      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 isValid22;
}, "validateDefines");
var validateVars = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config) => {
  let isValid22 = true;
  const fieldPath = config === 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
        )}.
`
      );
      isValid22 = 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".`
          );
          isValid22 = false;
        }
      }
    }
  }
  const configVars = Object.keys(config?.vars ?? {});
  if (configVars.length > 0) {
    if (typeof value === "object" && value !== null) {
      for (const varName of configVars) {
        if (!(varName in value)) {
          diagnostics.warnings.push(
            `"vars.${varName}" exists at the top level, but not on "${fieldPath}".
This is not what you probably want, since "vars" configuration is not inherited by environments.
Please add "vars.${varName}" to "env.${envName}".`
          );
        }
      }
    }
  }
  return isValid22;
}, "validateVars");
var validateSecrets = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config) => {
  const fieldPath = config === 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 isValid22 = true;
  validateAdditionalProperties(diagnostics, fieldPath, Object.keys(value), [
    "required"
  ]);
  isValid22 = validateOptionalTypedArray(
    diagnostics,
    `${fieldPath}.required`,
    value.required,
    "string"
  ) && isValid22;
  return isValid22;
}, "validateSecrets");
var validateBindingsProperty = /* @__PURE__ */ __name((envName, validateBinding) => (diagnostics, field, value, config) => {
  let isValid22 = true;
  const fieldPath = config === 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
        )}.`
      );
      isValid22 = false;
    } else if (!hasProperty(value, "bindings")) {
      diagnostics.errors.push(
        `The field "${fieldPath}" is missing the required "bindings" property.`
      );
      isValid22 = false;
    } else if (!Array.isArray(value.bindings)) {
      diagnostics.errors.push(
        `The field "${fieldPath}.bindings" should be an array but got ${JSON.stringify(
          value.bindings
        )}.`
      );
      isValid22 = 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)}`
        );
        isValid22 = validateBinding(
          bindingDiagnostics,
          `${fieldPath}.bindings[${i}]`,
          binding,
          config
        ) && isValid22;
        diagnostics.addChild(bindingDiagnostics);
      }
    }
    const configBindingNames = getBindingNames(
      config?.[field]
    );
    if (isValid22 && 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 isValid22;
}, "validateBindingsProperty");
var validateUnsafeSettings = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config) => {
  const fieldPath = config === 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, config);
    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 isValid22 = true;
  if (!isRequiredProperty(value, "name", "string")) {
    diagnostics.errors.push(`binding should have a string "name" field.`);
    isValid22 = false;
  }
  if (!isRequiredProperty(value, "class_name", "string")) {
    diagnostics.errors.push(`binding should have a string "class_name" field.`);
    isValid22 = false;
  }
  if (!isOptionalProperty(value, "script_name", "string")) {
    diagnostics.errors.push(
      `the field "script_name", when present, should be a string.`
    );
    isValid22 = false;
  }
  if (!isOptionalProperty(value, "environment", "string")) {
    diagnostics.errors.push(
      `the field "environment", when present, should be a string.`
    );
    isValid22 = false;
  }
  if ("environment" in value && !("script_name" in value)) {
    diagnostics.errors.push(
      `binding should have a "script_name" field if "environment" is present.`
    );
    isValid22 = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "class_name",
    "environment",
    "name",
    "script_name"
  ]);
  return isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isRequiredProperty(value, "name", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "name" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  } else if (!isValidWorkflowName(value.name)) {
    diagnostics.errors.push(
      `"${field}" binding "name" field is invalid. ${workflowNameFormatMessage}`
    );
    isValid22 = false;
  }
  if (!isRequiredProperty(value, "class_name", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "class_name" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = 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
      )}.`
    );
    isValid22 = false;
  }
  if (!isOptionalProperty(value, "remote", "boolean")) {
    diagnostics.errors.push(
      `"${field}" bindings should, optionally, have a boolean "remote" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = 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
        )}.`
      );
      isValid22 = 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
            )}.`
          );
          isValid22 = 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"
  ]);
  return isValid22;
}, "validateWorkflowBinding");
var validateCflogfwdrObject = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, topLevelEnv) => {
  const bindingsValidation = validateBindingsProperty(
    envName,
    validateCflogfwdrBinding
  );
  if (!bindingsValidation(diagnostics, field, value, topLevelEnv)) {
    return false;
  }
  const v2 = value;
  if (v2?.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 isValid22 = true;
  if (!isRequiredProperty(value, "name", "string")) {
    diagnostics.errors.push(`binding should have a string "name" field.`);
    isValid22 = false;
  }
  if (!isRequiredProperty(value, "destination", "string")) {
    diagnostics.errors.push(
      `binding should have a string "destination" field.`
    );
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "destination",
    "name"
  ]);
  return isValid22;
}, "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 isValid22 = true;
  isValid22 = validateOptionalProperty(
    diagnostics,
    field,
    "directory",
    value.directory,
    "string"
  ) && isValid22;
  isValid22 = validateOptionalProperty(
    diagnostics,
    field,
    "binding",
    value.binding,
    "string"
  ) && isValid22;
  isValid22 = validateOptionalProperty(
    diagnostics,
    field,
    "html_handling",
    value.html_handling,
    "string",
    [
      "auto-trailing-slash",
      "force-trailing-slash",
      "drop-trailing-slash",
      "none"
    ]
  ) && isValid22;
  isValid22 = validateOptionalProperty(
    diagnostics,
    field,
    "not_found_handling",
    value.not_found_handling,
    "string",
    ["single-page-application", "404-page", "none"]
  ) && isValid22;
  if (value.run_worker_first !== void 0) {
    if (typeof value.run_worker_first === "boolean") {
      isValid22 = validateOptionalProperty(
        diagnostics,
        field,
        "run_worker_first",
        value.run_worker_first,
        "boolean"
      ) && isValid22;
    } else if (Array.isArray(value.run_worker_first)) {
      isValid22 = validateOptionalTypedArray(
        diagnostics,
        "assets.run_worker_first",
        value.run_worker_first,
        "string"
      ) && isValid22;
    } 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
        )}.`
      );
      isValid22 = false;
    }
  }
  isValid22 = validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "directory",
    "binding",
    "html_handling",
    "not_found_handling",
    "run_worker_first"
  ]) && isValid22;
  return isValid22;
}, "validateAssetsConfig");
var validateNamedSimpleBinding = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config) => {
  const fieldPath = config === 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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(`binding should have a string "binding" field.`);
    isValid22 = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "remote"
  ]);
  return isValid22;
}, "validateNamedSimpleBinding");
var validateAIBinding = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config) => {
  const fieldPath = config === 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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(`binding should have a string "binding" field.`);
    isValid22 = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid22 = false;
  }
  return isValid22;
}, "validateAIBinding");
var validateVersionMetadataBinding = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config) => {
  const fieldPath = config === 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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(`binding should have a string "binding" field.`);
    isValid22 = false;
  }
  return isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "name", "string")) {
    diagnostics.errors.push(`binding should have a string "name" field.`);
    isValid22 = 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",
      "kv_namespace",
      "durable_object_namespace",
      "d1_database",
      "r2_bucket",
      "service",
      "logfwdr",
      "mtls_certificate",
      "pipeline",
      "worker_loader",
      "vpc_service",
      "flagship",
      "vpc_network",
      "stream",
      "media"
    ];
    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.`);
    isValid22 = false;
  }
  return isValid22;
}, "validateUnsafeBinding");
var validateBindingArray = /* @__PURE__ */ __name((envName, validateBinding) => (diagnostics, field, envValue, config) => {
  if (envValue === void 0) {
    return true;
  }
  const fieldPath = config === 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 isValid22 = true;
  for (let i = 0; i < envValue.length; i++) {
    isValid22 = validateBinding(
      diagnostics,
      `${fieldPath}[${i}]`,
      envValue[i],
      config
    ) && isValid22;
  }
  const configValue = config?.[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 isValid22;
}, "validateBindingArray");
function validateContainerApp(envName, topLevelName, configPath) {
  return (diagnostics, field, value, config) => {
    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) {
      if (!isOptionalProperty(value, "name", "string")) {
        diagnostics.errors.push(
          `Field "name", when present, should be a string, but got ${JSON.stringify(value)}`
        );
      }
      validateRequiredProperty(
        diagnostics,
        field,
        "class_name",
        containerAppOptional.class_name,
        "string"
      );
      validateOptionalProperty(
        diagnostics,
        field,
        "name",
        containerAppOptional.name,
        "string"
      );
      if (!containerAppOptional.name) {
        if (!topLevelName || !isOptionalProperty(containerAppOptional, "class_name", "string")) {
          diagnostics.errors.push(
            `Must have either a top level "name" and "containers.class_name" field defined, or have field "containers.name" defined.`
          );
        }
        let name = `${topLevelName}-${containerAppOptional.class_name}`;
        name += config === 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" || Array.isArray(containerAppOptional.configuration)) {
          diagnostics.errors.push(
            `"containers.configuration" should be an object`
          );
        }
        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 baseDir = configPath ? import_node_path2.default.dirname(configPath) : process.cwd();
          resolvedImage = import_node_path2.default.resolve(baseDir, resolvedImage);
          resolvedBuildContextPath = containerAppOptional.image_build_context ? import_node_path2.default.resolve(baseDir, containerAppOptional.image_build_context) : import_node_path2.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 ("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",
          "wrangler_ssh",
          "authorized_keys",
          "trusted_user_ca_keys",
          "configuration",
          "constraints",
          "affinities",
          "rollout_step_percentage",
          "rollout_kind",
          "durable_objects",
          "rollout_active_grace_period",
          "unsafe"
        ]
      );
      if ("configuration" in containerAppOptional) {
        validateAdditionalProperties(
          diagnostics,
          `${field}.configuration`,
          Object.keys(containerAppOptional.configuration),
          ["image", "secrets", "labels", "disk", "vcpu", "memory_mib"]
        );
      }
      if ("wrangler_ssh" in containerAppOptional) {
        if (!isRequiredProperty(
          containerAppOptional.wrangler_ssh,
          "enabled",
          "boolean"
        )) {
          diagnostics.errors.push(
            `${field}.wrangler_ssh.enabled must be a boolean`
          );
        }
        if (!isOptionalProperty(
          containerAppOptional.wrangler_ssh,
          "port",
          "number"
        ) || containerAppOptional.wrangler_ssh.port < 1 || containerAppOptional.wrangler_ssh.port > 65535) {
          diagnostics.errors.push(
            `${field}.wrangler_ssh.port must be a number between 1 and 65535 inclusive`
          );
        }
      }
      if ("authorized_keys" in containerAppOptional) {
        if (!Array.isArray(containerAppOptional.authorized_keys)) {
          diagnostics.errors.push(`${field}.authorized_keys must be an array`);
        } else {
          for (const index in containerAppOptional.authorized_keys) {
            const fieldPath = `${field}.authorized_keys[${index}]`;
            const key = containerAppOptional.authorized_keys[index];
            if (!isRequiredProperty(key, "name", "string")) {
              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`
              );
            }
            if (!key.public_key.toLowerCase().startsWith("ssh-ed25519")) {
              diagnostics.errors.push(
                `${fieldPath}.public_key is a unsupported key type. Please provide a ED25519 public key.`
              );
            }
          }
        }
      }
      if ("trusted_user_ca_keys" in containerAppOptional) {
        if (!Array.isArray(containerAppOptional.trusted_user_ca_keys)) {
          diagnostics.errors.push(
            `${field}.trusted_user_ca_keys must be an array`
          );
        } else {
          for (const index in containerAppOptional.trusted_user_ca_keys) {
            const fieldPath = `${field}.trusted_user_ca_keys[${index}]`;
            const key = containerAppOptional.trusted_user_ca_keys[index];
            if (!isOptionalProperty(key, "name", "string")) {
              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`
              );
            }
            if (!key.public_key.toLowerCase().startsWith("ssh-ed25519")) {
              diagnostics.errors.push(
                `${fieldPath}.public_key is a unsupported key type. Please provide a ED25519 public key.`
              );
            }
          }
        }
      }
      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"
        );
      }
      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 isValid22 = 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
          )}.`
        );
        isValid22 = 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 isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = 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
      )}.`
    );
    isValid22 = 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
      )}.`
    );
    isValid22 = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "id",
    "preview_id",
    "remote"
  ]);
  return isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "name", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "name" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = 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
      )}.`
    );
    isValid22 = 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
      )}.`
    );
    isValid22 = 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
      )}.`
    );
    isValid22 = 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.`
    );
    isValid22 = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "allowed_sender_addresses",
    "allowed_destination_addresses",
    "destination_address",
    "name",
    "binding",
    "remote"
  ]);
  return isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isRequiredProperty(value, "queue", "string") || value.queue.length === 0) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "queue" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = 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)}.`
      );
      isValid22 = false;
    }
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid22 = false;
  }
  return isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = 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
      )}.`
    );
    isValid22 = false;
  }
  if (isValid22 && hasProperty(value, "bucket_name") && !isValidR2BucketName(value.bucket_name)) {
    diagnostics.errors.push(
      `${field}.bucket_name=${JSON.stringify(value.bucket_name)} is invalid. ${bucketFormatMessage}`
    );
    isValid22 = 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
      )}.`
    );
    isValid22 = false;
  }
  if (isValid22 && 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}`
    );
    isValid22 = false;
  }
  if (!isOptionalProperty(value, "jurisdiction", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should, optionally, have a string "jurisdiction" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "bucket_name",
    "preview_bucket_name",
    "jurisdiction",
    "remote"
  ]);
  return isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isOptionalProperty(value, "database_id", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a "database_id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = 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
      )}.`
    );
    isValid22 = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "database_id",
    "database_internal_env",
    "database_name",
    "migrations_dir",
    "migrations_table",
    "preview_database_id",
    "remote"
  ]);
  return isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isRequiredProperty(value, "index_name", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have an "index_name" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "index_name",
    "remote"
  ]);
  return isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(value)}.`
    );
    isValid22 = false;
  }
  if (!isRequiredProperty(value, "namespace", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a "namespace" field but got ${JSON.stringify(value)}.`
    );
    isValid22 = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "namespace",
    "remote"
  ]);
  return isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(value)}.`
    );
    isValid22 = false;
  }
  if (!isRequiredProperty(value, "instance_name", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have an "instance_name" field but got ${JSON.stringify(value)}.`
    );
    isValid22 = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "instance_name",
    "remote"
  ]);
  return isValid22;
}, "validateAISearchBinding");
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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isRequiredProperty(value, "id", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a "id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "id",
    "localConnectionString"
  ]);
  return isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isRequiredProperty(value, "service_id", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a "service_id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "service_id",
    "remote"
  ]);
  return isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = 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.`
    );
    isValid22 = 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
      )}.`
    );
    isValid22 = 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
      )}.`
    );
    isValid22 = 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
      )}.`
    );
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "tunnel_id",
    "network_id",
    "remote"
  ]);
  return isValid22;
}, "validateVpcNetworkBinding");
var validateBindingsHaveUniqueNames = /* @__PURE__ */ __name((diagnostics, config) => {
  let hasDuplicates = false;
  const bindingNamesArray = Object.entries(friendlyBindingNames);
  const bindingsGroupedByType = Object.fromEntries(
    bindingNamesArray.map(([bindingType, binding]) => [
      binding,
      getBindingNames(
        bindingType === "queues" ? config[bindingType]?.producers : config[bindingType]
      )
    ])
  );
  bindingsGroupedByType["Secret"] = config.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(config)) {
        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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isRequiredProperty(value, "service", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "service" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isOptionalProperty(value, "environment", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "environment" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isOptionalProperty(value, "entrypoint", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "entrypoint" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid22 = false;
  }
  return isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = 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
      )}.`
    );
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "dataset"
  ]);
  return isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isRequiredProperty(value, "namespace", "string")) {
    diagnostics.errors.push(
      `"${field}" should have a string "namespace" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (hasProperty(value, "outbound")) {
    if (!validateWorkerNamespaceOutbound(
      diagnostics,
      `${field}.outbound`,
      value.outbound ?? {}
    )) {
      diagnostics.errors.push(`"${field}" has an invalid outbound definition.`);
      isValid22 = false;
    }
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid22 = false;
  }
  return isValid22;
}, "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 isValid22 = true;
  isValid22 = isValid22 && validateRequiredProperty(
    diagnostics,
    field,
    "service",
    value.service,
    "string"
  );
  isValid22 = isValid22 && validateOptionalProperty(
    diagnostics,
    field,
    "environment",
    value.environment,
    "string"
  );
  isValid22 = isValid22 && validateOptionalTypedArray(
    diagnostics,
    `${field}.parameters`,
    value.parameters,
    "string"
  );
  return isValid22;
}
__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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = 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
      )}.`
    );
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "certificate_id",
    "remote"
  ]);
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid22 = false;
  }
  return isValid22;
}, "validateMTlsCertificateBinding");
function validateQueues(envName) {
  return (diagnostics, field, value, config) => {
    if (value === void 0) {
      return true;
    }
    const fieldPath = config === 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 isValid22 = true;
    if (!validateAdditionalProperties(
      diagnostics,
      fieldPath,
      Object.keys(value),
      ["consumers", "producers"]
    )) {
      isValid22 = 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
          )}.`
        );
        isValid22 = false;
      }
      for (let i = 0; i < consumers.length; i++) {
        const consumer = consumers[i];
        const consumerPath = `${fieldPath}.consumers[${i}]`;
        if (!validateConsumer(diagnostics, consumerPath, consumer, config)) {
          isValid22 = false;
        }
      }
    }
    if (hasProperty(value, "producers")) {
      if (!validateBindingArray(envName, validateQueueBinding)(
        diagnostics,
        `${field}.producers`,
        value.producers,
        config
      )) {
        isValid22 = false;
      }
    }
    return isValid22;
  };
}
__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 isValid22 = 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"
  ])) {
    isValid22 = 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.`
    );
    isValid22 = 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)}.`
      );
      isValid22 = false;
    }
  }
  return isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isRequiredProperty(value, "pipeline", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "pipeline" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "pipeline",
    "remote"
  ]);
  return isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isRequiredProperty(value, "store_id", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "store_id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isRequiredProperty(value, "secret_name", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "secret_name" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "store_id",
    "secret_name"
  ]);
  return isValid22;
}, "validateSecretsStoreSecretBinding");
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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isOptionalProperty(value, "enable_timer", "boolean")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a boolean "enable_timer" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "enable_timer"
  ]);
  return isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isRequiredProperty(value, "app_id", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "app_id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "app_id",
    "remote"
  ]);
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid22 = false;
  }
  return isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding"
  ]);
  return isValid22;
}, "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 isValid22 = true;
  if (!isRequiredProperty(value, "name", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "name" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = false;
  }
  if (!isRequiredProperty(value, "namespace_id", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "namespace_id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid22 = 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
      )}.`
    );
    isValid22 = 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
        )}.`
      );
      isValid22 = 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
        )}.`
      );
      isValid22 = 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
        )}.`
      );
      isValid22 = false;
    }
    validateAdditionalProperties(
      diagnostics,
      `${field}.simple`,
      Object.keys(value.simple),
      ["limit", "period"]
    );
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "name",
    "namespace_id",
    "simple"
  ]);
  return isValid22;
}, "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 isValid22 = true;
  isValid22 = 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",
    "unsafe_hello_world",
    "worker_loaders",
    "ratelimits",
    "vpc_services",
    "version_metadata",
    "logpush",
    "observability",
    "limits"
  ]) && isValid22;
  isValid22 = validateVars(envName)(
    diagnostics,
    `${field}.vars`,
    previews.vars,
    void 0
  ) && isValid22;
  isValid22 = validateDefines(envName)(
    diagnostics,
    `${field}.define`,
    previews.define,
    void 0
  ) && isValid22;
  isValid22 = validateBindingsProperty(envName, validateDurableObjectBinding)(
    diagnostics,
    `${field}.durable_objects`,
    previews.durable_objects,
    void 0
  ) && isValid22;
  isValid22 = all(
    validateBindingArray(envName, validateWorkflowBinding),
    validateUniqueNameProperty
  )(diagnostics, `${field}.workflows`, previews.workflows, void 0) && isValid22;
  isValid22 = validateBindingArray(envName, validateKVBinding)(
    diagnostics,
    `${field}.kv_namespaces`,
    previews.kv_namespaces,
    void 0
  ) && isValid22;
  isValid22 = validateBindingArray(envName, validateSendEmailBinding)(
    diagnostics,
    `${field}.send_email`,
    previews.send_email,
    void 0
  ) && isValid22;
  isValid22 = validateQueues(envName)(
    diagnostics,
    `${field}.queues`,
    previews.queues,
    void 0
  ) && isValid22;
  isValid22 = validateBindingArray(envName, validateD1Binding)(
    diagnostics,
    `${field}.d1_databases`,
    previews.d1_databases,
    void 0
  ) && isValid22;
  isValid22 = validateBindingArray(envName, validateR2Binding)(
    diagnostics,
    `${field}.r2_buckets`,
    previews.r2_buckets,
    void 0
  ) && isValid22;
  isValid22 = validateBindingArray(envName, validateVectorizeBinding)(
    diagnostics,
    `${field}.vectorize`,
    previews.vectorize,
    void 0
  ) && isValid22;
  isValid22 = validateBindingArray(envName, validateHyperdriveBinding)(
    diagnostics,
    `${field}.hyperdrive`,
    previews.hyperdrive,
    void 0
  ) && isValid22;
  isValid22 = validateBindingArray(envName, validateServiceBinding)(
    diagnostics,
    `${field}.services`,
    previews.services,
    void 0
  ) && isValid22;
  isValid22 = validateBindingArray(envName, validateAnalyticsEngineBinding)(
    diagnostics,
    `${field}.analytics_engine_datasets`,
    previews.analytics_engine_datasets,
    void 0
  ) && isValid22;
  isValid22 = validateBindingArray(envName, validateWorkerNamespaceBinding)(
    diagnostics,
    `${field}.dispatch_namespaces`,
    previews.dispatch_namespaces,
    void 0
  ) && isValid22;
  isValid22 = validateBindingArray(envName, validateMTlsCertificateBinding)(
    diagnostics,
    `${field}.mtls_certificates`,
    previews.mtls_certificates,
    void 0
  ) && isValid22;
  isValid22 = validateTailConsumers(
    diagnostics,
    `${field}.tail_consumers`,
    previews.tail_consumers,
    void 0
  ) && isValid22;
  isValid22 = validateStreamingTailConsumers(
    diagnostics,
    `${field}.streaming_tail_consumers`,
    previews.streaming_tail_consumers,
    void 0
  ) && isValid22;
  if (previews.unsafe !== void 0) {
    isValid22 = validateUnsafeSettings(envName)(
      diagnostics,
      `${field}.unsafe`,
      previews.unsafe,
      void 0
    ) && isValid22;
  }
  if (previews.browser !== void 0) {
    isValid22 = validateNamedSimpleBinding(envName)(
      diagnostics,
      `${field}.browser`,
      previews.browser,
      void 0
    ) && isValid22;
  }
  if (previews.ai !== void 0) {
    isValid22 = validateAIBinding(envName)(
      diagnostics,
      `${field}.ai`,
      previews.ai,
      void 0
    ) && isValid22;
  }
  if (previews.images !== void 0) {
    isValid22 = validateNamedSimpleBinding(envName)(
      diagnostics,
      `${field}.images`,
      previews.images,
      void 0
    ) && isValid22;
  }
  if (previews.stream !== void 0) {
    isValid22 = validateNamedSimpleBinding(envName)(
      diagnostics,
      `${field}.stream`,
      previews.stream,
      void 0
    ) && isValid22;
  }
  if (previews.media !== void 0) {
    isValid22 = validateNamedSimpleBinding(envName)(
      diagnostics,
      `${field}.media`,
      previews.media,
      void 0
    ) && isValid22;
  }
  isValid22 = validateBindingArray(envName, validatePipelineBinding)(
    diagnostics,
    `${field}.pipelines`,
    previews.pipelines,
    void 0
  ) && isValid22;
  isValid22 = validateBindingArray(envName, validateSecretsStoreSecretBinding)(
    diagnostics,
    `${field}.secrets_store_secrets`,
    previews.secrets_store_secrets,
    void 0
  ) && isValid22;
  isValid22 = validateBindingArray(envName, validateHelloWorldBinding)(
    diagnostics,
    `${field}.unsafe_hello_world`,
    previews.unsafe_hello_world,
    void 0
  ) && isValid22;
  isValid22 = validateBindingArray(envName, validateWorkerLoaderBinding)(
    diagnostics,
    `${field}.worker_loaders`,
    previews.worker_loaders,
    void 0
  ) && isValid22;
  isValid22 = validateBindingArray(envName, validateRateLimitBinding)(
    diagnostics,
    `${field}.ratelimits`,
    previews.ratelimits,
    void 0
  ) && isValid22;
  isValid22 = validateBindingArray(envName, validateVpcServiceBinding)(
    diagnostics,
    `${field}.vpc_services`,
    previews.vpc_services,
    void 0
  ) && isValid22;
  if (previews.version_metadata !== void 0) {
    isValid22 = validateVersionMetadataBinding(envName)(
      diagnostics,
      `${field}.version_metadata`,
      previews.version_metadata,
      void 0
    ) && isValid22;
  }
  isValid22 = isBoolean(diagnostics, `${field}.logpush`, previews.logpush, void 0) && isValid22;
  isValid22 = validateObservability(
    diagnostics,
    `${field}.observability`,
    previews.observability,
    void 0
  ) && isValid22;
  if (previews.limits) {
    isValid22 = validateOptionalProperty(
      diagnostics,
      `${field}.limits`,
      "cpu_ms",
      previews.limits.cpu_ms,
      "number"
    ) && isValid22;
    isValid22 = validateOptionalProperty(
      diagnostics,
      `${field}.limits`,
      "subrequests",
      previews.limits.subrequests,
      "number"
    ) && isValid22;
  }
  return isValid22;
}, "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(
        (c) => typeof c !== "object" || !isRequiredProperty(c, "from", "string") || !isRequiredProperty(c, "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(
        (c) => typeof c !== "object" || !isRequiredProperty(c, "from", "string") || !isRequiredProperty(c, "from_script", "string") || !isRequiredProperty(c, "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 validateObservability = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (value === void 0) {
    return true;
  }
  if (typeof value !== "object") {
    diagnostics.errors.push(
      `"${field}" should be an object but got ${JSON.stringify(value)}.`
    );
    return false;
  }
  const val = value;
  let isValid22 = true;
  isValid22 = 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"
    }
  ]) && isValid22;
  isValid22 = validateOptionalProperty(
    diagnostics,
    field,
    "head_sampling_rate",
    val.head_sampling_rate,
    "number"
  ) && isValid22;
  isValid22 = validateOptionalProperty(diagnostics, field, "logs", val.logs, "object") && isValid22;
  isValid22 = validateOptionalProperty(
    diagnostics,
    field,
    "traces",
    val.traces,
    "object"
  ) && isValid22;
  isValid22 = validateAdditionalProperties(diagnostics, field, Object.keys(val), [
    "enabled",
    "head_sampling_rate",
    "logs",
    "traces"
  ]) && isValid22;
  if (typeof val.logs === "object") {
    isValid22 = validateOptionalProperty(
      diagnostics,
      field,
      "logs.enabled",
      val.logs.enabled,
      "boolean"
    ) && isValid22;
    isValid22 = validateOptionalProperty(
      diagnostics,
      field,
      "logs.head_sampling_rate",
      val.logs.head_sampling_rate,
      "number"
    ) && isValid22;
    isValid22 = validateOptionalProperty(
      diagnostics,
      field,
      "logs.invocation_logs",
      val.logs.invocation_logs,
      "boolean"
    ) && isValid22;
    isValid22 = validateOptionalTypedArray(
      diagnostics,
      "logs.destinations",
      val.logs?.destinations,
      "string"
    ) && isValid22;
    isValid22 = validateOptionalProperty(
      diagnostics,
      field,
      "logs.persist",
      val.logs.persist,
      "boolean"
    ) && isValid22;
    isValid22 = validateAdditionalProperties(diagnostics, field, Object.keys(val.logs), [
      "enabled",
      "head_sampling_rate",
      "invocation_logs",
      "destinations",
      "persist"
    ]) && isValid22;
  }
  if (typeof val.traces === "object") {
    isValid22 = validateOptionalProperty(
      diagnostics,
      field,
      "traces.enabled",
      val.traces.enabled,
      "boolean"
    ) && isValid22;
    isValid22 = validateOptionalProperty(
      diagnostics,
      field,
      "traces.head_sampling_rate",
      val.traces.head_sampling_rate,
      "number"
    ) && isValid22;
    isValid22 = validateOptionalTypedArray(
      diagnostics,
      "traces.destinations",
      val.traces?.destinations,
      "string"
    ) && isValid22;
    isValid22 = validateOptionalProperty(
      diagnostics,
      field,
      "traces.persist",
      val.traces.persist,
      "boolean"
    ) && isValid22;
    isValid22 = validateAdditionalProperties(
      diagnostics,
      field,
      Object.keys(val.traces),
      ["enabled", "head_sampling_rate", "destinations", "persist"]
    ) && isValid22;
  }
  const samplingRate = val?.head_sampling_rate;
  if (samplingRate && (samplingRate < 0 || samplingRate > 1)) {
    diagnostics.errors.push(
      `"${field}.head_sampling_rate" must be a value between 0 and 1.`
    );
  }
  return isValid22;
}, "validateObservability");
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 isValid22 = true;
  isValid22 = validateRequiredProperty(
    diagnostics,
    field,
    "enabled",
    val.enabled,
    "boolean"
  ) && isValid22;
  isValid22 = validateAdditionalProperties(diagnostics, field, Object.keys(val), [
    "enabled"
  ]) && isValid22;
  return isValid22;
}, "validateCache");
function warnIfDurableObjectsHaveNoMigrations(diagnostics, durableObjects, migrations, configPath) {
  if (Array.isArray(durableObjects.bindings) && durableObjects.bindings.length > 0) {
    const exportedDurableObjects = (durableObjects.bindings || []).filter(
      (binding) => !binding.script_name
    );
    if (exportedDurableObjects.length > 0 && migrations.length === 0) {
      if (!exportedDurableObjects.some(
        (exportedDurableObject) => typeof exportedDurableObject.class_name !== "string"
      )) {
        const durableObjectClassnames = exportedDurableObjects.map(
          (durable) => durable.class_name
        );
        diagnostics.warnings.push(dedent`
				In your ${configFileName(configPath)} file, you have configured \`durable_objects\` exported by this Worker (${durableObjectClassnames.join(", ")}), but no \`migrations\` for them. This may not work as expected until you add a \`migrations\` section to your ${configFileName(configPath)} file. Add the following configuration:

				\`\`\`
				${formatConfigSnippet(
          {
            migrations: [
              { tag: "v1", new_sqlite_classes: durableObjectClassnames }
            ]
          },
          configPath
        )}
				\`\`\`

				Refer to https://developers.cloudflare.com/durable-objects/reference/durable-objects-migrations/ for more details.`);
      }
    }
  }
}
__name(warnIfDurableObjectsHaveNoMigrations, "warnIfDurableObjectsHaveNoMigrations");
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 baseDir = configPath ? import_node_path2.default.dirname(configPath) : process.cwd();
  const maybeDockerfile = import_node_path2.default.resolve(baseDir, imagePath);
  if (import_node_fs2.default.existsSync(maybeDockerfile)) {
    if (isDirectory(maybeDockerfile)) {
      throw new UserError(
        `${imagePath} is a directory, you should specify a path to the Dockerfile`
      );
    }
    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);
    }
    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)`
    );
  }
  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)`
    );
  }
  return false;
}
__name(isDockerfile, "isDockerfile");
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(config, envNames, projectName) {
  if (!config.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.`);
  }
  const diagnostics = new Diagnostics(
    `Running configuration file validation for Pages:`
  );
  validateMainField(config, diagnostics);
  validateProjectName(projectName, diagnostics);
  validatePagesEnvironmentNames(envNames, diagnostics);
  validateUnsupportedFields(config, diagnostics);
  validateDurableObjectBinding2(config, diagnostics);
  return diagnostics;
}
__name(validatePagesConfig, "validatePagesConfig");
function validateMainField(config, diagnostics) {
  if (config.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(config, diagnostics) {
  const unsupportedFields = new Set(Object.keys(config));
  for (const field of supportedPagesConfigFields) {
    if (field === "queues" && config.queues?.consumers?.length) {
      continue;
    }
    unsupportedFields.delete(field);
  }
  for (const field of unsupportedFields) {
    if (config[field] === void 0 || JSON.stringify(config[field]) === JSON.stringify(defaultWranglerConfig[field])) {
      unsupportedFields.delete(field);
    }
  }
  if (unsupportedFields.size > 0) {
    const fields = Array.from(unsupportedFields.keys());
    fields.forEach((field) => {
      if (field === "queues" && config.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(config, diagnostics) {
  if (config.durable_objects.bindings.length > 0) {
    const invalidBindings = config.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");

// ../cli/check-macos-version.ts
var import_ci_info = __toESM(require_ci_info());
var MINIMUM_MACOS_VERSION = "13.5.0";
function checkMacOSVersion(options) {
  if (process.platform !== "darwin") {
    return;
  }
  if (import_ci_info.default.isCI) {
    return;
  }
  const release = import_node_os3.default.release();
  const macOSVersion = darwinVersionToMacOSVersion(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).`
      );
    } 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) {
    const macOSMajor = major - 9;
    const minor = parseInt(match[2], 10);
    const patch = parseInt(match[3], 10);
    return `${macOSMajor}.${minor}.${patch}`;
  }
  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/index.ts
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) => {
  const currentLevel = getLogLevel();
  if (LOGGER_LEVELS[currentLevel] >= LOGGER_LEVELS.log) {
    stdout.write(`${msg}
`);
  }
};
var log = (msg) => {
  const lines = msg.split("\n").map((ln) => `${gray(shapes.bar)}${ln.length > 0 ? " " + white(ln) : ""}`);
  logRaw(lines.join("\n"));
};
var newline = () => {
  log("");
};

// src/index.ts
var import_exit_hook = __toESM(require_exit_hook());

// ../../node_modules/.pnpm/kleur@4.1.5/node_modules/kleur/colors.mjs
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(x2, y) {
  let rgx = new RegExp(`\\x1b\\[${y}m`, "g");
  let open2 = `\x1B[${x2}m`, close = `\x1B[${y}m`;
  return function(txt) {
    if (!$.enabled || txt == null) return txt;
    return open2 + (!!~("" + txt).indexOf(close) ? txt.replace(rgx, close + open2) : txt) + close;
  };
}
var reset = init(0, 0);
var bold2 = init(1, 22);
var dim2 = init(2, 22);
var italic = init(3, 23);
var underline = init(4, 24);
var inverse = init(7, 27);
var hidden2 = init(8, 28);
var strikethrough = init(9, 29);
var black2 = init(30, 39);
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 white2 = init(37, 39);
var gray2 = init(90, 39);
var grey = init(90, 39);
var bgBlack = init(40, 49);
var bgRed2 = init(41, 49);
var bgGreen2 = init(42, 49);
var bgYellow2 = init(43, 49);
var bgBlue2 = init(44, 49);
var bgMagenta = init(45, 49);
var bgCyan2 = init(46, 49);
var bgWhite = init(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/shared/index.worker.ts
var import_fs = __toESM(require("fs"));
var import_path = __toESM(require("path"));
var import_url = __toESM(require("url"));
var contents;
function index_worker_default() {
  if (contents !== void 0) return contents;
  const filePath = import_path.default.join(__dirname, "workers", "shared/index.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/zod.worker.ts
var import_fs2 = __toESM(require("fs"));
var import_path2 = __toESM(require("path"));
var import_url2 = __toESM(require("url"));
var contents2;
function zod_worker_default() {
  if (contents2 !== void 0) return contents2;
  const filePath = import_path2.default.join(__dirname, "workers", "shared/zod.worker.js");
  contents2 = import_fs2.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url2.default.pathToFileURL(filePath);
  return contents2;
}

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

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
var external_exports = {};
__export(external_exports, {
  BRAND: () => BRAND2,
  DIRTY: () => DIRTY2,
  EMPTY_PATH: () => EMPTY_PATH2,
  INVALID: () => INVALID2,
  NEVER: () => NEVER2,
  OK: () => OK2,
  ParseStatus: () => ParseStatus2,
  Schema: () => ZodType2,
  ZodAny: () => ZodAny2,
  ZodArray: () => ZodArray2,
  ZodBigInt: () => ZodBigInt2,
  ZodBoolean: () => ZodBoolean2,
  ZodBranded: () => ZodBranded2,
  ZodCatch: () => ZodCatch2,
  ZodDate: () => ZodDate2,
  ZodDefault: () => ZodDefault2,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2,
  ZodEffects: () => ZodEffects2,
  ZodEnum: () => ZodEnum2,
  ZodError: () => ZodError2,
  ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind2,
  ZodFunction: () => ZodFunction2,
  ZodIntersection: () => ZodIntersection2,
  ZodIssueCode: () => ZodIssueCode2,
  ZodLazy: () => ZodLazy2,
  ZodLiteral: () => ZodLiteral2,
  ZodMap: () => ZodMap2,
  ZodNaN: () => ZodNaN2,
  ZodNativeEnum: () => ZodNativeEnum2,
  ZodNever: () => ZodNever2,
  ZodNull: () => ZodNull2,
  ZodNullable: () => ZodNullable2,
  ZodNumber: () => ZodNumber2,
  ZodObject: () => ZodObject2,
  ZodOptional: () => ZodOptional2,
  ZodParsedType: () => ZodParsedType2,
  ZodPipeline: () => ZodPipeline2,
  ZodPromise: () => ZodPromise2,
  ZodReadonly: () => ZodReadonly2,
  ZodRecord: () => ZodRecord2,
  ZodSchema: () => ZodType2,
  ZodSet: () => ZodSet2,
  ZodString: () => ZodString2,
  ZodSymbol: () => ZodSymbol2,
  ZodTransformer: () => ZodEffects2,
  ZodTuple: () => ZodTuple2,
  ZodType: () => ZodType2,
  ZodUndefined: () => ZodUndefined2,
  ZodUnion: () => ZodUnion2,
  ZodUnknown: () => ZodUnknown2,
  ZodVoid: () => ZodVoid2,
  addIssueToContext: () => addIssueToContext2,
  any: () => anyType2,
  array: () => arrayType2,
  bigint: () => bigIntType2,
  boolean: () => booleanType2,
  coerce: () => coerce2,
  custom: () => custom2,
  date: () => dateType2,
  datetimeRegex: () => datetimeRegex2,
  defaultErrorMap: () => en_default,
  discriminatedUnion: () => discriminatedUnionType2,
  effect: () => effectsType2,
  enum: () => enumType2,
  function: () => functionType2,
  getErrorMap: () => getErrorMap2,
  getParsedType: () => getParsedType2,
  instanceof: () => instanceOfType2,
  intersection: () => intersectionType2,
  isAborted: () => isAborted2,
  isAsync: () => isAsync2,
  isDirty: () => isDirty2,
  isValid: () => isValid2,
  late: () => late2,
  lazy: () => lazyType2,
  literal: () => literalType2,
  makeIssue: () => makeIssue2,
  map: () => mapType2,
  nan: () => nanType2,
  nativeEnum: () => nativeEnumType2,
  never: () => neverType2,
  null: () => nullType2,
  nullable: () => nullableType2,
  number: () => numberType2,
  object: () => objectType2,
  objectUtil: () => objectUtil2,
  oboolean: () => oboolean2,
  onumber: () => onumber2,
  optional: () => optionalType2,
  ostring: () => ostring2,
  pipeline: () => pipelineType2,
  preprocess: () => preprocessType2,
  promise: () => promiseType2,
  quotelessJson: () => quotelessJson2,
  record: () => recordType2,
  set: () => setType2,
  setErrorMap: () => setErrorMap2,
  strictObject: () => strictObjectType2,
  string: () => stringType2,
  symbol: () => symbolType2,
  transformer: () => effectsType2,
  tuple: () => tupleType2,
  undefined: () => undefinedType2,
  union: () => unionType2,
  unknown: () => unknownType2,
  util: () => util2,
  void: () => voidType2
});

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
var util2;
(function(util6) {
  util6.assertEqual = (_2) => {
  };
  function assertIs(_arg) {
  }
  util6.assertIs = assertIs;
  function assertNever3(_x) {
    throw new Error();
  }
  util6.assertNever = assertNever3;
  util6.arrayToEnum = (items) => {
    const obj = {};
    for (const item of items) {
      obj[item] = item;
    }
    return obj;
  };
  util6.getValidEnumValues = (obj) => {
    const validKeys = util6.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
    const filtered = {};
    for (const k of validKeys) {
      filtered[k] = obj[k];
    }
    return util6.objectValues(filtered);
  };
  util6.objectValues = (obj) => {
    return util6.objectKeys(obj).map(function(e) {
      return obj[e];
    });
  };
  util6.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
    const keys = [];
    for (const key in object) {
      if (Object.prototype.hasOwnProperty.call(object, key)) {
        keys.push(key);
      }
    }
    return keys;
  };
  util6.find = (arr, checker) => {
    for (const item of arr) {
      if (checker(item))
        return item;
    }
    return void 0;
  };
  util6.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
  function joinValues(array, separator = " | ") {
    return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
  }
  util6.joinValues = joinValues;
  util6.jsonStringifyReplacer = (_2, value) => {
    if (typeof value === "bigint") {
      return value.toString();
    }
    return value;
  };
})(util2 || (util2 = {}));
var objectUtil2;
(function(objectUtil3) {
  objectUtil3.mergeShapes = (first, second) => {
    return {
      ...first,
      ...second
      // second overwrites first
    };
  };
})(objectUtil2 || (objectUtil2 = {}));
var ZodParsedType2 = util2.arrayToEnum([
  "string",
  "nan",
  "number",
  "integer",
  "float",
  "boolean",
  "date",
  "bigint",
  "symbol",
  "function",
  "undefined",
  "null",
  "array",
  "object",
  "unknown",
  "promise",
  "void",
  "never",
  "map",
  "set"
]);
var getParsedType2 = (data2) => {
  const t = typeof data2;
  switch (t) {
    case "undefined":
      return ZodParsedType2.undefined;
    case "string":
      return ZodParsedType2.string;
    case "number":
      return Number.isNaN(data2) ? ZodParsedType2.nan : ZodParsedType2.number;
    case "boolean":
      return ZodParsedType2.boolean;
    case "function":
      return ZodParsedType2.function;
    case "bigint":
      return ZodParsedType2.bigint;
    case "symbol":
      return ZodParsedType2.symbol;
    case "object":
      if (Array.isArray(data2)) {
        return ZodParsedType2.array;
      }
      if (data2 === null) {
        return ZodParsedType2.null;
      }
      if (data2.then && typeof data2.then === "function" && data2.catch && typeof data2.catch === "function") {
        return ZodParsedType2.promise;
      }
      if (typeof Map !== "undefined" && data2 instanceof Map) {
        return ZodParsedType2.map;
      }
      if (typeof Set !== "undefined" && data2 instanceof Set) {
        return ZodParsedType2.set;
      }
      if (typeof Date !== "undefined" && data2 instanceof Date) {
        return ZodParsedType2.date;
      }
      return ZodParsedType2.object;
    default:
      return ZodParsedType2.unknown;
  }
};

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js
var ZodIssueCode2 = util2.arrayToEnum([
  "invalid_type",
  "invalid_literal",
  "custom",
  "invalid_union",
  "invalid_union_discriminator",
  "invalid_enum_value",
  "unrecognized_keys",
  "invalid_arguments",
  "invalid_return_type",
  "invalid_date",
  "invalid_string",
  "too_small",
  "too_big",
  "invalid_intersection_types",
  "not_multiple_of",
  "not_finite"
]);
var quotelessJson2 = (obj) => {
  const json = JSON.stringify(obj, null, 2);
  return json.replace(/"([^"]+)":/g, "$1:");
};
var ZodError2 = class _ZodError extends Error {
  get errors() {
    return this.issues;
  }
  constructor(issues) {
    super();
    this.issues = [];
    this.addIssue = (sub) => {
      this.issues = [...this.issues, sub];
    };
    this.addIssues = (subs = []) => {
      this.issues = [...this.issues, ...subs];
    };
    const actualProto = new.target.prototype;
    if (Object.setPrototypeOf) {
      Object.setPrototypeOf(this, actualProto);
    } else {
      this.__proto__ = actualProto;
    }
    this.name = "ZodError";
    this.issues = issues;
  }
  format(_mapper) {
    const mapper = _mapper || function(issue) {
      return issue.message;
    };
    const fieldErrors = { _errors: [] };
    const processError = (error) => {
      for (const issue of error.issues) {
        if (issue.code === "invalid_union") {
          issue.unionErrors.map(processError);
        } else if (issue.code === "invalid_return_type") {
          processError(issue.returnTypeError);
        } else if (issue.code === "invalid_arguments") {
          processError(issue.argumentsError);
        } else if (issue.path.length === 0) {
          fieldErrors._errors.push(mapper(issue));
        } else {
          let curr = fieldErrors;
          let i = 0;
          while (i < issue.path.length) {
            const el = issue.path[i];
            const terminal = i === issue.path.length - 1;
            if (!terminal) {
              curr[el] = curr[el] || { _errors: [] };
            } else {
              curr[el] = curr[el] || { _errors: [] };
              curr[el]._errors.push(mapper(issue));
            }
            curr = curr[el];
            i++;
          }
        }
      }
    };
    processError(this);
    return fieldErrors;
  }
  static assert(value) {
    if (!(value instanceof _ZodError)) {
      throw new Error(`Not a ZodError: ${value}`);
    }
  }
  toString() {
    return this.message;
  }
  get message() {
    return JSON.stringify(this.issues, util2.jsonStringifyReplacer, 2);
  }
  get isEmpty() {
    return this.issues.length === 0;
  }
  flatten(mapper = (issue) => issue.message) {
    const fieldErrors = {};
    const formErrors = [];
    for (const sub of this.issues) {
      if (sub.path.length > 0) {
        const firstEl = sub.path[0];
        fieldErrors[firstEl] = fieldErrors[firstEl] || [];
        fieldErrors[firstEl].push(mapper(sub));
      } else {
        formErrors.push(mapper(sub));
      }
    }
    return { formErrors, fieldErrors };
  }
  get formErrors() {
    return this.flatten();
  }
};
ZodError2.create = (issues) => {
  const error = new ZodError2(issues);
  return error;
};

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js
var errorMap2 = (issue, _ctx) => {
  let message;
  switch (issue.code) {
    case ZodIssueCode2.invalid_type:
      if (issue.received === ZodParsedType2.undefined) {
        message = "Required";
      } else {
        message = `Expected ${issue.expected}, received ${issue.received}`;
      }
      break;
    case ZodIssueCode2.invalid_literal:
      message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util2.jsonStringifyReplacer)}`;
      break;
    case ZodIssueCode2.unrecognized_keys:
      message = `Unrecognized key(s) in object: ${util2.joinValues(issue.keys, ", ")}`;
      break;
    case ZodIssueCode2.invalid_union:
      message = `Invalid input`;
      break;
    case ZodIssueCode2.invalid_union_discriminator:
      message = `Invalid discriminator value. Expected ${util2.joinValues(issue.options)}`;
      break;
    case ZodIssueCode2.invalid_enum_value:
      message = `Invalid enum value. Expected ${util2.joinValues(issue.options)}, received '${issue.received}'`;
      break;
    case ZodIssueCode2.invalid_arguments:
      message = `Invalid function arguments`;
      break;
    case ZodIssueCode2.invalid_return_type:
      message = `Invalid function return type`;
      break;
    case ZodIssueCode2.invalid_date:
      message = `Invalid date`;
      break;
    case ZodIssueCode2.invalid_string:
      if (typeof issue.validation === "object") {
        if ("includes" in issue.validation) {
          message = `Invalid input: must include "${issue.validation.includes}"`;
          if (typeof issue.validation.position === "number") {
            message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
          }
        } else if ("startsWith" in issue.validation) {
          message = `Invalid input: must start with "${issue.validation.startsWith}"`;
        } else if ("endsWith" in issue.validation) {
          message = `Invalid input: must end with "${issue.validation.endsWith}"`;
        } else {
          util2.assertNever(issue.validation);
        }
      } else if (issue.validation !== "regex") {
        message = `Invalid ${issue.validation}`;
      } else {
        message = "Invalid";
      }
      break;
    case ZodIssueCode2.too_small:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
      else if (issue.type === "bigint")
        message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode2.too_big:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "bigint")
        message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode2.custom:
      message = `Invalid input`;
      break;
    case ZodIssueCode2.invalid_intersection_types:
      message = `Intersection results could not be merged`;
      break;
    case ZodIssueCode2.not_multiple_of:
      message = `Number must be a multiple of ${issue.multipleOf}`;
      break;
    case ZodIssueCode2.not_finite:
      message = "Number must be finite";
      break;
    default:
      message = _ctx.defaultError;
      util2.assertNever(issue);
  }
  return { message };
};
var en_default = errorMap2;

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js
var overrideErrorMap2 = en_default;
function setErrorMap2(map) {
  overrideErrorMap2 = map;
}
function getErrorMap2() {
  return overrideErrorMap2;
}

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
var makeIssue2 = (params) => {
  const { data: data2, path: path62, errorMaps, issueData } = params;
  const fullPath = [...path62, ...issueData.path || []];
  const fullIssue = {
    ...issueData,
    path: fullPath
  };
  if (issueData.message !== void 0) {
    return {
      ...issueData,
      path: fullPath,
      message: issueData.message
    };
  }
  let errorMessage = "";
  const maps = errorMaps.filter((m2) => !!m2).slice().reverse();
  for (const map of maps) {
    errorMessage = map(fullIssue, { data: data2, defaultError: errorMessage }).message;
  }
  return {
    ...issueData,
    path: fullPath,
    message: errorMessage
  };
};
var EMPTY_PATH2 = [];
function addIssueToContext2(ctx, issueData) {
  const overrideMap = getErrorMap2();
  const issue = makeIssue2({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      // contextual error map is first priority
      ctx.schemaErrorMap,
      // then schema-bound map if available
      overrideMap,
      // then global override map
      overrideMap === en_default ? void 0 : en_default
      // then global default map
    ].filter((x2) => !!x2)
  });
  ctx.common.issues.push(issue);
}
var ParseStatus2 = class _ParseStatus2 {
  constructor() {
    this.value = "valid";
  }
  dirty() {
    if (this.value === "valid")
      this.value = "dirty";
  }
  abort() {
    if (this.value !== "aborted")
      this.value = "aborted";
  }
  static mergeArray(status2, results) {
    const arrayValue = [];
    for (const s of results) {
      if (s.status === "aborted")
        return INVALID2;
      if (s.status === "dirty")
        status2.dirty();
      arrayValue.push(s.value);
    }
    return { status: status2.value, value: arrayValue };
  }
  static async mergeObjectAsync(status2, pairs) {
    const syncPairs = [];
    for (const pair of pairs) {
      const key = await pair.key;
      const value = await pair.value;
      syncPairs.push({
        key,
        value
      });
    }
    return _ParseStatus2.mergeObjectSync(status2, syncPairs);
  }
  static mergeObjectSync(status2, pairs) {
    const finalObject = {};
    for (const pair of pairs) {
      const { key, value } = pair;
      if (key.status === "aborted")
        return INVALID2;
      if (value.status === "aborted")
        return INVALID2;
      if (key.status === "dirty")
        status2.dirty();
      if (value.status === "dirty")
        status2.dirty();
      if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
        finalObject[key.value] = value.value;
      }
    }
    return { status: status2.value, value: finalObject };
  }
};
var INVALID2 = Object.freeze({
  status: "aborted"
});
var DIRTY2 = (value) => ({ status: "dirty", value });
var OK2 = (value) => ({ status: "valid", value });
var isAborted2 = (x2) => x2.status === "aborted";
var isDirty2 = (x2) => x2.status === "dirty";
var isValid2 = (x2) => x2.status === "valid";
var isAsync2 = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise;

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
var errorUtil2;
(function(errorUtil3) {
  errorUtil3.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  errorUtil3.toString = (message) => typeof message === "string" ? message : message?.message;
})(errorUtil2 || (errorUtil2 = {}));

// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
var ParseInputLazyPath2 = class {
  constructor(parent, value, path62, key) {
    this._cachedPath = [];
    this.parent = parent;
    this.data = value;
    this._path = path62;
    this._key = key;
  }
  get path() {
    if (!this._cachedPath.length) {
      if (Array.isArray(this._key)) {
        this._cachedPath.push(...this._path, ...this._key);
      } else {
        this._cachedPath.push(...this._path, this._key);
      }
    }
    return this._cachedPath;
  }
};
var handleResult2 = (ctx, result) => {
  if (isValid2(result)) {
    return { success: true, data: result.value };
  } else {
    if (!ctx.common.issues.length) {
      throw new Error("Validation failed but no issues detected.");
    }
    return {
      success: false,
      get error() {
        if (this._error)
          return this._error;
        const error = new ZodError2(ctx.common.issues);
        this._error = error;
        return this._error;
      }
    };
  }
};
function processCreateParams2(params) {
  if (!params)
    return {};
  const { errorMap: errorMap3, invalid_type_error, required_error, description } = params;
  if (errorMap3 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap3)
    return { errorMap: errorMap3, description };
  const customMap = (iss, ctx) => {
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message ?? ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: message ?? required_error ?? ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: message ?? invalid_type_error ?? ctx.defaultError };
  };
  return { errorMap: customMap, description };
}
var ZodType2 = class {
  get description() {
    return this._def.description;
  }
  _getType(input) {
    return getParsedType2(input.data);
  }
  _getOrReturnCtx(input, ctx) {
    return ctx || {
      common: input.parent.common,
      data: input.data,
      parsedType: getParsedType2(input.data),
      schemaErrorMap: this._def.errorMap,
      path: input.path,
      parent: input.parent
    };
  }
  _processInputParams(input) {
    return {
      status: new ParseStatus2(),
      ctx: {
        common: input.parent.common,
        data: input.data,
        parsedType: getParsedType2(input.data),
        schemaErrorMap: this._def.errorMap,
        path: input.path,
        parent: input.parent
      }
    };
  }
  _parseSync(input) {
    const result = this._parse(input);
    if (isAsync2(result)) {
      throw new Error("Synchronous parse encountered promise.");
    }
    return result;
  }
  _parseAsync(input) {
    const result = this._parse(input);
    return Promise.resolve(result);
  }
  parse(data2, params) {
    const result = this.safeParse(data2, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  safeParse(data2, params) {
    const ctx = {
      common: {
        issues: [],
        async: params?.async ?? false,
        contextualErrorMap: params?.errorMap
      },
      path: params?.path || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data: data2,
      parsedType: getParsedType2(data2)
    };
    const result = this._parseSync({ data: data2, path: ctx.path, parent: ctx });
    return handleResult2(ctx, result);
  }
  "~validate"(data2) {
    const ctx = {
      common: {
        issues: [],
        async: !!this["~standard"].async
      },
      path: [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data: data2,
      parsedType: getParsedType2(data2)
    };
    if (!this["~standard"].async) {
      try {
        const result = this._parseSync({ data: data2, path: [], parent: ctx });
        return isValid2(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        };
      } catch (err) {
        if (err?.message?.toLowerCase()?.includes("encountered")) {
          this["~standard"].async = true;
        }
        ctx.common = {
          issues: [],
          async: true
        };
      }
    }
    return this._parseAsync({ data: data2, path: [], parent: ctx }).then((result) => isValid2(result) ? {
      value: result.value
    } : {
      issues: ctx.common.issues
    });
  }
  async parseAsync(data2, params) {
    const result = await this.safeParseAsync(data2, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  async safeParseAsync(data2, params) {
    const ctx = {
      common: {
        issues: [],
        contextualErrorMap: params?.errorMap,
        async: true
      },
      path: params?.path || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data: data2,
      parsedType: getParsedType2(data2)
    };
    const maybeAsyncResult = this._parse({ data: data2, path: ctx.path, parent: ctx });
    const result = await (isAsync2(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
    return handleResult2(ctx, result);
  }
  refine(check, message) {
    const getIssueProperties = (val) => {
      if (typeof message === "string" || typeof message === "undefined") {
        return { message };
      } else if (typeof message === "function") {
        return message(val);
      } else {
        return message;
      }
    };
    return this._refinement((val, ctx) => {
      const result = check(val);
      const setError = () => ctx.addIssue({
        code: ZodIssueCode2.custom,
        ...getIssueProperties(val)
      });
      if (typeof Promise !== "undefined" && result instanceof Promise) {
        return result.then((data2) => {
          if (!data2) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      if (!result) {
        setError();
        return false;
      } else {
        return true;
      }
    });
  }
  refinement(check, refinementData) {
    return this._refinement((val, ctx) => {
      if (!check(val)) {
        ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
        return false;
      } else {
        return true;
      }
    });
  }
  _refinement(refinement) {
    return new ZodEffects2({
      schema: this,
      typeName: ZodFirstPartyTypeKind2.ZodEffects,
      effect: { type: "refinement", refinement }
    });
  }
  superRefine(refinement) {
    return this._refinement(refinement);
  }
  constructor(def) {
    this.spa = this.safeParseAsync;
    this._def = def;
    this.parse = this.parse.bind(this);
    this.safeParse = this.safeParse.bind(this);
    this.parseAsync = this.parseAsync.bind(this);
    this.safeParseAsync = this.safeParseAsync.bind(this);
    this.spa = this.spa.bind(this);
    this.refine = this.refine.bind(this);
    this.refinement = this.refinement.bind(this);
    this.superRefine = this.superRefine.bind(this);
    this.optional = this.optional.bind(this);
    this.nullable = this.nullable.bind(this);
    this.nullish = this.nullish.bind(this);
    this.array = this.array.bind(this);
    this.promise = this.promise.bind(this);
    this.or = this.or.bind(this);
    this.and = this.and.bind(this);
    this.transform = this.transform.bind(this);
    this.brand = this.brand.bind(this);
    this.default = this.default.bind(this);
    this.catch = this.catch.bind(this);
    this.describe = this.describe.bind(this);
    this.pipe = this.pipe.bind(this);
    this.readonly = this.readonly.bind(this);
    this.isNullable = this.isNullable.bind(this);
    this.isOptional = this.isOptional.bind(this);
    this["~standard"] = {
      version: 1,
      vendor: "zod",
      validate: (data2) => this["~validate"](data2)
    };
  }
  optional() {
    return ZodOptional2.create(this, this._def);
  }
  nullable() {
    return ZodNullable2.create(this, this._def);
  }
  nullish() {
    return this.nullable().optional();
  }
  array() {
    return ZodArray2.create(this);
  }
  promise() {
    return ZodPromise2.create(this, this._def);
  }
  or(option) {
    return ZodUnion2.create([this, option], this._def);
  }
  and(incoming) {
    return ZodIntersection2.create(this, incoming, this._def);
  }
  transform(transform) {
    return new ZodEffects2({
      ...processCreateParams2(this._def),
      schema: this,
      typeName: ZodFirstPartyTypeKind2.ZodEffects,
      effect: { type: "transform", transform }
    });
  }
  default(def) {
    const defaultValueFunc = typeof def === "function" ? def : () => def;
    return new ZodDefault2({
      ...processCreateParams2(this._def),
      innerType: this,
      defaultValue: defaultValueFunc,
      typeName: ZodFirstPartyTypeKind2.ZodDefault
    });
  }
  brand() {
    return new ZodBranded2({
      typeName: ZodFirstPartyTypeKind2.ZodBranded,
      type: this,
      ...processCreateParams2(this._def)
    });
  }
  catch(def) {
    const catchValueFunc = typeof def === "function" ? def : () => def;
    return new ZodCatch2({
      ...processCreateParams2(this._def),
      innerType: this,
      catchValue: catchValueFunc,
      typeName: ZodFirstPartyTypeKind2.ZodCatch
    });
  }
  describe(description) {
    const This = this.constructor;
    return new This({
      ...this._def,
      description
    });
  }
  pipe(target) {
    return ZodPipeline2.create(this, target);
  }
  readonly() {
    return ZodReadonly2.create(this);
  }
  isOptional() {
    return this.safeParse(void 0).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
};
var cuidRegex2 = /^c[^\s-]{8,}$/i;
var cuid2Regex2 = /^[0-9a-z]+$/;
var ulidRegex2 = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
var uuidRegex2 = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
var nanoidRegex = /^[a-z0-9_-]{21}$/i;
var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
var durationRegex = /^[-+]?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 emailRegex2 = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
var emojiRegex2;
var ipv4Regex2 = /^(?:(?: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 ipv4CidrRegex = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/;
var ipv6Regex2 = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
var dateRegexSource = `((\\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 dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
  let secondsRegexSource = `[0-5]\\d`;
  if (args.precision) {
    secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  }
  const secondsQuantifier = args.precision ? "+" : "?";
  return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
  return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex2(args) {
  let regex2 = `${dateRegexSource}T${timeRegexSource(args)}`;
  const opts = [];
  opts.push(args.local ? `Z?` : `Z`);
  if (args.offset)
    opts.push(`([+-]\\d{2}:?\\d{2})`);
  regex2 = `${regex2}(${opts.join("|")})`;
  return new RegExp(`^${regex2}$`);
}
function isValidIP2(ip, version3) {
  if ((version3 === "v4" || !version3) && ipv4Regex2.test(ip)) {
    return true;
  }
  if ((version3 === "v6" || !version3) && ipv6Regex2.test(ip)) {
    return true;
  }
  return false;
}
function isValidJWT(jwt, alg) {
  if (!jwtRegex.test(jwt))
    return false;
  try {
    const [header] = jwt.split(".");
    if (!header)
      return false;
    const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base64));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if ("typ" in decoded && decoded?.typ !== "JWT")
      return false;
    if (!decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch {
    return false;
  }
}
function isValidCidr(ip, version3) {
  if ((version3 === "v4" || !version3) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version3 === "v6" || !version3) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}
var ZodString2 = class _ZodString2 extends ZodType2 {
  _parse(input) {
    if (this._def.coerce) {
      input.data = String(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.string) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext2(ctx2, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.string,
        received: ctx2.parsedType
      });
      return INVALID2;
    }
    const status2 = new ParseStatus2();
    let ctx = void 0;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.length < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.too_small,
            minimum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.length > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.too_big,
            maximum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "length") {
        const tooBig = input.data.length > check.value;
        const tooSmall = input.data.length < check.value;
        if (tooBig || tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          if (tooBig) {
            addIssueToContext2(ctx, {
              code: ZodIssueCode2.too_big,
              maximum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          } else if (tooSmall) {
            addIssueToContext2(ctx, {
              code: ZodIssueCode2.too_small,
              minimum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          }
          status2.dirty();
        }
      } else if (check.kind === "email") {
        if (!emailRegex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "email",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "emoji") {
        if (!emojiRegex2) {
          emojiRegex2 = new RegExp(_emojiRegex, "u");
        }
        if (!emojiRegex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "emoji",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "uuid") {
        if (!uuidRegex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "uuid",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "nanoid") {
        if (!nanoidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "nanoid",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "cuid") {
        if (!cuidRegex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "cuid",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "cuid2") {
        if (!cuid2Regex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "cuid2",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "ulid") {
        if (!ulidRegex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "ulid",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "url") {
        try {
          new URL(input.data);
        } catch {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "url",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "regex") {
        check.regex.lastIndex = 0;
        const testResult = check.regex.test(input.data);
        if (!testResult) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "regex",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "trim") {
        input.data = input.data.trim();
      } else if (check.kind === "includes") {
        if (!input.data.includes(check.value, check.position)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.invalid_string,
            validation: { includes: check.value, position: check.position },
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "toLowerCase") {
        input.data = input.data.toLowerCase();
      } else if (check.kind === "toUpperCase") {
        input.data = input.data.toUpperCase();
      } else if (check.kind === "startsWith") {
        if (!input.data.startsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.invalid_string,
            validation: { startsWith: check.value },
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "endsWith") {
        if (!input.data.endsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.invalid_string,
            validation: { endsWith: check.value },
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "datetime") {
        const regex2 = datetimeRegex2(check);
        if (!regex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.invalid_string,
            validation: "datetime",
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "date") {
        const regex2 = dateRegex;
        if (!regex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.invalid_string,
            validation: "date",
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "time") {
        const regex2 = timeRegex(check);
        if (!regex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.invalid_string,
            validation: "time",
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "duration") {
        if (!durationRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "duration",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "ip") {
        if (!isValidIP2(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "ip",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "jwt") {
        if (!isValidJWT(input.data, check.alg)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "jwt",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "cidr") {
        if (!isValidCidr(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "cidr",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "base64") {
        if (!base64Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "base64",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "base64url") {
        if (!base64urlRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            validation: "base64url",
            code: ZodIssueCode2.invalid_string,
            message: check.message
          });
          status2.dirty();
        }
      } else {
        util2.assertNever(check);
      }
    }
    return { status: status2.value, value: input.data };
  }
  _regex(regex2, validation, message) {
    return this.refinement((data2) => regex2.test(data2), {
      validation,
      code: ZodIssueCode2.invalid_string,
      ...errorUtil2.errToObj(message)
    });
  }
  _addCheck(check) {
    return new _ZodString2({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  email(message) {
    return this._addCheck({ kind: "email", ...errorUtil2.errToObj(message) });
  }
  url(message) {
    return this._addCheck({ kind: "url", ...errorUtil2.errToObj(message) });
  }
  emoji(message) {
    return this._addCheck({ kind: "emoji", ...errorUtil2.errToObj(message) });
  }
  uuid(message) {
    return this._addCheck({ kind: "uuid", ...errorUtil2.errToObj(message) });
  }
  nanoid(message) {
    return this._addCheck({ kind: "nanoid", ...errorUtil2.errToObj(message) });
  }
  cuid(message) {
    return this._addCheck({ kind: "cuid", ...errorUtil2.errToObj(message) });
  }
  cuid2(message) {
    return this._addCheck({ kind: "cuid2", ...errorUtil2.errToObj(message) });
  }
  ulid(message) {
    return this._addCheck({ kind: "ulid", ...errorUtil2.errToObj(message) });
  }
  base64(message) {
    return this._addCheck({ kind: "base64", ...errorUtil2.errToObj(message) });
  }
  base64url(message) {
    return this._addCheck({
      kind: "base64url",
      ...errorUtil2.errToObj(message)
    });
  }
  jwt(options) {
    return this._addCheck({ kind: "jwt", ...errorUtil2.errToObj(options) });
  }
  ip(options) {
    return this._addCheck({ kind: "ip", ...errorUtil2.errToObj(options) });
  }
  cidr(options) {
    return this._addCheck({ kind: "cidr", ...errorUtil2.errToObj(options) });
  }
  datetime(options) {
    if (typeof options === "string") {
      return this._addCheck({
        kind: "datetime",
        precision: null,
        offset: false,
        local: false,
        message: options
      });
    }
    return this._addCheck({
      kind: "datetime",
      precision: typeof options?.precision === "undefined" ? null : options?.precision,
      offset: options?.offset ?? false,
      local: options?.local ?? false,
      ...errorUtil2.errToObj(options?.message)
    });
  }
  date(message) {
    return this._addCheck({ kind: "date", message });
  }
  time(options) {
    if (typeof options === "string") {
      return this._addCheck({
        kind: "time",
        precision: null,
        message: options
      });
    }
    return this._addCheck({
      kind: "time",
      precision: typeof options?.precision === "undefined" ? null : options?.precision,
      ...errorUtil2.errToObj(options?.message)
    });
  }
  duration(message) {
    return this._addCheck({ kind: "duration", ...errorUtil2.errToObj(message) });
  }
  regex(regex2, message) {
    return this._addCheck({
      kind: "regex",
      regex: regex2,
      ...errorUtil2.errToObj(message)
    });
  }
  includes(value, options) {
    return this._addCheck({
      kind: "includes",
      value,
      position: options?.position,
      ...errorUtil2.errToObj(options?.message)
    });
  }
  startsWith(value, message) {
    return this._addCheck({
      kind: "startsWith",
      value,
      ...errorUtil2.errToObj(message)
    });
  }
  endsWith(value, message) {
    return this._addCheck({
      kind: "endsWith",
      value,
      ...errorUtil2.errToObj(message)
    });
  }
  min(minLength, message) {
    return this._addCheck({
      kind: "min",
      value: minLength,
      ...errorUtil2.errToObj(message)
    });
  }
  max(maxLength, message) {
    return this._addCheck({
      kind: "max",
      value: maxLength,
      ...errorUtil2.errToObj(message)
    });
  }
  length(len, message) {
    return this._addCheck({
      kind: "length",
      value: len,
      ...errorUtil2.errToObj(message)
    });
  }
  /**
   * Equivalent to `.min(1)`
   */
  nonempty(message) {
    return this.min(1, errorUtil2.errToObj(message));
  }
  trim() {
    return new _ZodString2({
      ...this._def,
      checks: [...this._def.checks, { kind: "trim" }]
    });
  }
  toLowerCase() {
    return new _ZodString2({
      ...this._def,
      checks: [...this._def.checks, { kind: "toLowerCase" }]
    });
  }
  toUpperCase() {
    return new _ZodString2({
      ...this._def,
      checks: [...this._def.checks, { kind: "toUpperCase" }]
    });
  }
  get isDatetime() {
    return !!this._def.checks.find((ch) => ch.kind === "datetime");
  }
  get isDate() {
    return !!this._def.checks.find((ch) => ch.kind === "date");
  }
  get isTime() {
    return !!this._def.checks.find((ch) => ch.kind === "time");
  }
  get isDuration() {
    return !!this._def.checks.find((ch) => ch.kind === "duration");
  }
  get isEmail() {
    return !!this._def.checks.find((ch) => ch.kind === "email");
  }
  get isURL() {
    return !!this._def.checks.find((ch) => ch.kind === "url");
  }
  get isEmoji() {
    return !!this._def.checks.find((ch) => ch.kind === "emoji");
  }
  get isUUID() {
    return !!this._def.checks.find((ch) => ch.kind === "uuid");
  }
  get isNANOID() {
    return !!this._def.checks.find((ch) => ch.kind === "nanoid");
  }
  get isCUID() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid");
  }
  get isCUID2() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid2");
  }
  get isULID() {
    return !!this._def.checks.find((ch) => ch.kind === "ulid");
  }
  get isIP() {
    return !!this._def.checks.find((ch) => ch.kind === "ip");
  }
  get isCIDR() {
    return !!this._def.checks.find((ch) => ch.kind === "cidr");
  }
  get isBase64() {
    return !!this._def.checks.find((ch) => ch.kind === "base64");
  }
  get isBase64url() {
    return !!this._def.checks.find((ch) => ch.kind === "base64url");
  }
  get minLength() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxLength() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
};
ZodString2.create = (params) => {
  return new ZodString2({
    checks: [],
    typeName: ZodFirstPartyTypeKind2.ZodString,
    coerce: params?.coerce ?? false,
    ...processCreateParams2(params)
  });
};
function floatSafeRemainder2(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / 10 ** decCount;
}
var ZodNumber2 = class _ZodNumber2 extends ZodType2 {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
    this.step = this.multipleOf;
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = Number(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.number) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext2(ctx2, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.number,
        received: ctx2.parsedType
      });
      return INVALID2;
    }
    let ctx = void 0;
    const status2 = new ParseStatus2();
    for (const check of this._def.checks) {
      if (check.kind === "int") {
        if (!util2.isInteger(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.invalid_type,
            expected: "integer",
            received: "float",
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.too_small,
            minimum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.too_big,
            maximum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (floatSafeRemainder2(input.data, check.value) !== 0) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "finite") {
        if (!Number.isFinite(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.not_finite,
            message: check.message
          });
          status2.dirty();
        }
      } else {
        util2.assertNever(check);
      }
    }
    return { status: status2.value, value: input.data };
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil2.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil2.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil2.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil2.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new _ZodNumber2({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil2.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new _ZodNumber2({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  int(message) {
    return this._addCheck({
      kind: "int",
      message: errorUtil2.toString(message)
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: false,
      message: errorUtil2.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: false,
      message: errorUtil2.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: true,
      message: errorUtil2.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: true,
      message: errorUtil2.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil2.toString(message)
    });
  }
  finite(message) {
    return this._addCheck({
      kind: "finite",
      message: errorUtil2.toString(message)
    });
  }
  safe(message) {
    return this._addCheck({
      kind: "min",
      inclusive: true,
      value: Number.MIN_SAFE_INTEGER,
      message: errorUtil2.toString(message)
    })._addCheck({
      kind: "max",
      inclusive: true,
      value: Number.MAX_SAFE_INTEGER,
      message: errorUtil2.toString(message)
    });
  }
  get minValue() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxValue() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
  get isInt() {
    return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util2.isInteger(ch.value));
  }
  get isFinite() {
    let max = null;
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
        return true;
      } else if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      } else if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return Number.isFinite(min) && Number.isFinite(max);
  }
};
ZodNumber2.create = (params) => {
  return new ZodNumber2({
    checks: [],
    typeName: ZodFirstPartyTypeKind2.ZodNumber,
    coerce: params?.coerce || false,
    ...processCreateParams2(params)
  });
};
var ZodBigInt2 = class _ZodBigInt2 extends ZodType2 {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
  }
  _parse(input) {
    if (this._def.coerce) {
      try {
        input.data = BigInt(input.data);
      } catch {
        return this._getInvalidInput(input);
      }
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.bigint) {
      return this._getInvalidInput(input);
    }
    let ctx = void 0;
    const status2 = new ParseStatus2();
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.too_small,
            type: "bigint",
            minimum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.too_big,
            type: "bigint",
            maximum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status2.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (input.data % check.value !== BigInt(0)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status2.dirty();
        }
      } else {
        util2.assertNever(check);
      }
    }
    return { status: status2.value, value: input.data };
  }
  _getInvalidInput(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext2(ctx, {
      code: ZodIssueCode2.invalid_type,
      expected: ZodParsedType2.bigint,
      received: ctx.parsedType
    });
    return INVALID2;
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil2.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil2.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil2.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil2.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new _ZodBigInt2({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil2.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new _ZodBigInt2({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil2.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil2.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil2.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil2.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil2.toString(message)
    });
  }
  get minValue() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxValue() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
};
ZodBigInt2.create = (params) => {
  return new ZodBigInt2({
    checks: [],
    typeName: ZodFirstPartyTypeKind2.ZodBigInt,
    coerce: params?.coerce ?? false,
    ...processCreateParams2(params)
  });
};
var ZodBoolean2 = class extends ZodType2 {
  _parse(input) {
    if (this._def.coerce) {
      input.data = Boolean(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.boolean) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.boolean,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    return OK2(input.data);
  }
};
ZodBoolean2.create = (params) => {
  return new ZodBoolean2({
    typeName: ZodFirstPartyTypeKind2.ZodBoolean,
    coerce: params?.coerce || false,
    ...processCreateParams2(params)
  });
};
var ZodDate2 = class _ZodDate2 extends ZodType2 {
  _parse(input) {
    if (this._def.coerce) {
      input.data = new Date(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.date) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext2(ctx2, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.date,
        received: ctx2.parsedType
      });
      return INVALID2;
    }
    if (Number.isNaN(input.data.getTime())) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext2(ctx2, {
        code: ZodIssueCode2.invalid_date
      });
      return INVALID2;
    }
    const status2 = new ParseStatus2();
    let ctx = void 0;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.getTime() < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.too_small,
            message: check.message,
            inclusive: true,
            exact: false,
            minimum: check.value,
            type: "date"
          });
          status2.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.getTime() > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.too_big,
            message: check.message,
            inclusive: true,
            exact: false,
            maximum: check.value,
            type: "date"
          });
          status2.dirty();
        }
      } else {
        util2.assertNever(check);
      }
    }
    return {
      status: status2.value,
      value: new Date(input.data.getTime())
    };
  }
  _addCheck(check) {
    return new _ZodDate2({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  min(minDate, message) {
    return this._addCheck({
      kind: "min",
      value: minDate.getTime(),
      message: errorUtil2.toString(message)
    });
  }
  max(maxDate, message) {
    return this._addCheck({
      kind: "max",
      value: maxDate.getTime(),
      message: errorUtil2.toString(message)
    });
  }
  get minDate() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min != null ? new Date(min) : null;
  }
  get maxDate() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max != null ? new Date(max) : null;
  }
};
ZodDate2.create = (params) => {
  return new ZodDate2({
    checks: [],
    coerce: params?.coerce || false,
    typeName: ZodFirstPartyTypeKind2.ZodDate,
    ...processCreateParams2(params)
  });
};
var ZodSymbol2 = class extends ZodType2 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.symbol) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.symbol,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    return OK2(input.data);
  }
};
ZodSymbol2.create = (params) => {
  return new ZodSymbol2({
    typeName: ZodFirstPartyTypeKind2.ZodSymbol,
    ...processCreateParams2(params)
  });
};
var ZodUndefined2 = class extends ZodType2 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.undefined,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    return OK2(input.data);
  }
};
ZodUndefined2.create = (params) => {
  return new ZodUndefined2({
    typeName: ZodFirstPartyTypeKind2.ZodUndefined,
    ...processCreateParams2(params)
  });
};
var ZodNull2 = class extends ZodType2 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.null) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.null,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    return OK2(input.data);
  }
};
ZodNull2.create = (params) => {
  return new ZodNull2({
    typeName: ZodFirstPartyTypeKind2.ZodNull,
    ...processCreateParams2(params)
  });
};
var ZodAny2 = class extends ZodType2 {
  constructor() {
    super(...arguments);
    this._any = true;
  }
  _parse(input) {
    return OK2(input.data);
  }
};
ZodAny2.create = (params) => {
  return new ZodAny2({
    typeName: ZodFirstPartyTypeKind2.ZodAny,
    ...processCreateParams2(params)
  });
};
var ZodUnknown2 = class extends ZodType2 {
  constructor() {
    super(...arguments);
    this._unknown = true;
  }
  _parse(input) {
    return OK2(input.data);
  }
};
ZodUnknown2.create = (params) => {
  return new ZodUnknown2({
    typeName: ZodFirstPartyTypeKind2.ZodUnknown,
    ...processCreateParams2(params)
  });
};
var ZodNever2 = class extends ZodType2 {
  _parse(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext2(ctx, {
      code: ZodIssueCode2.invalid_type,
      expected: ZodParsedType2.never,
      received: ctx.parsedType
    });
    return INVALID2;
  }
};
ZodNever2.create = (params) => {
  return new ZodNever2({
    typeName: ZodFirstPartyTypeKind2.ZodNever,
    ...processCreateParams2(params)
  });
};
var ZodVoid2 = class extends ZodType2 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.void,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    return OK2(input.data);
  }
};
ZodVoid2.create = (params) => {
  return new ZodVoid2({
    typeName: ZodFirstPartyTypeKind2.ZodVoid,
    ...processCreateParams2(params)
  });
};
var ZodArray2 = class _ZodArray2 extends ZodType2 {
  _parse(input) {
    const { ctx, status: status2 } = this._processInputParams(input);
    const def = this._def;
    if (ctx.parsedType !== ZodParsedType2.array) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.array,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    if (def.exactLength !== null) {
      const tooBig = ctx.data.length > def.exactLength.value;
      const tooSmall = ctx.data.length < def.exactLength.value;
      if (tooBig || tooSmall) {
        addIssueToContext2(ctx, {
          code: tooBig ? ZodIssueCode2.too_big : ZodIssueCode2.too_small,
          minimum: tooSmall ? def.exactLength.value : void 0,
          maximum: tooBig ? def.exactLength.value : void 0,
          type: "array",
          inclusive: true,
          exact: true,
          message: def.exactLength.message
        });
        status2.dirty();
      }
    }
    if (def.minLength !== null) {
      if (ctx.data.length < def.minLength.value) {
        addIssueToContext2(ctx, {
          code: ZodIssueCode2.too_small,
          minimum: def.minLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.minLength.message
        });
        status2.dirty();
      }
    }
    if (def.maxLength !== null) {
      if (ctx.data.length > def.maxLength.value) {
        addIssueToContext2(ctx, {
          code: ZodIssueCode2.too_big,
          maximum: def.maxLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.maxLength.message
        });
        status2.dirty();
      }
    }
    if (ctx.common.async) {
      return Promise.all([...ctx.data].map((item, i) => {
        return def.type._parseAsync(new ParseInputLazyPath2(ctx, item, ctx.path, i));
      })).then((result2) => {
        return ParseStatus2.mergeArray(status2, result2);
      });
    }
    const result = [...ctx.data].map((item, i) => {
      return def.type._parseSync(new ParseInputLazyPath2(ctx, item, ctx.path, i));
    });
    return ParseStatus2.mergeArray(status2, result);
  }
  get element() {
    return this._def.type;
  }
  min(minLength, message) {
    return new _ZodArray2({
      ...this._def,
      minLength: { value: minLength, message: errorUtil2.toString(message) }
    });
  }
  max(maxLength, message) {
    return new _ZodArray2({
      ...this._def,
      maxLength: { value: maxLength, message: errorUtil2.toString(message) }
    });
  }
  length(len, message) {
    return new _ZodArray2({
      ...this._def,
      exactLength: { value: len, message: errorUtil2.toString(message) }
    });
  }
  nonempty(message) {
    return this.min(1, message);
  }
};
ZodArray2.create = (schema, params) => {
  return new ZodArray2({
    type: schema,
    minLength: null,
    maxLength: null,
    exactLength: null,
    typeName: ZodFirstPartyTypeKind2.ZodArray,
    ...processCreateParams2(params)
  });
};
function deepPartialify2(schema) {
  if (schema instanceof ZodObject2) {
    const newShape = {};
    for (const key in schema.shape) {
      const fieldSchema = schema.shape[key];
      newShape[key] = ZodOptional2.create(deepPartialify2(fieldSchema));
    }
    return new ZodObject2({
      ...schema._def,
      shape: () => newShape
    });
  } else if (schema instanceof ZodArray2) {
    return new ZodArray2({
      ...schema._def,
      type: deepPartialify2(schema.element)
    });
  } else if (schema instanceof ZodOptional2) {
    return ZodOptional2.create(deepPartialify2(schema.unwrap()));
  } else if (schema instanceof ZodNullable2) {
    return ZodNullable2.create(deepPartialify2(schema.unwrap()));
  } else if (schema instanceof ZodTuple2) {
    return ZodTuple2.create(schema.items.map((item) => deepPartialify2(item)));
  } else {
    return schema;
  }
}
var ZodObject2 = class _ZodObject2 extends ZodType2 {
  constructor() {
    super(...arguments);
    this._cached = null;
    this.nonstrict = this.passthrough;
    this.augment = this.extend;
  }
  _getCached() {
    if (this._cached !== null)
      return this._cached;
    const shape = this._def.shape();
    const keys = util2.objectKeys(shape);
    this._cached = { shape, keys };
    return this._cached;
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.object) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext2(ctx2, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.object,
        received: ctx2.parsedType
      });
      return INVALID2;
    }
    const { status: status2, ctx } = this._processInputParams(input);
    const { shape, keys: shapeKeys } = this._getCached();
    const extraKeys = [];
    if (!(this._def.catchall instanceof ZodNever2 && this._def.unknownKeys === "strip")) {
      for (const key in ctx.data) {
        if (!shapeKeys.includes(key)) {
          extraKeys.push(key);
        }
      }
    }
    const pairs = [];
    for (const key of shapeKeys) {
      const keyValidator = shape[key];
      const value = ctx.data[key];
      pairs.push({
        key: { status: "valid", value: key },
        value: keyValidator._parse(new ParseInputLazyPath2(ctx, value, ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (this._def.catchall instanceof ZodNever2) {
      const unknownKeys = this._def.unknownKeys;
      if (unknownKeys === "passthrough") {
        for (const key of extraKeys) {
          pairs.push({
            key: { status: "valid", value: key },
            value: { status: "valid", value: ctx.data[key] }
          });
        }
      } else if (unknownKeys === "strict") {
        if (extraKeys.length > 0) {
          addIssueToContext2(ctx, {
            code: ZodIssueCode2.unrecognized_keys,
            keys: extraKeys
          });
          status2.dirty();
        }
      } else if (unknownKeys === "strip") {
      } else {
        throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
      }
    } else {
      const catchall = this._def.catchall;
      for (const key of extraKeys) {
        const value = ctx.data[key];
        pairs.push({
          key: { status: "valid", value: key },
          value: catchall._parse(
            new ParseInputLazyPath2(ctx, value, ctx.path, key)
            //, ctx.child(key), value, getParsedType(value)
          ),
          alwaysSet: key in ctx.data
        });
      }
    }
    if (ctx.common.async) {
      return Promise.resolve().then(async () => {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value,
            alwaysSet: pair.alwaysSet
          });
        }
        return syncPairs;
      }).then((syncPairs) => {
        return ParseStatus2.mergeObjectSync(status2, syncPairs);
      });
    } else {
      return ParseStatus2.mergeObjectSync(status2, pairs);
    }
  }
  get shape() {
    return this._def.shape();
  }
  strict(message) {
    errorUtil2.errToObj;
    return new _ZodObject2({
      ...this._def,
      unknownKeys: "strict",
      ...message !== void 0 ? {
        errorMap: (issue, ctx) => {
          const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
          if (issue.code === "unrecognized_keys")
            return {
              message: errorUtil2.errToObj(message).message ?? defaultError
            };
          return {
            message: defaultError
          };
        }
      } : {}
    });
  }
  strip() {
    return new _ZodObject2({
      ...this._def,
      unknownKeys: "strip"
    });
  }
  passthrough() {
    return new _ZodObject2({
      ...this._def,
      unknownKeys: "passthrough"
    });
  }
  // const AugmentFactory =
  //   <Def extends ZodObjectDef>(def: Def) =>
  //   <Augmentation extends ZodRawShape>(
  //     augmentation: Augmentation
  //   ): ZodObject<
  //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
  //     Def["unknownKeys"],
  //     Def["catchall"]
  //   > => {
  //     return new ZodObject({
  //       ...def,
  //       shape: () => ({
  //         ...def.shape(),
  //         ...augmentation,
  //       }),
  //     }) as any;
  //   };
  extend(augmentation) {
    return new _ZodObject2({
      ...this._def,
      shape: () => ({
        ...this._def.shape(),
        ...augmentation
      })
    });
  }
  /**
   * Prior to zod@1.0.12 there was a bug in the
   * inferred type of merged objects. Please
   * upgrade if you are experiencing issues.
   */
  merge(merging) {
    const merged = new _ZodObject2({
      unknownKeys: merging._def.unknownKeys,
      catchall: merging._def.catchall,
      shape: () => ({
        ...this._def.shape(),
        ...merging._def.shape()
      }),
      typeName: ZodFirstPartyTypeKind2.ZodObject
    });
    return merged;
  }
  // merge<
  //   Incoming extends AnyZodObject,
  //   Augmentation extends Incoming["shape"],
  //   NewOutput extends {
  //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  //       ? Augmentation[k]["_output"]
  //       : k extends keyof Output
  //       ? Output[k]
  //       : never;
  //   },
  //   NewInput extends {
  //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  //       ? Augmentation[k]["_input"]
  //       : k extends keyof Input
  //       ? Input[k]
  //       : never;
  //   }
  // >(
  //   merging: Incoming
  // ): ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"],
  //   NewOutput,
  //   NewInput
  // > {
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  setKey(key, schema) {
    return this.augment({ [key]: schema });
  }
  // merge<Incoming extends AnyZodObject>(
  //   merging: Incoming
  // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
  // ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"]
  // > {
  //   // const mergedShape = objectUtil.mergeShapes(
  //   //   this._def.shape(),
  //   //   merging._def.shape()
  //   // );
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  catchall(index) {
    return new _ZodObject2({
      ...this._def,
      catchall: index
    });
  }
  pick(mask) {
    const shape = {};
    for (const key of util2.objectKeys(mask)) {
      if (mask[key] && this.shape[key]) {
        shape[key] = this.shape[key];
      }
    }
    return new _ZodObject2({
      ...this._def,
      shape: () => shape
    });
  }
  omit(mask) {
    const shape = {};
    for (const key of util2.objectKeys(this.shape)) {
      if (!mask[key]) {
        shape[key] = this.shape[key];
      }
    }
    return new _ZodObject2({
      ...this._def,
      shape: () => shape
    });
  }
  /**
   * @deprecated
   */
  deepPartial() {
    return deepPartialify2(this);
  }
  partial(mask) {
    const newShape = {};
    for (const key of util2.objectKeys(this.shape)) {
      const fieldSchema = this.shape[key];
      if (mask && !mask[key]) {
        newShape[key] = fieldSchema;
      } else {
        newShape[key] = fieldSchema.optional();
      }
    }
    return new _ZodObject2({
      ...this._def,
      shape: () => newShape
    });
  }
  required(mask) {
    const newShape = {};
    for (const key of util2.objectKeys(this.shape)) {
      if (mask && !mask[key]) {
        newShape[key] = this.shape[key];
      } else {
        const fieldSchema = this.shape[key];
        let newField = fieldSchema;
        while (newField instanceof ZodOptional2) {
          newField = newField._def.innerType;
        }
        newShape[key] = newField;
      }
    }
    return new _ZodObject2({
      ...this._def,
      shape: () => newShape
    });
  }
  keyof() {
    return createZodEnum2(util2.objectKeys(this.shape));
  }
};
ZodObject2.create = (shape, params) => {
  return new ZodObject2({
    shape: () => shape,
    unknownKeys: "strip",
    catchall: ZodNever2.create(),
    typeName: ZodFirstPartyTypeKind2.ZodObject,
    ...processCreateParams2(params)
  });
};
ZodObject2.strictCreate = (shape, params) => {
  return new ZodObject2({
    shape: () => shape,
    unknownKeys: "strict",
    catchall: ZodNever2.create(),
    typeName: ZodFirstPartyTypeKind2.ZodObject,
    ...processCreateParams2(params)
  });
};
ZodObject2.lazycreate = (shape, params) => {
  return new ZodObject2({
    shape,
    unknownKeys: "strip",
    catchall: ZodNever2.create(),
    typeName: ZodFirstPartyTypeKind2.ZodObject,
    ...processCreateParams2(params)
  });
};
var ZodUnion2 = class extends ZodType2 {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const options = this._def.options;
    function handleResults(results) {
      for (const result of results) {
        if (result.result.status === "valid") {
          return result.result;
        }
      }
      for (const result of results) {
        if (result.result.status === "dirty") {
          ctx.common.issues.push(...result.ctx.common.issues);
          return result.result;
        }
      }
      const unionErrors = results.map((result) => new ZodError2(result.ctx.common.issues));
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_union,
        unionErrors
      });
      return INVALID2;
    }
    if (ctx.common.async) {
      return Promise.all(options.map(async (option) => {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        return {
          result: await option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: childCtx
          }),
          ctx: childCtx
        };
      })).then(handleResults);
    } else {
      let dirty = void 0;
      const issues = [];
      for (const option of options) {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        const result = option._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: childCtx
        });
        if (result.status === "valid") {
          return result;
        } else if (result.status === "dirty" && !dirty) {
          dirty = { result, ctx: childCtx };
        }
        if (childCtx.common.issues.length) {
          issues.push(childCtx.common.issues);
        }
      }
      if (dirty) {
        ctx.common.issues.push(...dirty.ctx.common.issues);
        return dirty.result;
      }
      const unionErrors = issues.map((issues2) => new ZodError2(issues2));
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_union,
        unionErrors
      });
      return INVALID2;
    }
  }
  get options() {
    return this._def.options;
  }
};
ZodUnion2.create = (types4, params) => {
  return new ZodUnion2({
    options: types4,
    typeName: ZodFirstPartyTypeKind2.ZodUnion,
    ...processCreateParams2(params)
  });
};
var getDiscriminator2 = (type) => {
  if (type instanceof ZodLazy2) {
    return getDiscriminator2(type.schema);
  } else if (type instanceof ZodEffects2) {
    return getDiscriminator2(type.innerType());
  } else if (type instanceof ZodLiteral2) {
    return [type.value];
  } else if (type instanceof ZodEnum2) {
    return type.options;
  } else if (type instanceof ZodNativeEnum2) {
    return util2.objectValues(type.enum);
  } else if (type instanceof ZodDefault2) {
    return getDiscriminator2(type._def.innerType);
  } else if (type instanceof ZodUndefined2) {
    return [void 0];
  } else if (type instanceof ZodNull2) {
    return [null];
  } else if (type instanceof ZodOptional2) {
    return [void 0, ...getDiscriminator2(type.unwrap())];
  } else if (type instanceof ZodNullable2) {
    return [null, ...getDiscriminator2(type.unwrap())];
  } else if (type instanceof ZodBranded2) {
    return getDiscriminator2(type.unwrap());
  } else if (type instanceof ZodReadonly2) {
    return getDiscriminator2(type.unwrap());
  } else if (type instanceof ZodCatch2) {
    return getDiscriminator2(type._def.innerType);
  } else {
    return [];
  }
};
var ZodDiscriminatedUnion2 = class _ZodDiscriminatedUnion2 extends ZodType2 {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType2.object) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.object,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    const discriminator = this.discriminator;
    const discriminatorValue = ctx.data[discriminator];
    const option = this.optionsMap.get(discriminatorValue);
    if (!option) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_union_discriminator,
        options: Array.from(this.optionsMap.keys()),
        path: [discriminator]
      });
      return INVALID2;
    }
    if (ctx.common.async) {
      return option._parseAsync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    } else {
      return option._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    }
  }
  get discriminator() {
    return this._def.discriminator;
  }
  get options() {
    return this._def.options;
  }
  get optionsMap() {
    return this._def.optionsMap;
  }
  /**
   * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
   * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
   * have a different value for each object in the union.
   * @param discriminator the name of the discriminator property
   * @param types an array of object schemas
   * @param params
   */
  static create(discriminator, options, params) {
    const optionsMap = /* @__PURE__ */ new Map();
    for (const type of options) {
      const discriminatorValues = getDiscriminator2(type.shape[discriminator]);
      if (!discriminatorValues.length) {
        throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
      }
      for (const value of discriminatorValues) {
        if (optionsMap.has(value)) {
          throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
        }
        optionsMap.set(value, type);
      }
    }
    return new _ZodDiscriminatedUnion2({
      typeName: ZodFirstPartyTypeKind2.ZodDiscriminatedUnion,
      discriminator,
      options,
      optionsMap,
      ...processCreateParams2(params)
    });
  }
};
function mergeValues2(a, b) {
  const aType = getParsedType2(a);
  const bType = getParsedType2(b);
  if (a === b) {
    return { valid: true, data: a };
  } else if (aType === ZodParsedType2.object && bType === ZodParsedType2.object) {
    const bKeys = util2.objectKeys(b);
    const sharedKeys = util2.objectKeys(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 };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType2.array && bType === ZodParsedType2.array) {
    if (a.length !== b.length) {
      return { valid: false };
    }
    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 };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType2.date && bType === ZodParsedType2.date && +a === +b) {
    return { valid: true, data: a };
  } else {
    return { valid: false };
  }
}
var ZodIntersection2 = class extends ZodType2 {
  _parse(input) {
    const { status: status2, ctx } = this._processInputParams(input);
    const handleParsed = (parsedLeft, parsedRight) => {
      if (isAborted2(parsedLeft) || isAborted2(parsedRight)) {
        return INVALID2;
      }
      const merged = mergeValues2(parsedLeft.value, parsedRight.value);
      if (!merged.valid) {
        addIssueToContext2(ctx, {
          code: ZodIssueCode2.invalid_intersection_types
        });
        return INVALID2;
      }
      if (isDirty2(parsedLeft) || isDirty2(parsedRight)) {
        status2.dirty();
      }
      return { status: status2.value, value: merged.data };
    };
    if (ctx.common.async) {
      return Promise.all([
        this._def.left._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        }),
        this._def.right._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        })
      ]).then(([left, right]) => handleParsed(left, right));
    } else {
      return handleParsed(this._def.left._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }), this._def.right._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }));
    }
  }
};
ZodIntersection2.create = (left, right, params) => {
  return new ZodIntersection2({
    left,
    right,
    typeName: ZodFirstPartyTypeKind2.ZodIntersection,
    ...processCreateParams2(params)
  });
};
var ZodTuple2 = class _ZodTuple2 extends ZodType2 {
  _parse(input) {
    const { status: status2, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType2.array) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.array,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    if (ctx.data.length < this._def.items.length) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.too_small,
        minimum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      return INVALID2;
    }
    const rest = this._def.rest;
    if (!rest && ctx.data.length > this._def.items.length) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.too_big,
        maximum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      status2.dirty();
    }
    const items = [...ctx.data].map((item, itemIndex) => {
      const schema = this._def.items[itemIndex] || this._def.rest;
      if (!schema)
        return null;
      return schema._parse(new ParseInputLazyPath2(ctx, item, ctx.path, itemIndex));
    }).filter((x2) => !!x2);
    if (ctx.common.async) {
      return Promise.all(items).then((results) => {
        return ParseStatus2.mergeArray(status2, results);
      });
    } else {
      return ParseStatus2.mergeArray(status2, items);
    }
  }
  get items() {
    return this._def.items;
  }
  rest(rest) {
    return new _ZodTuple2({
      ...this._def,
      rest
    });
  }
};
ZodTuple2.create = (schemas, params) => {
  if (!Array.isArray(schemas)) {
    throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  }
  return new ZodTuple2({
    items: schemas,
    typeName: ZodFirstPartyTypeKind2.ZodTuple,
    rest: null,
    ...processCreateParams2(params)
  });
};
var ZodRecord2 = class _ZodRecord2 extends ZodType2 {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status: status2, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType2.object) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.object,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    const pairs = [];
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    for (const key in ctx.data) {
      pairs.push({
        key: keyType._parse(new ParseInputLazyPath2(ctx, key, ctx.path, key)),
        value: valueType._parse(new ParseInputLazyPath2(ctx, ctx.data[key], ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (ctx.common.async) {
      return ParseStatus2.mergeObjectAsync(status2, pairs);
    } else {
      return ParseStatus2.mergeObjectSync(status2, pairs);
    }
  }
  get element() {
    return this._def.valueType;
  }
  static create(first, second, third) {
    if (second instanceof ZodType2) {
      return new _ZodRecord2({
        keyType: first,
        valueType: second,
        typeName: ZodFirstPartyTypeKind2.ZodRecord,
        ...processCreateParams2(third)
      });
    }
    return new _ZodRecord2({
      keyType: ZodString2.create(),
      valueType: first,
      typeName: ZodFirstPartyTypeKind2.ZodRecord,
      ...processCreateParams2(second)
    });
  }
};
var ZodMap2 = class extends ZodType2 {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status: status2, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType2.map) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.map,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    const pairs = [...ctx.data.entries()].map(([key, value], index) => {
      return {
        key: keyType._parse(new ParseInputLazyPath2(ctx, key, ctx.path, [index, "key"])),
        value: valueType._parse(new ParseInputLazyPath2(ctx, value, ctx.path, [index, "value"]))
      };
    });
    if (ctx.common.async) {
      const finalMap = /* @__PURE__ */ new Map();
      return Promise.resolve().then(async () => {
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          if (key.status === "aborted" || value.status === "aborted") {
            return INVALID2;
          }
          if (key.status === "dirty" || value.status === "dirty") {
            status2.dirty();
          }
          finalMap.set(key.value, value.value);
        }
        return { status: status2.value, value: finalMap };
      });
    } else {
      const finalMap = /* @__PURE__ */ new Map();
      for (const pair of pairs) {
        const key = pair.key;
        const value = pair.value;
        if (key.status === "aborted" || value.status === "aborted") {
          return INVALID2;
        }
        if (key.status === "dirty" || value.status === "dirty") {
          status2.dirty();
        }
        finalMap.set(key.value, value.value);
      }
      return { status: status2.value, value: finalMap };
    }
  }
};
ZodMap2.create = (keyType, valueType, params) => {
  return new ZodMap2({
    valueType,
    keyType,
    typeName: ZodFirstPartyTypeKind2.ZodMap,
    ...processCreateParams2(params)
  });
};
var ZodSet2 = class _ZodSet2 extends ZodType2 {
  _parse(input) {
    const { status: status2, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType2.set) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.set,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    const def = this._def;
    if (def.minSize !== null) {
      if (ctx.data.size < def.minSize.value) {
        addIssueToContext2(ctx, {
          code: ZodIssueCode2.too_small,
          minimum: def.minSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.minSize.message
        });
        status2.dirty();
      }
    }
    if (def.maxSize !== null) {
      if (ctx.data.size > def.maxSize.value) {
        addIssueToContext2(ctx, {
          code: ZodIssueCode2.too_big,
          maximum: def.maxSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.maxSize.message
        });
        status2.dirty();
      }
    }
    const valueType = this._def.valueType;
    function finalizeSet(elements2) {
      const parsedSet = /* @__PURE__ */ new Set();
      for (const element of elements2) {
        if (element.status === "aborted")
          return INVALID2;
        if (element.status === "dirty")
          status2.dirty();
        parsedSet.add(element.value);
      }
      return { status: status2.value, value: parsedSet };
    }
    const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath2(ctx, item, ctx.path, i)));
    if (ctx.common.async) {
      return Promise.all(elements).then((elements2) => finalizeSet(elements2));
    } else {
      return finalizeSet(elements);
    }
  }
  min(minSize, message) {
    return new _ZodSet2({
      ...this._def,
      minSize: { value: minSize, message: errorUtil2.toString(message) }
    });
  }
  max(maxSize, message) {
    return new _ZodSet2({
      ...this._def,
      maxSize: { value: maxSize, message: errorUtil2.toString(message) }
    });
  }
  size(size, message) {
    return this.min(size, message).max(size, message);
  }
  nonempty(message) {
    return this.min(1, message);
  }
};
ZodSet2.create = (valueType, params) => {
  return new ZodSet2({
    valueType,
    minSize: null,
    maxSize: null,
    typeName: ZodFirstPartyTypeKind2.ZodSet,
    ...processCreateParams2(params)
  });
};
var ZodFunction2 = class _ZodFunction2 extends ZodType2 {
  constructor() {
    super(...arguments);
    this.validate = this.implement;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType2.function) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.function,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    function makeArgsIssue(args, error) {
      return makeIssue2({
        data: args,
        path: ctx.path,
        errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default].filter((x2) => !!x2),
        issueData: {
          code: ZodIssueCode2.invalid_arguments,
          argumentsError: error
        }
      });
    }
    function makeReturnsIssue(returns, error) {
      return makeIssue2({
        data: returns,
        path: ctx.path,
        errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default].filter((x2) => !!x2),
        issueData: {
          code: ZodIssueCode2.invalid_return_type,
          returnTypeError: error
        }
      });
    }
    const params = { errorMap: ctx.common.contextualErrorMap };
    const fn = ctx.data;
    if (this._def.returns instanceof ZodPromise2) {
      const me = this;
      return OK2(async function(...args) {
        const error = new ZodError2([]);
        const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
          error.addIssue(makeArgsIssue(args, e));
          throw error;
        });
        const result = await Reflect.apply(fn, this, parsedArgs);
        const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
          error.addIssue(makeReturnsIssue(result, e));
          throw error;
        });
        return parsedReturns;
      });
    } else {
      const me = this;
      return OK2(function(...args) {
        const parsedArgs = me._def.args.safeParse(args, params);
        if (!parsedArgs.success) {
          throw new ZodError2([makeArgsIssue(args, parsedArgs.error)]);
        }
        const result = Reflect.apply(fn, this, parsedArgs.data);
        const parsedReturns = me._def.returns.safeParse(result, params);
        if (!parsedReturns.success) {
          throw new ZodError2([makeReturnsIssue(result, parsedReturns.error)]);
        }
        return parsedReturns.data;
      });
    }
  }
  parameters() {
    return this._def.args;
  }
  returnType() {
    return this._def.returns;
  }
  args(...items) {
    return new _ZodFunction2({
      ...this._def,
      args: ZodTuple2.create(items).rest(ZodUnknown2.create())
    });
  }
  returns(returnType) {
    return new _ZodFunction2({
      ...this._def,
      returns: returnType
    });
  }
  implement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  strictImplement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  static create(args, returns, params) {
    return new _ZodFunction2({
      args: args ? args : ZodTuple2.create([]).rest(ZodUnknown2.create()),
      returns: returns || ZodUnknown2.create(),
      typeName: ZodFirstPartyTypeKind2.ZodFunction,
      ...processCreateParams2(params)
    });
  }
};
var ZodLazy2 = class extends ZodType2 {
  get schema() {
    return this._def.getter();
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const lazySchema = this._def.getter();
    return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  }
};
ZodLazy2.create = (getter, params) => {
  return new ZodLazy2({
    getter,
    typeName: ZodFirstPartyTypeKind2.ZodLazy,
    ...processCreateParams2(params)
  });
};
var ZodLiteral2 = class extends ZodType2 {
  _parse(input) {
    if (input.data !== this._def.value) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext2(ctx, {
        received: ctx.data,
        code: ZodIssueCode2.invalid_literal,
        expected: this._def.value
      });
      return INVALID2;
    }
    return { status: "valid", value: input.data };
  }
  get value() {
    return this._def.value;
  }
};
ZodLiteral2.create = (value, params) => {
  return new ZodLiteral2({
    value,
    typeName: ZodFirstPartyTypeKind2.ZodLiteral,
    ...processCreateParams2(params)
  });
};
function createZodEnum2(values, params) {
  return new ZodEnum2({
    values,
    typeName: ZodFirstPartyTypeKind2.ZodEnum,
    ...processCreateParams2(params)
  });
}
var ZodEnum2 = class _ZodEnum2 extends ZodType2 {
  _parse(input) {
    if (typeof input.data !== "string") {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext2(ctx, {
        expected: util2.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode2.invalid_type
      });
      return INVALID2;
    }
    if (!this._cache) {
      this._cache = new Set(this._def.values);
    }
    if (!this._cache.has(input.data)) {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext2(ctx, {
        received: ctx.data,
        code: ZodIssueCode2.invalid_enum_value,
        options: expectedValues
      });
      return INVALID2;
    }
    return OK2(input.data);
  }
  get options() {
    return this._def.values;
  }
  get enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Values() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  extract(values, newDef = this._def) {
    return _ZodEnum2.create(values, {
      ...this._def,
      ...newDef
    });
  }
  exclude(values, newDef = this._def) {
    return _ZodEnum2.create(this.options.filter((opt) => !values.includes(opt)), {
      ...this._def,
      ...newDef
    });
  }
};
ZodEnum2.create = createZodEnum2;
var ZodNativeEnum2 = class extends ZodType2 {
  _parse(input) {
    const nativeEnumValues = util2.getValidEnumValues(this._def.values);
    const ctx = this._getOrReturnCtx(input);
    if (ctx.parsedType !== ZodParsedType2.string && ctx.parsedType !== ZodParsedType2.number) {
      const expectedValues = util2.objectValues(nativeEnumValues);
      addIssueToContext2(ctx, {
        expected: util2.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode2.invalid_type
      });
      return INVALID2;
    }
    if (!this._cache) {
      this._cache = new Set(util2.getValidEnumValues(this._def.values));
    }
    if (!this._cache.has(input.data)) {
      const expectedValues = util2.objectValues(nativeEnumValues);
      addIssueToContext2(ctx, {
        received: ctx.data,
        code: ZodIssueCode2.invalid_enum_value,
        options: expectedValues
      });
      return INVALID2;
    }
    return OK2(input.data);
  }
  get enum() {
    return this._def.values;
  }
};
ZodNativeEnum2.create = (values, params) => {
  return new ZodNativeEnum2({
    values,
    typeName: ZodFirstPartyTypeKind2.ZodNativeEnum,
    ...processCreateParams2(params)
  });
};
var ZodPromise2 = class extends ZodType2 {
  unwrap() {
    return this._def.type;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType2.promise && ctx.common.async === false) {
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.promise,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    const promisified = ctx.parsedType === ZodParsedType2.promise ? ctx.data : Promise.resolve(ctx.data);
    return OK2(promisified.then((data2) => {
      return this._def.type.parseAsync(data2, {
        path: ctx.path,
        errorMap: ctx.common.contextualErrorMap
      });
    }));
  }
};
ZodPromise2.create = (schema, params) => {
  return new ZodPromise2({
    type: schema,
    typeName: ZodFirstPartyTypeKind2.ZodPromise,
    ...processCreateParams2(params)
  });
};
var ZodEffects2 = class extends ZodType2 {
  innerType() {
    return this._def.schema;
  }
  sourceType() {
    return this._def.schema._def.typeName === ZodFirstPartyTypeKind2.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  }
  _parse(input) {
    const { status: status2, ctx } = this._processInputParams(input);
    const effect = this._def.effect || null;
    const checkCtx = {
      addIssue: (arg) => {
        addIssueToContext2(ctx, arg);
        if (arg.fatal) {
          status2.abort();
        } else {
          status2.dirty();
        }
      },
      get path() {
        return ctx.path;
      }
    };
    checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
    if (effect.type === "preprocess") {
      const processed = effect.transform(ctx.data, checkCtx);
      if (ctx.common.async) {
        return Promise.resolve(processed).then(async (processed2) => {
          if (status2.value === "aborted")
            return INVALID2;
          const result = await this._def.schema._parseAsync({
            data: processed2,
            path: ctx.path,
            parent: ctx
          });
          if (result.status === "aborted")
            return INVALID2;
          if (result.status === "dirty")
            return DIRTY2(result.value);
          if (status2.value === "dirty")
            return DIRTY2(result.value);
          return result;
        });
      } else {
        if (status2.value === "aborted")
          return INVALID2;
        const result = this._def.schema._parseSync({
          data: processed,
          path: ctx.path,
          parent: ctx
        });
        if (result.status === "aborted")
          return INVALID2;
        if (result.status === "dirty")
          return DIRTY2(result.value);
        if (status2.value === "dirty")
          return DIRTY2(result.value);
        return result;
      }
    }
    if (effect.type === "refinement") {
      const executeRefinement = (acc) => {
        const result = effect.refinement(acc, checkCtx);
        if (ctx.common.async) {
          return Promise.resolve(result);
        }
        if (result instanceof Promise) {
          throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
        }
        return acc;
      };
      if (ctx.common.async === false) {
        const inner = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inner.status === "aborted")
          return INVALID2;
        if (inner.status === "dirty")
          status2.dirty();
        executeRefinement(inner.value);
        return { status: status2.value, value: inner.value };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
          if (inner.status === "aborted")
            return INVALID2;
          if (inner.status === "dirty")
            status2.dirty();
          return executeRefinement(inner.value).then(() => {
            return { status: status2.value, value: inner.value };
          });
        });
      }
    }
    if (effect.type === "transform") {
      if (ctx.common.async === false) {
        const base2 = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (!isValid2(base2))
          return INVALID2;
        const result = effect.transform(base2.value, checkCtx);
        if (result instanceof Promise) {
          throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
        }
        return { status: status2.value, value: result };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base2) => {
          if (!isValid2(base2))
            return INVALID2;
          return Promise.resolve(effect.transform(base2.value, checkCtx)).then((result) => ({
            status: status2.value,
            value: result
          }));
        });
      }
    }
    util2.assertNever(effect);
  }
};
ZodEffects2.create = (schema, effect, params) => {
  return new ZodEffects2({
    schema,
    typeName: ZodFirstPartyTypeKind2.ZodEffects,
    effect,
    ...processCreateParams2(params)
  });
};
ZodEffects2.createWithPreprocess = (preprocess, schema, params) => {
  return new ZodEffects2({
    schema,
    effect: { type: "preprocess", transform: preprocess },
    typeName: ZodFirstPartyTypeKind2.ZodEffects,
    ...processCreateParams2(params)
  });
};
var ZodOptional2 = class extends ZodType2 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType2.undefined) {
      return OK2(void 0);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodOptional2.create = (type, params) => {
  return new ZodOptional2({
    innerType: type,
    typeName: ZodFirstPartyTypeKind2.ZodOptional,
    ...processCreateParams2(params)
  });
};
var ZodNullable2 = class extends ZodType2 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType2.null) {
      return OK2(null);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodNullable2.create = (type, params) => {
  return new ZodNullable2({
    innerType: type,
    typeName: ZodFirstPartyTypeKind2.ZodNullable,
    ...processCreateParams2(params)
  });
};
var ZodDefault2 = class extends ZodType2 {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    let data2 = ctx.data;
    if (ctx.parsedType === ZodParsedType2.undefined) {
      data2 = this._def.defaultValue();
    }
    return this._def.innerType._parse({
      data: data2,
      path: ctx.path,
      parent: ctx
    });
  }
  removeDefault() {
    return this._def.innerType;
  }
};
ZodDefault2.create = (type, params) => {
  return new ZodDefault2({
    innerType: type,
    typeName: ZodFirstPartyTypeKind2.ZodDefault,
    defaultValue: typeof params.default === "function" ? params.default : () => params.default,
    ...processCreateParams2(params)
  });
};
var ZodCatch2 = class extends ZodType2 {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const newCtx = {
      ...ctx,
      common: {
        ...ctx.common,
        issues: []
      }
    };
    const result = this._def.innerType._parse({
      data: newCtx.data,
      path: newCtx.path,
      parent: {
        ...newCtx
      }
    });
    if (isAsync2(result)) {
      return result.then((result2) => {
        return {
          status: "valid",
          value: result2.status === "valid" ? result2.value : this._def.catchValue({
            get error() {
              return new ZodError2(newCtx.common.issues);
            },
            input: newCtx.data
          })
        };
      });
    } else {
      return {
        status: "valid",
        value: result.status === "valid" ? result.value : this._def.catchValue({
          get error() {
            return new ZodError2(newCtx.common.issues);
          },
          input: newCtx.data
        })
      };
    }
  }
  removeCatch() {
    return this._def.innerType;
  }
};
ZodCatch2.create = (type, params) => {
  return new ZodCatch2({
    innerType: type,
    typeName: ZodFirstPartyTypeKind2.ZodCatch,
    catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
    ...processCreateParams2(params)
  });
};
var ZodNaN2 = class extends ZodType2 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType2.nan) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext2(ctx, {
        code: ZodIssueCode2.invalid_type,
        expected: ZodParsedType2.nan,
        received: ctx.parsedType
      });
      return INVALID2;
    }
    return { status: "valid", value: input.data };
  }
};
ZodNaN2.create = (params) => {
  return new ZodNaN2({
    typeName: ZodFirstPartyTypeKind2.ZodNaN,
    ...processCreateParams2(params)
  });
};
var BRAND2 = /* @__PURE__ */ Symbol("zod_brand");
var ZodBranded2 = class extends ZodType2 {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const data2 = ctx.data;
    return this._def.type._parse({
      data: data2,
      path: ctx.path,
      parent: ctx
    });
  }
  unwrap() {
    return this._def.type;
  }
};
var ZodPipeline2 = class _ZodPipeline2 extends ZodType2 {
  _parse(input) {
    const { status: status2, ctx } = this._processInputParams(input);
    if (ctx.common.async) {
      const handleAsync = async () => {
        const inResult = await this._def.in._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inResult.status === "aborted")
          return INVALID2;
        if (inResult.status === "dirty") {
          status2.dirty();
          return DIRTY2(inResult.value);
        } else {
          return this._def.out._parseAsync({
            data: inResult.value,
            path: ctx.path,
            parent: ctx
          });
        }
      };
      return handleAsync();
    } else {
      const inResult = this._def.in._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
      if (inResult.status === "aborted")
        return INVALID2;
      if (inResult.status === "dirty") {
        status2.dirty();
        return {
          status: "dirty",
          value: inResult.value
        };
      } else {
        return this._def.out._parseSync({
          data: inResult.value,
          path: ctx.path,
          parent: ctx
        });
      }
    }
  }
  static create(a, b) {
    return new _ZodPipeline2({
      in: a,
      out: b,
      typeName: ZodFirstPartyTypeKind2.ZodPipeline
    });
  }
};
var ZodReadonly2 = class extends ZodType2 {
  _parse(input) {
    const result = this._def.innerType._parse(input);
    const freeze = (data2) => {
      if (isValid2(data2)) {
        data2.value = Object.freeze(data2.value);
      }
      return data2;
    };
    return isAsync2(result) ? result.then((data2) => freeze(data2)) : freeze(result);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodReadonly2.create = (type, params) => {
  return new ZodReadonly2({
    innerType: type,
    typeName: ZodFirstPartyTypeKind2.ZodReadonly,
    ...processCreateParams2(params)
  });
};
function cleanParams(params, data2) {
  const p = typeof params === "function" ? params(data2) : typeof params === "string" ? { message: params } : params;
  const p2 = typeof p === "string" ? { message: p } : p;
  return p2;
}
function custom2(check, _params = {}, fatal) {
  if (check)
    return ZodAny2.create().superRefine((data2, ctx) => {
      const r2 = check(data2);
      if (r2 instanceof Promise) {
        return r2.then((r3) => {
          if (!r3) {
            const params = cleanParams(_params, data2);
            const _fatal = params.fatal ?? fatal ?? true;
            ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
          }
        });
      }
      if (!r2) {
        const params = cleanParams(_params, data2);
        const _fatal = params.fatal ?? fatal ?? true;
        ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
      }
      return;
    });
  return ZodAny2.create();
}
var late2 = {
  object: ZodObject2.lazycreate
};
var ZodFirstPartyTypeKind2;
(function(ZodFirstPartyTypeKind3) {
  ZodFirstPartyTypeKind3["ZodString"] = "ZodString";
  ZodFirstPartyTypeKind3["ZodNumber"] = "ZodNumber";
  ZodFirstPartyTypeKind3["ZodNaN"] = "ZodNaN";
  ZodFirstPartyTypeKind3["ZodBigInt"] = "ZodBigInt";
  ZodFirstPartyTypeKind3["ZodBoolean"] = "ZodBoolean";
  ZodFirstPartyTypeKind3["ZodDate"] = "ZodDate";
  ZodFirstPartyTypeKind3["ZodSymbol"] = "ZodSymbol";
  ZodFirstPartyTypeKind3["ZodUndefined"] = "ZodUndefined";
  ZodFirstPartyTypeKind3["ZodNull"] = "ZodNull";
  ZodFirstPartyTypeKind3["ZodAny"] = "ZodAny";
  ZodFirstPartyTypeKind3["ZodUnknown"] = "ZodUnknown";
  ZodFirstPartyTypeKind3["ZodNever"] = "ZodNever";
  ZodFirstPartyTypeKind3["ZodVoid"] = "ZodVoid";
  ZodFirstPartyTypeKind3["ZodArray"] = "ZodArray";
  ZodFirstPartyTypeKind3["ZodObject"] = "ZodObject";
  ZodFirstPartyTypeKind3["ZodUnion"] = "ZodUnion";
  ZodFirstPartyTypeKind3["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  ZodFirstPartyTypeKind3["ZodIntersection"] = "ZodIntersection";
  ZodFirstPartyTypeKind3["ZodTuple"] = "ZodTuple";
  ZodFirstPartyTypeKind3["ZodRecord"] = "ZodRecord";
  ZodFirstPartyTypeKind3["ZodMap"] = "ZodMap";
  ZodFirstPartyTypeKind3["ZodSet"] = "ZodSet";
  ZodFirstPartyTypeKind3["ZodFunction"] = "ZodFunction";
  ZodFirstPartyTypeKind3["ZodLazy"] = "ZodLazy";
  ZodFirstPartyTypeKind3["ZodLiteral"] = "ZodLiteral";
  ZodFirstPartyTypeKind3["ZodEnum"] = "ZodEnum";
  ZodFirstPartyTypeKind3["ZodEffects"] = "ZodEffects";
  ZodFirstPartyTypeKind3["ZodNativeEnum"] = "ZodNativeEnum";
  ZodFirstPartyTypeKind3["ZodOptional"] = "ZodOptional";
  ZodFirstPartyTypeKind3["ZodNullable"] = "ZodNullable";
  ZodFirstPartyTypeKind3["ZodDefault"] = "ZodDefault";
  ZodFirstPartyTypeKind3["ZodCatch"] = "ZodCatch";
  ZodFirstPartyTypeKind3["ZodPromise"] = "ZodPromise";
  ZodFirstPartyTypeKind3["ZodBranded"] = "ZodBranded";
  ZodFirstPartyTypeKind3["ZodPipeline"] = "ZodPipeline";
  ZodFirstPartyTypeKind3["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind2 || (ZodFirstPartyTypeKind2 = {}));
var instanceOfType2 = (cls, params = {
  message: `Input not instance of ${cls.name}`
}) => custom2((data2) => data2 instanceof cls, params);
var stringType2 = ZodString2.create;
var numberType2 = ZodNumber2.create;
var nanType2 = ZodNaN2.create;
var bigIntType2 = ZodBigInt2.create;
var booleanType2 = ZodBoolean2.create;
var dateType2 = ZodDate2.create;
var symbolType2 = ZodSymbol2.create;
var undefinedType2 = ZodUndefined2.create;
var nullType2 = ZodNull2.create;
var anyType2 = ZodAny2.create;
var unknownType2 = ZodUnknown2.create;
var neverType2 = ZodNever2.create;
var voidType2 = ZodVoid2.create;
var arrayType2 = ZodArray2.create;
var objectType2 = ZodObject2.create;
var strictObjectType2 = ZodObject2.strictCreate;
var unionType2 = ZodUnion2.create;
var discriminatedUnionType2 = ZodDiscriminatedUnion2.create;
var intersectionType2 = ZodIntersection2.create;
var tupleType2 = ZodTuple2.create;
var recordType2 = ZodRecord2.create;
var mapType2 = ZodMap2.create;
var setType2 = ZodSet2.create;
var functionType2 = ZodFunction2.create;
var lazyType2 = ZodLazy2.create;
var literalType2 = ZodLiteral2.create;
var enumType2 = ZodEnum2.create;
var nativeEnumType2 = ZodNativeEnum2.create;
var promiseType2 = ZodPromise2.create;
var effectsType2 = ZodEffects2.create;
var optionalType2 = ZodOptional2.create;
var nullableType2 = ZodNullable2.create;
var preprocessType2 = ZodEffects2.createWithPreprocess;
var pipelineType2 = ZodPipeline2.create;
var ostring2 = () => stringType2().optional();
var onumber2 = () => numberType2().optional();
var oboolean2 = () => booleanType2().optional();
var coerce2 = {
  string: ((arg) => ZodString2.create({ ...arg, coerce: true })),
  number: ((arg) => ZodNumber2.create({ ...arg, coerce: true })),
  boolean: ((arg) => ZodBoolean2.create({
    ...arg,
    coerce: true
  })),
  bigint: ((arg) => ZodBigInt2.create({ ...arg, coerce: true })),
  date: ((arg) => ZodDate2.create({ ...arg, coerce: true }))
};
var NEVER2 = INVALID2;

// src/cf.ts
var import_node_assert3 = __toESM(require("node:assert"));
var import_node_fs3 = require("node:fs");
var import_promises = require("node:fs/promises");
var import_node_path3 = __toESM(require("node:path"));
var import_undici = require("undici");
function getDefaultCfPath() {
  const miniflareCacheDir = process.env.MINIFLARE_CACHE_DIR;
  if (miniflareCacheDir) {
    return import_node_path3.default.resolve(miniflareCacheDir, "cf.json");
  }
  const nodeModulesMfPath = import_node_path3.default.resolve("node_modules", ".mf");
  const wranglerCachePath = import_node_path3.default.resolve(".wrangler", "cache");
  if ((0, import_node_fs3.existsSync)(nodeModulesMfPath)) {
    return import_node_path3.default.resolve(nodeModulesMfPath, "cf.json");
  }
  if ((0, import_node_fs3.existsSync)(wranglerCachePath)) {
    return import_node_path3.default.resolve(wranglerCachePath, "cf.json");
  }
  if ((0, import_node_fs3.existsSync)("node_modules")) {
    return import_node_path3.default.resolve(nodeModulesMfPath, "cf.json");
  }
  return import_node_path3.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: ""
  },
  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_promises.readFile)(cfPath, "utf8"));
    const cfStat = await (0, import_promises.stat)(cfPath);
    (0, import_node_assert3.default)(Date.now() - cfStat.mtimeMs <= CF_DAYS * DAY);
    return storedCf;
  } catch {
  }
  try {
    const res = await (0, import_undici.fetch)(defaultCfFetchEndpoint);
    const cfText = await res.text();
    const storedCf = JSON.parse(cfText);
    await (0, import_promises.mkdir)(import_node_path3.default.dirname(cfPath), { recursive: true });
    await (0, import_promises.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" + dim2(e.cause ? e.cause.stack : e.stack)
    );
    return fallbackCf;
  }
}

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

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

// src/workers/core/constants.ts
var CorePaths = {
  /** Magic proxy used by getPlatformProxy */
  PLATFORM_PROXY: "/cdn-cgi/platform-proxy",
  /** Trigger scheduled event handlers */
  SCHEDULED: "/cdn-cgi/handler/scheduled",
  /** Trigger email event handlers */
  EMAIL: "/cdn-cgi/handler/email",
  /** Handler path prefix for validation */
  HANDLER_PREFIX: "/cdn-cgi/handler/",
  /** Live reload WebSocket endpoint */
  LIVE_RELOAD: "/cdn-cgi/mf/reload",
  /** Local explorer UI and API */
  EXPLORER: "/cdn-cgi/explorer",
  /** Legacy way to trigger scheduled event handlers */
  LEGACY_SCHEDULED: "/cdn-cgi/mf/scheduled"
};
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",
  ROUTE_OVERRIDE: "MF-Route-Override",
  CF_BLOB: "MF-CF-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",
  IMAGES_SERVICE: "MINIFLARE_IMAGES_SERVICE",
  TEXT_UPSTREAM_URL: "MINIFLARE_UPSTREAM_URL",
  JSON_CF_BLOB: "CF_BLOB",
  JSON_ROUTES: "MINIFLARE_ROUTES",
  JSON_LOG_LEVEL: "MINIFLARE_LOG_LEVEL",
  DATA_LIVE_RELOAD_SCRIPT: "MINIFLARE_LIVE_RELOAD_SCRIPT",
  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",
  JSON_TELEMETRY_CONFIG: "MINIFLARE_TELEMETRY_CONFIG"
};
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 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_assert4 = __toESM(require("node:assert"));
var import_node_buffer = 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(object) {
  return Object.getOwnPropertySymbols(object).filter(
    (symbol) => Object.getOwnPropertyDescriptor(object, symbol).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 c = s.charCodeAt(i);
    if (c < 48 || c > 57) return false;
  }
  const n = +s;
  if (n >= 2 ** 32 - 1) return false;
  if (n < 0) return false;
  return true;
}
function valid_array_indices(array) {
  const keys = Object.keys(array);
  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(string) {
  const binaryString = asciiToBinary(string);
  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(data2) {
  if (data2.length % 4 === 0) {
    data2 = data2.replace(/==?$/, "");
  }
  let output = "";
  let buffer = 0;
  let accumulatedBits = 0;
  for (let i = 0; i < data2.length; i++) {
    buffer <<= 6;
    buffer |= KEY_STRING.indexOf(data2[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 parse4(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 set = /* @__PURE__ */ new Set();
            hydrated[index] = set;
            for (let i = 1; i < value.length; i += 1) {
              set.add(hydrate(value[i]));
            }
            break;
          case "Map":
            const map = /* @__PURE__ */ new Map();
            hydrated[index] = map;
            for (let i = 1; i < value.length; i += 2) {
              map.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 base64 = value[1];
            if (typeof base64 !== "string") {
              throw new Error("Invalid ArrayBuffer encoding");
            }
            const arraybuffer = decode64(base64);
            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 url38 = new URL(value[1]);
            hydrated[index] = url38;
            break;
          }
          case "URLSearchParams": {
            const url38 = new URLSearchParams(value[1]);
            hydrated[index] = url38;
            break;
          }
          default:
            throw new Error(`Unknown type ${type}`);
        }
      } else if (value[0] === SPARSE) {
        const len = value[1];
        const array = new Array(len);
        hydrated[index] = array;
        for (let i = 2; i < value.length; i += 2) {
          const idx = value[i];
          array[idx] = hydrate(value[i + 1]);
        }
      } else {
        const array = new Array(value.length);
        hydrated[index] = array;
        for (let i = 0; i < value.length; i += 1) {
          const n = value[i];
          if (n === HOLE) continue;
          array[i] = hydrate(n);
        }
      }
    } else {
      const object = {};
      hydrated[index] = object;
      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];
        object[key] = hydrate(n);
      }
    }
    return hydrated[index];
  }
  return hydrate(0);
}

// ../../node_modules/.pnpm/devalue@5.6.3/node_modules/devalue/src/stringify.js
function stringify2(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 p = 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 = p++;
    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 d2 = String(thing.length).length;
              const hole_cost = (thing.length - population) * 3;
              const sparse_cost = 4 + d2 + population * (d2 + 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 m2 = +/(\d+)/.exec(type)[1] / 8;
            str += `,${a / m2},${b / m2}`;
          }
          str += "]";
          break;
        }
        case "ArrayBuffer": {
          const arraybuffer = thing;
          const base64 = encode64(arraybuffer);
          str = `["ArrayBuffer","${base64}"]`;
          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_buffer.Buffer.from(value).toString("base64")];
    }
  },
  ArrayBufferView(value) {
    if (ArrayBuffer.isView(value)) {
      return [
        value.constructor.name,
        value.buffer,
        value.byteOffset,
        value.byteLength
      ];
    }
  },
  RegExp(value) {
    if (value instanceof RegExp) {
      const { source, flags } = value;
      const encoded = import_node_buffer.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_assert4.default)(Array.isArray(value));
    const [encoded] = value;
    (0, import_node_assert4.default)(typeof encoded === "string");
    const view = import_node_buffer.Buffer.from(encoded, "base64");
    return view.buffer.slice(
      view.byteOffset,
      view.byteOffset + view.byteLength
    );
  },
  ArrayBufferView(value) {
    (0, import_node_assert4.default)(Array.isArray(value));
    const [name, buffer, byteOffset, byteLength] = value;
    (0, import_node_assert4.default)(typeof name === "string");
    (0, import_node_assert4.default)(buffer instanceof ArrayBuffer);
    (0, import_node_assert4.default)(typeof byteOffset === "number");
    (0, import_node_assert4.default)(typeof byteLength === "number");
    const ctor = globalThis[name];
    (0, import_node_assert4.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_assert4.default)(Array.isArray(value));
    const [name, encoded, flags] = value;
    (0, import_node_assert4.default)(typeof name === "string");
    (0, import_node_assert4.default)(typeof encoded === "string");
    const source = import_node_buffer.Buffer.from(encoded, "base64").toString("utf-8");
    return new RegExp(source, flags);
  },
  Error(value) {
    (0, import_node_assert4.default)(Array.isArray(value));
    const [name, message, stack, cause] = value;
    (0, import_node_assert4.default)(typeof name === "string");
    (0, import_node_assert4.default)(typeof message === "string");
    (0, import_node_assert4.default)(stack === void 0 || typeof stack === "string");
    const ctor = globalThis[name];
    (0, import_node_assert4.default)(ALLOWED_ERROR_CONSTRUCTORS.includes(ctor));
    const error = new ctor(message, { cause });
    error.stack = stack;
    return error;
  }
};
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_assert4.default)(typeof value === "object" && value !== null);
      return new impl.Headers(value);
    },
    Request(value) {
      (0, import_node_assert4.default)(Array.isArray(value));
      const [method, url38, headers, cf, body] = value;
      (0, import_node_assert4.default)(typeof method === "string");
      (0, import_node_assert4.default)(typeof url38 === "string");
      (0, import_node_assert4.default)(headers instanceof impl.Headers);
      (0, import_node_assert4.default)(body === null || impl.isReadableStream(body));
      return new impl.Request(url38, {
        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_assert4.default)(Array.isArray(value));
      const [status2, statusText, headers, cf, body] = value;
      (0, import_node_assert4.default)(typeof status2 === "number");
      (0, import_node_assert4.default)(typeof statusText === "string");
      (0, import_node_assert4.default)(headers instanceof impl.Headers);
      (0, import_node_assert4.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 = stringify2(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 array = [streamBuffers.shift(), value2.type];
        if (value2 instanceof impl.File) {
          array.push(value2.name, value2.lastModified);
        }
        return array;
      }
    };
    const stringifiedValue2 = stringify2(value, streamReducers);
    return { value: stringifiedValue2, unbufferedStream };
  });
}
var __MiniflareFunctionWrapper = class {
  constructor(fnWithProps) {
    return new Proxy(this, {
      get: (_2, key) => {
        if (key === "__miniflareWrappedFunction") return fnWithProps;
        return fnWithProps[key];
      }
    });
  }
};
function parseWithReadableStreams(impl, stringified, revivers2) {
  const streamRevivers = {
    ReadableStream(value) {
      if (value === true) {
        (0, import_node_assert4.default)(stringified.unbufferedStream !== void 0);
        return stringified.unbufferedStream;
      }
      (0, import_node_assert4.default)(value instanceof ArrayBuffer);
      return impl.unbufferReadableStream(value);
    },
    Blob(value) {
      (0, import_node_assert4.default)(Array.isArray(value));
      if (value.length === 2) {
        const [buffer, type] = value;
        (0, import_node_assert4.default)(buffer instanceof ArrayBuffer);
        (0, import_node_assert4.default)(typeof type === "string");
        const opts = {};
        if (type !== "") opts.type = type;
        return new impl.Blob([buffer], opts);
      } else {
        (0, import_node_assert4.default)(value.length === 4);
        const [buffer, type, name, lastModified] = value;
        (0, import_node_assert4.default)(buffer instanceof ArrayBuffer);
        (0, import_node_assert4.default)(typeof type === "string");
        (0, import_node_assert4.default)(typeof name === "string");
        (0, import_node_assert4.default)(typeof lastModified === "number");
        const opts = { lastModified };
        if (type !== "") opts.type = type;
        return new impl.File([buffer], name, opts);
      }
    },
    ...revivers2
  };
  return parse4(stringified.value, streamRevivers);
}

// src/workers/core/routing.ts
function matchRoutes(routes, url38) {
  for (const route of routes) {
    if (route.protocol && route.protocol !== url38.protocol) continue;
    if (route.allowHostnamePrefix) {
      if (!url38.hostname.endsWith(route.hostname)) continue;
    } else {
      if (url38.hostname !== route.hostname) continue;
    }
    const path62 = url38.pathname + url38.search;
    if (route.allowPathSuffix) {
      if (!path62.startsWith(route.path)) continue;
    } else {
      if (path62 !== 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",
  MAYBE_JSON_ENABLE_STICKY_BLOBS: "MINIFLARE_STICKY_BLOBS"
};
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_buffer2 = require("node:buffer");
function viewToBuffer(view) {
  return view.buffer.slice(
    view.byteOffset,
    view.byteOffset + view.byteLength
  );
}
function base64Encode(value) {
  return import_node_buffer2.Buffer.from(value, "utf8").toString("base64");
}
function base64Decode(encoded) {
  return import_node_buffer2.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_assert5 = __toESM(require("node:assert"));
var DeferredPromise = class extends Promise {
  resolve;
  reject;
  constructor(executor = () => {
  }) {
    let promiseResolve;
    let promiseReject;
    super((resolve6, reject) => {
      promiseResolve = resolve6;
      promiseReject = reject;
      return executor(resolve6, reject);
    });
    this.resolve = promiseResolve;
    this.reject = promiseReject;
  }
};
var Mutex = class {
  locked = false;
  resolveQueue = [];
  drainQueue = [];
  lock() {
    if (!this.locked) {
      this.locked = true;
      return;
    }
    return new Promise((resolve6) => this.resolveQueue.push(resolve6));
  }
  unlock() {
    (0, import_node_assert5.default)(this.locked);
    if (this.resolveQueue.length > 0) {
      this.resolveQueue.shift()?.();
    } else {
      this.locked = false;
      let resolve6;
      while ((resolve6 = this.drainQueue.shift()) !== void 0) resolve6();
    }
  }
  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((resolve6) => this.drainQueue.push(resolve6));
  }
};
var WaitGroup = class {
  counter = 0;
  resolveQueue = [];
  add() {
    this.counter++;
  }
  done() {
    (0, import_node_assert5.default)(this.counter > 0);
    this.counter--;
    if (this.counter === 0) {
      let resolve6;
      while ((resolve6 = this.resolveQueue.shift()) !== void 0) resolve6();
    }
  }
  wait() {
    if (this.counter === 0) return Promise.resolve();
    return new Promise((resolve6) => this.resolveQueue.push(resolve6));
  }
};

// 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 url38 = new URL(request4.url);
  return url38.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"
};

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

// src/workers/queues/schemas.ts
var QueueMessageDelaySchema = external_exports.number().int().min(0).max(86400).optional();
var QueueProducerOptionsSchema = /* @__PURE__ */ external_exports.object({
  // https://developers.cloudflare.com/queues/platform/configuration/#producer
  queueName: external_exports.string(),
  deliveryDelay: QueueMessageDelaySchema
});
var QueueProducerSchema = /* @__PURE__ */ external_exports.intersection(
  QueueProducerOptionsSchema,
  external_exports.object({ workerName: external_exports.string() })
);
var QueueProducersSchema = /* @__PURE__ */ external_exports.record(QueueProducerSchema);
var QueueConsumerOptionsSchema = /* @__PURE__ */ external_exports.object({
  // https://developers.cloudflare.com/queues/platform/configuration/#consumer
  // https://developers.cloudflare.com/queues/platform/limits/
  maxBatchSize: external_exports.number().min(0).max(100).optional(),
  maxBatchTimeout: external_exports.number().min(0).max(60).optional(),
  // seconds
  maxRetires: external_exports.number().min(0).max(100).optional(),
  // deprecated
  maxRetries: external_exports.number().min(0).max(100).optional(),
  deadLetterQueue: external_exports.ostring(),
  retryDelay: QueueMessageDelaySchema
}).transform((queue) => {
  if (queue.maxRetires !== void 0) {
    queue.maxRetries = queue.maxRetires;
  }
  return queue;
});
var QueueConsumerSchema = /* @__PURE__ */ external_exports.intersection(
  QueueConsumerOptionsSchema,
  external_exports.object({ workerName: external_exports.string() })
);
var QueueConsumersSchema = /* @__PURE__ */ external_exports.record(QueueConsumerSchema);
var QueueContentTypeSchema = /* @__PURE__ */ external_exports.enum(["text", "json", "bytes", "v8"]).default("v8");
var QueueIncomingMessageSchema = /* @__PURE__ */ external_exports.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_exports.ostring(),
  timestamp: external_exports.onumber()
});
var QueuesBatchRequestSchema = /* @__PURE__ */ external_exports.object({
  messages: external_exports.array(QueueIncomingMessageSchema)
});

// src/http/request.ts
var import_undici2 = require("undici");
var kCf = /* @__PURE__ */ Symbol("kCf");
var Request = class _Request extends import_undici2.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, init2) {
    super(input, init2);
    this[kCf] = init2?.cf;
    if (input instanceof _Request) this[kCf] ??= input.cf;
  }
  get cf() {
    return this[kCf];
  }
  // JSDoc comment so retained when bundling types with api-extractor
  /** @ts-expect-error `clone` is actually defined as a method internally */
  clone() {
    const request4 = super.clone();
    Object.setPrototypeOf(request4, _Request.prototype);
    request4[kCf] = this[kCf];
    return request4;
  }
};

// src/http/response.ts
var import_undici3 = require("undici");
var kWebSocket = /* @__PURE__ */ Symbol("kWebSocket");
var Response2 = class _Response extends import_undici3.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_undici3.Response.error();
    Object.setPrototypeOf(response, _Response.prototype);
    return response;
  }
  static redirect(url38, status2) {
    const response = import_undici3.Response.redirect(url38, status2);
    Object.setPrototypeOf(response, _Response.prototype);
    return response;
  }
  static json(data2, init2) {
    const body = JSON.stringify(data2);
    const response = new _Response(body, init2);
    response.headers.set("Content-Type", "application/json");
    return response;
  }
  constructor(body, init2) {
    if (init2?.webSocket) {
      if (init2.status !== 101) {
        throw new RangeError(
          "Responses with a WebSocket must have status code 101."
        );
      }
      init2 = { ...init2, status: 200 };
    }
    super(body, init2);
    this[kWebSocket] = init2?.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];
  }
  // JSDoc comment so retained when bundling types with api-extractor
  /** @ts-expect-error `clone` is actually defined as a method internally */
  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_assert7 = __toESM(require("node:assert"));
var import_node_events = require("node:events");
var import_ws = __toESM(require("ws"));

// src/shared/colour.ts
var originalEnabled = $.enabled;
function _forceColour(enabled = originalEnabled) {
  $.enabled = enabled;
}

// 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_MULTIPLE_OUTBOUNDS",
  // Both `outboundService` and `fetchMock` specified
  "ERR_INVALID_WRAPPED",
  // Worker not allowed to be used as wrapped binding
  "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_CYCLIC",
  // Generate cyclic workerd config
  "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}]`;
  }
  // 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_path4 = __toESM(require("node:path"));
var import_node_util = require("node:util");
var cwd = process.cwd();
var cwdNodeModules = import_node_path4.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 */]: red2,
  [2 /* WARN */]: yellow2,
  [3 /* INFO */]: green2,
  [4 /* DEBUG */]: grey,
  [5 /* VERBOSE */]: (input) => dim2(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 formatError(error) {
  let message;
  if (error.stack) {
    message = processStackTrace(error.stack, (line) => {
      if (!line.includes(cwd) || line.includes(cwdNodeModules)) {
        return dim2(line);
      }
      return line;
    });
  } else {
    message = error.toString();
  }
  if (error.cause instanceof Error) {
    message += `
Caused by: ${formatError(error.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 : "";
  }
  #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 */, formatError(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_util.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((error) => {
    return writer.abort(error);
  });
  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_assert6 = __toESM(require("node:assert"));
var import_node_path5 = __toESM(require("node:path"));
function zAwaitable(type) {
  return type.or(external_exports.promise(type));
}
var LiteralSchema = external_exports.union([
  external_exports.string(),
  external_exports.number(),
  external_exports.boolean(),
  external_exports.null()
]);
var JsonSchema = external_exports.lazy(
  () => external_exports.union([LiteralSchema, external_exports.array(JsonSchema), external_exports.record(JsonSchema)])
);
var rootPath;
function parseWithRootPath(newRootPath, schema, data2, params) {
  rootPath = newRootPath;
  try {
    return schema.parse(data2, params);
  } finally {
    rootPath = void 0;
  }
}
var PathSchema = external_exports.string().transform((p) => {
  (0, import_node_assert6.default)(
    rootPath !== void 0,
    "Expected `PathSchema` to be parsed within `parseWithRootPath()`"
  );
  return import_node_path5.default.resolve(rootPath, p);
});
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, init2) {
    super(type);
    this.data = init2.data;
  }
};
var CloseEvent = class extends Event {
  code;
  reason;
  wasClean;
  constructor(type, init2) {
    super(type);
    this.code = init2?.code ?? 1005;
    this.reason = init2?.reason ?? "";
    this.wasClean = init2?.wasClean ?? false;
  }
};
var ErrorEvent = class extends Event {
  error;
  constructor(type, init2) {
    super(type);
    this.error = init2?.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_assert7.default)(pair !== void 0);
    if (pair[kAccepted]) {
      pair.dispatchEvent(event);
    } else {
      (0, import_node_assert7.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_assert7.default)(pair !== void 0);
    this[kClosedOutgoing] = true;
    pair[kClosedIncoming] = true;
    const event = new CloseEvent("close", { code, reason });
    void this.#queuingDispatchToPair(event);
  }
  [kError](error) {
    const event = new ErrorEvent("error", { error });
    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", (error) => {
    pair[kError](error);
  });
  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 fetch4(input, init2) {
  const requestInit = init2;
  const request4 = new Request(input, requestInit);
  if (request4.method === "GET" && request4.headers.get("upgrade") === "websocket") {
    const url38 = new URL(request4.url);
    if (url38.protocol !== "http:" && url38.protocol !== "https:") {
      throw new TypeError(
        `Fetch API cannot load: ${url38.toString()}.
Make sure you're using http(s):// URLs for WebSocket requests via fetch.`
      );
    }
    url38.protocol = url38.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, url38.pathname + url38.search);
      rejectUnauthorized = { rejectUnauthorized: false };
    }
    const ws = new import_ws2.default(url38, protocols, {
      followRedirects: request4.redirect === "follow",
      headers: Object.fromEntries(headers.entries()),
      ...rejectUnauthorized
    });
    const responsePromise = new DeferredPromise();
    ws.once("upgrade", (req) => {
      const headers2 = convertUndiciHeadersToStandard(req.headers);
      const [worker, client] = Object.values(new WebSocketPair());
      const couplePromise = coupleWebSocket(ws, client);
      const response2 = new Response2(null, {
        status: 101,
        webSocket: worker,
        headers: headers2
      });
      responsePromise.resolve(couplePromise.then(() => response2));
    });
    ws.once("unexpected-response", (_2, req) => {
      const headers2 = convertUndiciHeadersToStandard(req.headers);
      const response2 = new Response2(req, {
        status: req.statusCode,
        headers: headers2
      });
      responsePromise.resolve(response2);
    });
    return responsePromise;
  }
  const response = await undici.fetch(request4, {
    dispatcher: requestInit?.dispatcher
  });
  return new Response2(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_assert8.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 v2 of value) {
            standardHeaders.append(name, v2);
          }
        }
      }
    }
    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 v2 of value) {
            standardHeaders.append(name, v2);
          }
        }
      }
    }
    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);
  }
  cfBlobJson;
  addHeaders(headers, path62) {
    const originalURL = this.userRuntimeOrigin + path62;
    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 path62 = options.path;
      if (options.query !== void 0) {
        const url38 = new URL(path62, "http://placeholder/");
        for (const [key, value] of Object.entries(options.query)) {
          url38.searchParams.append(key, value);
        }
        path62 = url38.pathname + url38.search;
      }
      const headers = convertUndiciHeadersToStandard(options.headers ?? {});
      this.addHeaders(headers, path62);
      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/server.ts
var import_promises2 = __toESM(require("node:fs/promises"));

// 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.httpsKeyPath) && (coreOpts.httpsCert || coreOpts.httpsCertPath)) {
    privateKey = await valueOrFile(coreOpts.httpsKey, coreOpts.httpsKeyPath);
    certificateChain = await valueOrFile(
      coreOpts.httpsCert,
      coreOpts.httpsCertPath
    );
  } else if (coreOpts.https) {
    privateKey = KEY;
    certificateChain = CERT;
  }
  if (privateKey && certificateChain) {
    return {
      https: {
        tlsOptions: {
          keypair: {
            privateKey,
            certificateChain
          }
        }
      }
    };
  } else {
    return { http: {} };
  }
}
function valueOrFile(value, filePath) {
  return value ?? (filePath && import_promises2.default.readFile(filePath, "utf8"));
}

// src/http/helpers.ts
var import_node_os4 = require("node:os");
function getAccessibleHosts(ipv4Only = false) {
  const hosts = [];
  Object.values((0, import_node_os4.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_undici4 = require("undici");

// src/plugins/shared/index.ts
var import_node_crypto = __toESM(require("node:crypto"));
var import_node_fs4 = require("node:fs");
var import_promises3 = __toESM(require("node:fs/promises"));
var import_node_path6 = __toESM(require("node:path"));
var import_node_url2 = require("node:url");

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

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

// src/plugins/shared/constants.ts
var SOCKET_ENTRY = "entry";
var SOCKET_ENTRY_LOCAL = "entry:local";
var SOCKET_DIRECT_PREFIX = "direct";
function getDirectSocketName(workerIndex, entrypoint) {
  return `${SOCKET_DIRECT_PREFIX}:${workerIndex}:${entrypoint}`;
}
var SERVICE_LOOPBACK = "loopback";
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 WORKER_BINDING_ENABLE_STICKY_BLOBS = {
  name: SharedBindings.MAYBE_JSON_ENABLE_STICKY_BLOBS,
  json: "true"
};
var enableControlEndpoints = false;
function getMiniflareObjectBindings(unsafeStickyBlobs) {
  const result = [];
  if (enableControlEndpoints) {
    result.push(WORKER_BINDING_ENABLE_CONTROL_ENDPOINTS);
  }
  if (unsafeStickyBlobs) {
    result.push(WORKER_BINDING_ENABLE_STICKY_BLOBS);
  }
  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: [
      { name: SharedBindings.TEXT_NAMESPACE, text: namespace },
      {
        name: SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT,
        durableObjectNamespace
      }
    ]
  };
}
function remoteProxyClientWorker(remoteProxyConnectionString, binding, script) {
  return {
    compatibilityDate: "2025-01-01",
    modules: [
      {
        name: "index.worker.js",
        esModule: (script ?? remote_proxy_client_worker_default)()
      }
    ],
    bindings: [
      ...remoteProxyConnectionString?.href ? [
        {
          name: "remoteProxyConnectionString",
          text: remoteProxyConnectionString.href
        }
      ] : [],
      {
        name: "binding",
        text: binding
      }
    ]
  };
}
var kUnsafeEphemeralUniqueKey = /* @__PURE__ */ Symbol.for(
  "miniflare.kUnsafeEphemeralUniqueKey"
);

// src/plugins/shared/routing.ts
var import_node_url = require("node:url");
var RouterError = class extends MiniflareError {
};
function routeSpecificity(url38) {
  const hostParts = url38.host.split(".");
  let hostScore = hostParts.length;
  if (hostParts[0] === "*") hostScore -= 2;
  const pathParts = url38.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 url38 = new import_node_url.URL(urlInput);
      const specificity = routeSpecificity(url38);
      const protocol = hasProtocol ? url38.protocol : void 0;
      const internationalisedAllowHostnamePrefix = url38.hostname.startsWith("xn--*");
      const allowHostnamePrefix = url38.hostname.startsWith("*") || internationalisedAllowHostnamePrefix;
      const anyHostname = url38.hostname === "*";
      if (allowHostnamePrefix && !anyHostname) {
        let hostname = url38.hostname;
        if (internationalisedAllowHostnamePrefix) {
          hostname = (0, import_node_url.domainToUnicode)(hostname);
        }
        url38.hostname = hostname.substring(1);
      }
      const allowPathSuffix = url38.pathname.endsWith("*");
      if (allowPathSuffix) {
        url38.pathname = url38.pathname.substring(0, url38.pathname.length - 1);
      }
      if (url38.search) {
        throw new RouterError(
          "ERR_QUERY_STRING",
          `Route "${route}" for "${target}" contains a query string. This is not allowed.`
        );
      }
      if (url38.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 ? "" : url38.hostname,
        path: url38.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
var DEFAULT_PERSIST_ROOT = ".mf";
var PersistenceSchema = external_exports.union([external_exports.boolean(), external_exports.string().url(), PathSchema]).optional();
async function loadExternalPlugins(packageName) {
  let pluginModule;
  try {
    const pluginPath = require.resolve(packageName);
    const moduleURL = (0, import_node_url2.pathToFileURL)(pluginPath).href;
    pluginModule = await import(moduleURL);
  } catch (error) {
    throw new MiniflareCoreError(
      "ERR_PLUGIN_LOADING_FAILED",
      `Package ${packageName} could not be loaded. ${error}`
    );
  }
  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;
  }
};
function namespaceKeys(namespaces) {
  if (Array.isArray(namespaces)) {
    return namespaces;
  } else if (namespaces !== void 0) {
    return Object.keys(namespaces);
  } else {
    return [];
  }
}
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,
        {
          id: value.id,
          remoteProxyConnectionString: value.remoteProxyConnectionString
        }
      ];
    });
  } else {
    return [];
  }
}
function maybeParseURL(url38) {
  if (typeof url38 !== "string" || import_node_path6.default.isAbsolute(url38)) return;
  try {
    return new URL(url38);
  } catch {
  }
}
function getPersistPath(pluginName, tmpPath, defaultPersistRoot, persist) {
  const memoryishPath = import_node_path6.default.join(tmpPath, pluginName);
  let result;
  if (persist === false) {
    result = memoryishPath;
  } else if (persist === void 0) {
    result = defaultPersistRoot === void 0 ? memoryishPath : import_node_path6.default.join(defaultPersistRoot, pluginName);
  } else {
    const url38 = maybeParseURL(persist);
    if (url38 !== void 0) {
      if (url38.protocol === "memory:") {
        result = memoryishPath;
      } else if (url38.protocol === "file:") {
        result = (0, import_node_url2.fileURLToPath)(url38);
      } else {
        throw new MiniflareCoreError(
          "ERR_PERSIST_UNSUPPORTED",
          `Unsupported "${url38.protocol}" persistence protocol for storage: ${url38.href}`
        );
      }
    } else {
      result = persist === true ? import_node_path6.default.join(defaultPersistRoot ?? DEFAULT_PERSIST_ROOT, pluginName) : persist;
    }
  }
  return result.replaceAll("\\", "/");
}
function durableObjectNamespaceIdFromName(uniqueKey, name) {
  const key = import_node_crypto.default.createHash("sha256").update(uniqueKey).digest();
  const nameHmac = import_node_crypto.default.createHmac("sha256", key).update(name).digest().subarray(0, 16);
  const hmac = import_node_crypto.default.createHmac("sha256", key).update(nameHmac).digest().subarray(0, 16);
  return Buffer.concat([nameHmac, hmac]).toString("hex");
}
async function migrateDatabase(log2, uniqueKey, persistPath, namespace) {
  const sanitisedNamespace = sanitisePath(namespace);
  const previousDir = import_node_path6.default.join(persistPath, sanitisedNamespace);
  const previousPath = import_node_path6.default.join(previousDir, "db.sqlite");
  const previousWalPath = import_node_path6.default.join(previousDir, "db.sqlite-wal");
  if (!(0, import_node_fs4.existsSync)(previousPath)) return;
  const id = durableObjectNamespaceIdFromName(uniqueKey, namespace);
  const newDir = import_node_path6.default.join(persistPath, uniqueKey);
  const newPath = import_node_path6.default.join(newDir, `${id}.sqlite`);
  const newWalPath = import_node_path6.default.join(newDir, `${id}.sqlite-wal`);
  if ((0, import_node_fs4.existsSync)(newPath)) {
    log2.debug(
      `Not migrating ${previousPath} to ${newPath} as it already exists`
    );
    return;
  }
  log2.debug(`Migrating ${previousPath} to ${newPath}...`);
  await import_promises3.default.mkdir(newDir, { recursive: true });
  try {
    await import_promises3.default.copyFile(previousPath, newPath);
    if ((0, import_node_fs4.existsSync)(previousWalPath)) {
      await import_promises3.default.copyFile(previousWalPath, newWalPath);
    }
    await import_promises3.default.unlink(previousPath);
    await import_promises3.default.unlink(previousWalPath);
  } catch (e) {
    log2.warn(`Error migrating ${previousPath} to ${newPath}: ${e}`);
  }
}
function getRemoteServiceNameSuffix(remoteProxyConnectionString) {
  const remoteSha = (0, import_node_crypto.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/ai/index.ts
var AISchema = external_exports.object({
  binding: external_exports.string(),
  remoteProxyConnectionString: external_exports.custom().optional()
});
var AIOptionsSchema = external_exports.object({
  ai: AISchema.optional()
});
var AI_PLUGIN_NAME = "ai";
var AI_PLUGIN = {
  options: AIOptionsSchema,
  async getBindings(options) {
    if (!options.ai) {
      return [];
    }
    return [
      {
        name: options.ai.binding,
        wrapped: {
          moduleName: "cloudflare-internal:ai-api",
          innerBindings: [
            {
              name: "fetcher",
              service: {
                name: getUserBindingServiceName(
                  AI_PLUGIN_NAME,
                  options.ai.binding,
                  options.ai.remoteProxyConnectionString
                )
              }
            }
          ]
        }
      }
    ];
  },
  getNodeBindings(options) {
    if (!options.ai) {
      return {};
    }
    return {
      [options.ai.binding]: new ProxyNodeBinding()
    };
  },
  async getServices({ options }) {
    if (!options.ai) {
      return [];
    }
    return [
      {
        name: getUserBindingServiceName(
          AI_PLUGIN_NAME,
          options.ai.binding,
          options.ai.remoteProxyConnectionString
        ),
        worker: remoteProxyClientWorker(
          options.ai.remoteProxyConnectionString,
          options.ai.binding
        )
      }
    ];
  }
};

// src/plugins/ai-search/index.ts
var AISearchEntrySchema = external_exports.object({
  namespace: external_exports.string().optional(),
  instance_name: external_exports.string().optional(),
  remoteProxyConnectionString: external_exports.custom().optional()
});
var AISearchOptionsSchema = external_exports.object({
  aiSearchNamespaces: external_exports.record(AISearchEntrySchema).optional(),
  aiSearchInstances: external_exports.record(AISearchEntrySchema).optional()
});
var AI_SEARCH_PLUGIN_NAME = "ai-search";
var AI_SEARCH_NS_SCOPE = "ai-search-ns";
var AI_SEARCH_INST_SCOPE = "ai-search-inst";
var AI_SEARCH_PLUGIN = {
  options: AISearchOptionsSchema,
  async getBindings(options) {
    const bindings = [];
    for (const [bindingName, entry] of Object.entries(
      options.aiSearchNamespaces ?? {}
    )) {
      bindings.push({
        name: bindingName,
        service: {
          name: getUserBindingServiceName(
            AI_SEARCH_NS_SCOPE,
            bindingName,
            entry.remoteProxyConnectionString
          )
        }
      });
    }
    for (const [bindingName, entry] of Object.entries(
      options.aiSearchInstances ?? {}
    )) {
      bindings.push({
        name: bindingName,
        service: {
          name: getUserBindingServiceName(
            AI_SEARCH_INST_SCOPE,
            bindingName,
            entry.remoteProxyConnectionString
          )
        }
      });
    }
    return bindings;
  },
  getNodeBindings(options) {
    const nodeBindings = {};
    for (const bindingName of Object.keys(options.aiSearchNamespaces ?? {})) {
      nodeBindings[bindingName] = new ProxyNodeBinding();
    }
    for (const bindingName of Object.keys(options.aiSearchInstances ?? {})) {
      nodeBindings[bindingName] = new ProxyNodeBinding();
    }
    return nodeBindings;
  },
  async getServices({ options }) {
    const services = [];
    for (const [bindingName, entry] of Object.entries(
      options.aiSearchNamespaces ?? {}
    )) {
      services.push({
        name: getUserBindingServiceName(
          AI_SEARCH_NS_SCOPE,
          bindingName,
          entry.remoteProxyConnectionString
        ),
        worker: remoteProxyClientWorker(
          entry.remoteProxyConnectionString,
          bindingName
        )
      });
    }
    for (const [bindingName, entry] of Object.entries(
      options.aiSearchInstances ?? {}
    )) {
      services.push({
        name: getUserBindingServiceName(
          AI_SEARCH_INST_SCOPE,
          bindingName,
          entry.remoteProxyConnectionString
        ),
        worker: remoteProxyClientWorker(
          entry.remoteProxyConnectionString,
          bindingName
        )
      });
    }
    return services;
  }
};

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

// src/plugins/analytics-engine/index.ts
var AnalyticsEngineSchema = external_exports.record(
  external_exports.object({
    dataset: external_exports.string()
  })
);
var AnalyticsEngineSchemaOptionsSchema = external_exports.object({
  analyticsEngineDatasets: AnalyticsEngineSchema.optional()
});
var AnalyticsEngineSchemaSharedOptionsSchema = external_exports.object({
  analyticsEngineDatasetsPersist: PersistenceSchema
});
var ANALYTICS_ENGINE_PLUGIN_NAME = "analytics-engine";
var ANALYTICS_ENGINE_PLUGIN = {
  options: AnalyticsEngineSchemaOptionsSchema,
  sharedOptions: AnalyticsEngineSchemaSharedOptionsSchema,
  async getBindings(options) {
    if (!options.analyticsEngineDatasets) {
      return [];
    }
    const bindings = Object.entries(
      options.analyticsEngineDatasets
    ).map(([name, config]) => {
      return {
        name,
        wrapped: {
          moduleName: `${ANALYTICS_ENGINE_PLUGIN_NAME}:local-simulator`,
          innerBindings: [
            {
              name: "dataset",
              json: JSON.stringify(config.dataset)
            }
          ]
        }
      };
    });
    return bindings;
  },
  getNodeBindings(options) {
    if (!options.analyticsEngineDatasets) {
      return {};
    }
    return Object.fromEntries(
      Object.keys(options.analyticsEngineDatasets).map((name) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices() {
    return [];
  },
  getExtensions({ options }) {
    if (!options.some((o) => o.analyticsEngineDatasets)) {
      return [];
    }
    return [
      {
        modules: [
          {
            name: `${ANALYTICS_ENGINE_PLUGIN_NAME}:local-simulator`,
            esModule: analytics_engine_worker_default(),
            internal: true
          }
        ]
      }
    ];
  }
};

// src/plugins/assets/index.ts
var import_node_crypto4 = __toESM(require("node:crypto"));
var import_promises7 = __toESM(require("node:fs/promises"));
var import_node_path13 = __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_exports.object({
  account_id: external_exports.number().optional(),
  script_id: external_exports.number().optional(),
  debug: external_exports.boolean().optional()
});
var StaticRoutingSchema = external_exports.object({
  user_worker: external_exports.array(external_exports.string()),
  asset_worker: external_exports.array(external_exports.string()).optional()
});
var RouterConfigSchema = external_exports.object({
  invoke_user_worker_ahead_of_assets: external_exports.boolean().optional(),
  static_routing: StaticRoutingSchema.optional(),
  has_user_worker: external_exports.boolean().optional(),
  ...InternalConfigSchema.shape
});
var EyeballRouterConfigSchema = external_exports.union([
  external_exports.object({
    limitedAssetsOnly: external_exports.boolean().optional()
  }),
  external_exports.null()
]);
var MetadataStaticRedirectEntry = external_exports.object({
  status: external_exports.number(),
  to: external_exports.string(),
  lineNumber: external_exports.number()
});
var MetadataRedirectEntry = external_exports.object({
  status: external_exports.number(),
  to: external_exports.string()
});
var MetadataStaticRedirects = external_exports.record(MetadataStaticRedirectEntry);
var MetadataRedirects = external_exports.record(MetadataRedirectEntry);
var MetadataHeaderEntry = external_exports.object({
  set: external_exports.record(external_exports.string()).optional(),
  unset: external_exports.array(external_exports.string()).optional()
});
var MetadataHeaders = external_exports.record(MetadataHeaderEntry);
var RedirectsSchema = external_exports.object({
  version: external_exports.literal(1),
  staticRules: MetadataStaticRedirects,
  rules: MetadataRedirects
}).optional();
var HeadersSchema = external_exports.object({
  version: external_exports.literal(2),
  rules: MetadataHeaders
}).optional();
var AssetConfigSchema = external_exports.object({
  compatibility_date: external_exports.string().optional(),
  compatibility_flags: external_exports.array(external_exports.string()).optional(),
  html_handling: external_exports.enum([
    "auto-trailing-slash",
    "force-trailing-slash",
    "drop-trailing-slash",
    "none"
  ]).optional(),
  not_found_handling: external_exports.enum(["single-page-application", "404-page", "none"]).optional(),
  redirects: RedirectsSchema,
  headers: HeadersSchema,
  has_static_routing: external_exports.boolean().optional(),
  ...InternalConfigSchema.shape
});

// ../workers-shared/utils/helpers.ts
var import_node_fs5 = require("node:fs");
var import_node_path7 = 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(path62) {
    if (typeof path62 !== "string")
      return null;
    const last = path62.replace(/^.*[/\\]/s, "").toLowerCase();
    const ext = last.replace(/^.*\./s, "").toLowerCase();
    const hasPath = last.length < path62.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_path7.isAbsolute)(relativeFilepath)) {
    throw new Error(`Expected relative path`);
  }
  return "/" + relativeFilepath.split(import_node_path7.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_fs5.readFileSync)(filePath, "utf8");
  } catch (e) {
    if (!thrownIsDoesNotExistError(e)) {
      throw e;
    }
  }
}
async function createAssetsIgnoreFunction(dir) {
  const cfAssetIgnorePath = (0, import_node_path7.resolve)(dir, 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;

// ../workers-shared/utils/configuration/validateURL.ts
var extractPathname = (path62 = "/", includeSearch, includeHash) => {
  if (!path62.startsWith("/")) {
    path62 = `/${path62}`;
  }
  const url38 = new URL(`//${path62}`, "relative://");
  return `${url38.pathname}${includeSearch ? url38.search : ""}${includeHash ? url38.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 path62 = PATH_REGEX.exec(token);
    if (path62) {
      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;
  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)) {
      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 [path62, pathError] = validateUrl(line, false, true);
      if (pathError) {
        invalid.push({
          line,
          lineNumber: i + 1,
          message: pathError
        });
        rule = void 0;
        continue;
      }
      rule = {
        path: path62,
        line,
        headers: {},
        unsetHeaders: []
      };
      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;
}

// ../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_path8 = 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_path8.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_path8.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
    }
  };
}

// ../../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 = (number, locale, options) => {
  let result = number;
  if (typeof locale === "string" || Array.isArray(locale)) {
    result = number.toLocaleString(locale, options);
  } else if (locale === true || options !== void 0) {
    result = number.toLocaleString(void 0, options);
  }
  return result;
};
function prettyBytes(number, options) {
  if (!Number.isFinite(number)) {
    throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`);
  }
  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 && number === 0) {
    return ` 0${separator}${UNITS[0]}`;
  }
  const isNegative = number < 0;
  const prefix = isNegative ? "-" : options.signed ? "+" : "";
  if (isNegative) {
    number = -number;
  }
  let localeOptions;
  if (options.minimumFractionDigits !== void 0) {
    localeOptions = { minimumFractionDigits: options.minimumFractionDigits };
  }
  if (options.maximumFractionDigits !== void 0) {
    localeOptions = { maximumFractionDigits: options.maximumFractionDigits, ...localeOptions };
  }
  if (number < 1) {
    const numberString2 = toLocaleString(number, options.locale, localeOptions);
    return prefix + numberString2 + separator + UNITS[0];
  }
  const exponent = Math.min(Math.floor(options.binary ? Math.log(number) / Math.log(1024) : Math.log10(number) / 3), UNITS.length - 1);
  number /= (options.binary ? 1024 : 1e3) ** exponent;
  if (!localeOptions) {
    number = number.toPrecision(3);
  }
  const numberString = toLocaleString(Number(number), 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_fs6 = __toESM(require("fs"));
var import_path6 = __toESM(require("path"));
var import_url6 = __toESM(require("url"));
var contents6;
function assets_worker_default() {
  if (contents6 !== void 0) return contents6;
  const filePath = import_path6.default.join(__dirname, "workers", "assets/assets.worker.js");
  contents6 = import_fs6.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url6.default.pathToFileURL(filePath);
  return contents6;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/assets/assets-kv.worker.ts
var import_fs7 = __toESM(require("fs"));
var import_path7 = __toESM(require("path"));
var import_url7 = __toESM(require("url"));
var contents7;
function assets_kv_worker_default() {
  if (contents7 !== void 0) return contents7;
  const filePath = import_path7.default.join(__dirname, "workers", "assets/assets-kv.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/router.worker.ts
var import_fs8 = __toESM(require("fs"));
var import_path8 = __toESM(require("path"));
var import_url8 = __toESM(require("url"));
var contents8;
function router_worker_default() {
  if (contents8 !== void 0) return contents8;
  const filePath = import_path8.default.join(__dirname, "workers", "assets/router.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/rpc-proxy.worker.ts
var import_fs9 = __toESM(require("fs"));
var import_path9 = __toESM(require("path"));
var import_url9 = __toESM(require("url"));
var contents9;
function rpc_proxy_worker_default() {
  if (contents9 !== void 0) return contents9;
  const filePath = import_path9.default.join(__dirname, "workers", "assets/rpc-proxy.worker.js");
  contents9 = import_fs9.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url9.default.pathToFileURL(filePath);
  return contents9;
}

// src/plugins/core/index.ts
var import_node_assert16 = __toESM(require("node:assert"));
var import_node_fs9 = require("node:fs");
var import_promises6 = __toESM(require("node:fs/promises"));
var import_node_path12 = __toESM(require("node:path"));
var import_node_stream2 = require("node:stream");
var import_node_tls = __toESM(require("node:tls"));
var import_node_util4 = 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 error;
  ((error2) => {
    error2["VALIDATE_INPUT"] = "VALIDATE_INPUT";
  })(error = 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 error;
  ((error2) => {
    error2["DEPLOYMENT_NOT_FOUND"] = "DEPLOYMENT_NOT_FOUND";
  })(error = DeploymentNotFoundError2.error || (DeploymentNotFoundError2.error = {}));
})(DeploymentNotFoundError || (DeploymentNotFoundError = {}));

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

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

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

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

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

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

// ../containers-shared/src/client/models/ImageRegistryProtocolNotFound.ts
var ImageRegistryProtocolNotFound;
((ImageRegistryProtocolNotFound2) => {
  let error;
  ((error2) => {
    error2["IMAGE_REGISTRY_PROTOCOL_NOT_FOUND"] = "IMAGE_REGISTRY_PROTOCOL_NOT_FOUND";
  })(error = 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 error;
  ((error2) => {
    error2["SECRET_NAME_ALREADY_EXISTS"] = "SECRET_NAME_ALREADY_EXISTS";
  })(error = SecretNameAlreadyExists2.error || (SecretNameAlreadyExists2.error = {}));
})(SecretNameAlreadyExists || (SecretNameAlreadyExists = {}));

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

// ../containers-shared/src/client/models/SSHPublicKeyNotFoundError.ts
var SSHPublicKeyNotFoundError;
((SSHPublicKeyNotFoundError2) => {
  let error;
  ((error2) => {
    error2["SSH_PUBLIC_KEY_NOT_FOUND"] = "SSH_PUBLIC_KEY_NOT_FOUND";
  })(error = 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";

// src/plugins/core/index.ts
var import_undici7 = require("undici");

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

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

// src/runtime/index.ts
var import_node_assert9 = __toESM(require("node:assert"));
var import_node_child_process = __toESM(require("node:child_process"));
var import_node_crypto2 = require("node:crypto");
var import_node_events2 = require("node:events");
var import_node_path9 = __toESM(require("node:path"));
var import_node_readline = __toESM(require("node:readline"));
var import_node_stream = require("node:stream");
var import_workerd4 = __toESM(require("workerd"));

// src/runtime/structured-logs.ts
function handleStructuredLogsFromStream(stream, structuredLogsHandler) {
  let streamAccumulator = "";
  stream.on("data", (chunk) => {
    const fullStreamOutput = `${streamAccumulator}${chunk}`;
    let currentLogsStr = "";
    const lastNewlineIdx = fullStreamOutput.lastIndexOf("\n");
    const adjustedStructuredLogsHandler = wrapStructuredLogsHandler(
      structuredLogsHandler
    );
    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 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) {
  return (structuredLog) => {
    if (messageClassifiers.isInternal(structuredLog.message)) {
      if (messageClassifiers.isAddressInUse(structuredLog.message)) {
        return;
      }
      if (messageClassifiers.isAccessViolation(structuredLog.message)) {
        let error = "There was an access violation in the runtime.";
        if (process.platform === "win32") {
          error += "\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: error
        });
      }
      return;
    }
    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_fs6 = require("node:fs");

// ../../node_modules/.pnpm/capnp-es@0.0.14_typescript@5.8.3/node_modules/capnp-es/dist/shared/capnp-es.DtDJWfSS.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 assertNever2(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 h2 = [];
  for (let i = 0; i < a.byteLength; i++) {
    h2.push(pad(a[i].toString(16), 2));
  }
  return `[${h2.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 r2 = format3("\n=== buffer[%d] ===", byteLength);
  for (let j = 0; j < byteLength; j += 16) {
    r2 += `
${pad(j.toString(16), 8)}: `;
    let s = "";
    let k;
    for (k = 0; k < 16 && j + k < b.byteLength; k++) {
      const v2 = b[j + k];
      r2 += `${pad(v2.toString(16), 2)} `;
      s += v2 > 31 && v2 < 255 ? String.fromCharCode(v2) : "\xB7";
      if (k === 7) {
        r2 += " ";
      }
    }
    r2 += `${" ".repeat((17 - k) * 3)}${s}`;
  }
  r2 += "\n";
  if (byteLength !== b.byteLength) {
    r2 += format3("=== (truncated %d bytes) ===\n", b.byteLength - byteLength);
  }
  return r2;
}
function format3(s, ...args) {
  const n = s.length;
  let arg;
  let argIndex = 0;
  let c;
  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++];
      c = s[i];
    }
    return digits.length > 0 ? Number.parseInt(digits, 10) : null;
  }
  for (; i < n; ++i) {
    c = s[i];
    if (escaped) {
      escaped = false;
      if (c === ".") {
        leadingZero = false;
        c = s[++i];
      } else if (c === "0" && s[i + 1] === ".") {
        leadingZero = true;
        i += 2;
        c = s[i];
      } else {
        leadingZero = true;
      }
      precision = slurpNumber();
      switch (c) {
        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 += c;
          break;
        }
      }
    } else if (c === "%") {
      escaped = true;
    } else {
      result += c;
    }
  }
  return result;
}
function pad(v2, width, pad2 = "0") {
  return v2.length >= width ? v2 : Array.from({ length: width - v2.length + 1 }).join(pad2) + v2;
}
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 format3(
      "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 c = getContent(src);
    this.segment = c.segment;
    this.byteOffset = c.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(format3(PTR_ALREADY_ADOPTED, this));
    }
    if (this.segment.message !== dst.segment.message) {
      throw new Error(format3(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 format3(
      "Orphan_%d@%a,type:%s",
      this.segment.id,
      this.byteOffset,
      this._capnp && this._capnp.type
    );
  }
};
function adopt(src, p) {
  src._moveTo(p);
}
function disown(p) {
  return new Orphan(p);
}
function dump(p) {
  return bufferToHex(p.segment.buffer.slice(p.byteOffset, p.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(format3(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(format3(PTR_INVALID_LIST_SIZE, elementSize));
    }
  }
}
function add(offset2, p) {
  return new Pointer(p.segment, p.byteOffset + offset2, p._capnp.depthLimit);
}
function copyFrom(src, p) {
  if (p.segment === src.segment && p.byteOffset === src.byteOffset) {
    return;
  }
  erase(p);
  if (isNull(src)) return;
  switch (getTargetPointerType(src)) {
    case PointerType.STRUCT: {
      copyFromStruct(src, p);
      break;
    }
    case PointerType.LIST: {
      copyFromList(src, p);
      break;
    }
    case PointerType.OTHER: {
      copyFromInterface(src, p);
      break;
    }
    /* istanbul ignore next */
    default: {
      throw new Error(
        format3(PTR_INVALID_POINTER_TYPE, getTargetPointerType(p))
      );
    }
  }
}
function erase(p) {
  if (isNull(p)) return;
  let c;
  switch (getTargetPointerType(p)) {
    case PointerType.STRUCT: {
      const size = getTargetStructSize(p);
      c = getContent(p);
      c.segment.fillZeroWords(c.byteOffset, size.dataByteLength / 8);
      for (let i = 0; i < size.pointerLength; i++) {
        erase(add(i * 8, c));
      }
      break;
    }
    case PointerType.LIST: {
      const elementSize = getTargetListElementSize(p);
      const length = getTargetListLength(p);
      let contentWords = padToWord$1(
        length * getListElementByteLength(elementSize)
      );
      c = getContent(p);
      if (elementSize === ListElementSize.POINTER) {
        for (let i = 0; i < length; i++) {
          erase(
            new Pointer(
              c.segment,
              c.byteOffset + i * 8,
              p._capnp.depthLimit - 1
            )
          );
        }
        break;
      } else if (elementSize === ListElementSize.COMPOSITE) {
        const tag = add(-8, c);
        const compositeSize = getStructSize(tag);
        const compositeByteLength = getByteLength(compositeSize);
        contentWords = getOffsetWords(tag);
        c.segment.setWordZero(c.byteOffset - 8);
        for (let i = 0; i < length; i++) {
          for (let j = 0; j < compositeSize.pointerLength; j++) {
            erase(
              new Pointer(
                c.segment,
                c.byteOffset + i * compositeByteLength + j * 8,
                p._capnp.depthLimit - 1
              )
            );
          }
        }
      }
      c.segment.fillZeroWords(c.byteOffset, contentWords);
      break;
    }
    case PointerType.OTHER: {
      break;
    }
    default: {
      throw new Error(
        format3(PTR_INVALID_POINTER_TYPE, getTargetPointerType(p))
      );
    }
  }
  erasePointer(p);
}
function erasePointer(p) {
  if (getPointerType(p) === PointerType.FAR) {
    const landingPad = followFar(p);
    if (isDoubleFar(p)) {
      landingPad.segment.setWordZero(landingPad.byteOffset + 8);
    }
    landingPad.segment.setWordZero(landingPad.byteOffset);
  }
  p.segment.setWordZero(p.byteOffset);
}
function followFar(p) {
  const targetSegment = p.segment.message.getSegment(
    p.segment.getUint32(p.byteOffset + 4)
  );
  const targetWordOffset = p.segment.getUint32(p.byteOffset) >>> 3;
  return new Pointer(
    targetSegment,
    targetWordOffset * 8,
    p._capnp.depthLimit - 1
  );
}
function followFars(p) {
  if (getPointerType(p) === PointerType.FAR) {
    const landingPad = followFar(p);
    if (isDoubleFar(p)) {
      landingPad.byteOffset += 8;
    }
    return landingPad;
  }
  return p;
}
function getCapabilityId(p) {
  return p.segment.getUint32(p.byteOffset + 4);
}
function isCompositeList(p) {
  return getTargetPointerType(p) === PointerType.LIST && getTargetListElementSize(p) === ListElementSize.COMPOSITE;
}
function getContent(p, ignoreCompositeIndex) {
  let c;
  if (isDoubleFar(p)) {
    const landingPad = followFar(p);
    c = new Pointer(
      p.segment.message.getSegment(getFarSegmentId(landingPad)),
      getOffsetWords(landingPad) * 8
    );
  } else {
    const target = followFars(p);
    c = new Pointer(
      target.segment,
      target.byteOffset + 8 + getOffsetWords(target) * 8
    );
  }
  if (isCompositeList(p)) {
    c.byteOffset += 8;
  }
  if (!ignoreCompositeIndex && p._capnp.compositeIndex !== void 0) {
    c.byteOffset -= 8;
    c.byteOffset += 8 + p._capnp.compositeIndex * getByteLength(padToWord(getStructSize(c)));
  }
  return c;
}
function getFarSegmentId(p) {
  return p.segment.getUint32(p.byteOffset + 4);
}
function getListElementSize(p) {
  return p.segment.getUint32(p.byteOffset + 4) & LIST_SIZE_MASK;
}
function getListLength(p) {
  return p.segment.getUint32(p.byteOffset + 4) >>> 3;
}
function getOffsetWords(p) {
  const o = p.segment.getInt32(p.byteOffset);
  return o & 2 ? o >> 3 : o >> 2;
}
function getPointerType(p) {
  return p.segment.getUint32(p.byteOffset) & POINTER_TYPE_MASK;
}
function getStructDataWords(p) {
  return p.segment.getUint16(p.byteOffset + 4);
}
function getStructPointerLength(p) {
  return p.segment.getUint16(p.byteOffset + 6);
}
function getStructSize(p) {
  return new ObjectSize(getStructDataWords(p) * 8, getStructPointerLength(p));
}
function getTargetCompositeListTag(p) {
  const c = getContent(p);
  c.byteOffset -= 8;
  return c;
}
function getTargetCompositeListSize(p) {
  return getStructSize(getTargetCompositeListTag(p));
}
function getTargetListElementSize(p) {
  return getListElementSize(followFars(p));
}
function getTargetListLength(p) {
  const t = followFars(p);
  if (getListElementSize(t) === ListElementSize.COMPOSITE) {
    return getOffsetWords(getTargetCompositeListTag(p));
  }
  return getListLength(t);
}
function getTargetPointerType(p) {
  const t = getPointerType(followFars(p));
  if (t === PointerType.FAR) {
    throw new Error(format3(PTR_INVALID_FAR_TARGET, p));
  }
  return t;
}
function getTargetStructSize(p) {
  return getStructSize(followFars(p));
}
function initPointer(contentSegment, contentOffset, p) {
  if (p.segment !== contentSegment) {
    if (!contentSegment.hasCapacity(8)) {
      const landingPad2 = p.segment.allocate(16);
      setFarPointer(true, landingPad2.byteOffset / 8, landingPad2.segment.id, p);
      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, p);
    return new PointerAllocationResult(
      landingPad,
      (contentOffset - landingPad.byteOffset - 8) / 8
    );
  }
  return new PointerAllocationResult(p, (contentOffset - p.byteOffset - 8) / 8);
}
function isDoubleFar(p) {
  return getPointerType(p) === PointerType.FAR && (p.segment.getUint32(p.byteOffset) & POINTER_DOUBLE_FAR_MASK) !== 0;
}
function isNull(p) {
  return p.segment.isWordZero(p.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, p) {
  const A = PointerType.FAR;
  const B = doubleFar ? 1 : 0;
  const C = offsetWords;
  const D = segmentId;
  p.segment.setUint32(p.byteOffset, A | B << 2 | C << 3);
  p.segment.setUint32(p.byteOffset + 4, D);
}
function setInterfacePointer(capId, p) {
  p.segment.setUint32(p.byteOffset, PointerType.OTHER);
  p.segment.setUint32(p.byteOffset + 4, capId);
}
function getInterfacePointer(p) {
  return p.segment.getUint32(p.byteOffset + 4);
}
function setListPointer(offsetWords, size, length, p, 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);
  }
  p.segment.setUint32(p.byteOffset, A | B << 2);
  p.segment.setUint32(p.byteOffset + 4, C | D << 3);
}
function setStructPointer(offsetWords, size, p) {
  const A = PointerType.STRUCT;
  const B = offsetWords;
  const C = getDataWordLength(size);
  const D = size.pointerLength;
  p.segment.setUint32(p.byteOffset, A | B << 2);
  p.segment.setUint16(p.byteOffset + 4, C);
  p.segment.setUint16(p.byteOffset + 6, D);
}
function validate(pointerType, p, elementSize) {
  if (isNull(p)) {
    return;
  }
  const t = followFars(p);
  const A = t.segment.getUint32(t.byteOffset) & POINTER_TYPE_MASK;
  if (A !== pointerType) {
    throw new Error(format3(PTR_WRONG_POINTER_TYPE, p, pointerType));
  }
  if (elementSize !== void 0) {
    const C = t.segment.getUint32(t.byteOffset + 4) & LIST_SIZE_MASK;
    if (C !== elementSize) {
      throw new Error(
        format3(PTR_WRONG_LIST_TYPE, p, 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 offset2 = i * srcStructByteLength + srcCompositeSize.dataByteLength + (j << 3);
        const srcPtr = new Pointer(
          srcContent.segment,
          srcContent.byteOffset + offset2,
          src._capnp.depthLimit - 1
        );
        const dstPtr = new Pointer(
          dstContent.segment,
          dstContent.byteOffset + offset2 + 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 offset2 = srcSize.dataByteLength + i * 8;
    const srcPtr = new Pointer(
      srcContent.segment,
      srcContent.byteOffset + offset2,
      src._capnp.depthLimit - 1
    );
    const dstPtr = new Pointer(
      dstContent.segment,
      dstContent.byteOffset + offset2,
      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, p) {
  message._capnp.traversalLimit -= 8;
  if (message._capnp.traversalLimit <= 0) {
    throw new Error(format3(PTR_TRAVERSAL_LIMIT_EXCEEDED, p));
  }
}
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(format3(PTR_DEPTH_LIMIT_EXCEEDED, this));
    }
    trackPointerAllocation(segment.message, this);
    if (byteOffset < 0 || byteOffset > segment.byteLength) {
      throw new Error(format3(PTR_OFFSET_OUT_OF_BOUNDS, byteOffset));
    }
  }
  [Symbol.toStringTag]() {
    return format3("Pointer_%d", this.segment.id);
  }
  toString() {
    return format3("->%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 r2 = cb.call(_this, this.at(i), i, this);
      res.push(...Array.isArray(r2) ? r2 : [r2]);
    }
    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 }, (_2, 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 c;
  switch (elementSize) {
    case ListElementSize.BIT: {
      c = 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: {
      c = list.segment.allocate(length * getListElementByteLength(elementSize));
      break;
    }
    case ListElementSize.COMPOSITE: {
      if (compositeSize === void 0) {
        throw new Error(format3(PTR_COMPOSITE_SIZE_UNDEFINED));
      }
      compositeSize = padToWord(compositeSize);
      const byteLength = getByteLength(compositeSize) * length;
      c = list.segment.allocate(byteLength + 8);
      setStructPointer(length, compositeSize, c);
      break;
    }
    case ListElementSize.VOID: {
      setListPointer(0, elementSize, length, list);
      return;
    }
    default: {
      throw new Error(format3(PTR_INVALID_LIST_SIZE, elementSize));
    }
  }
  const res = initPointer(c.segment, c.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 c = 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(c.segment.buffer, c.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 c = getContent(this);
    return c.segment.getUint8(c.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 c = getContent(this);
    c.segment.setUint8(c.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 c = getContent(this);
    return c.segment.buffer.slice(c.byteOffset, c.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 c = getContent(this);
    return new DataView(c.segment.buffer, c.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 c = getContent(this);
    return new Uint8Array(c.segment.buffer, c.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 c = getContent(this);
    return textDecoder.decode(
      new Uint8Array(
        c.segment.buffer,
        c.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 c;
    let original;
    if (!isNull(this)) {
      c = getContent(this);
      const originalLength = Math.min(this.length, index);
      original = new Uint8Array(
        c.segment.buffer.slice(c.byteOffset, c.byteOffset + originalLength)
      );
      erase(this);
    }
    initList$1(ListElementSize.BYTE, dstLength + 1, this);
    c = getContent(this);
    const dst = new Uint8Array(c.segment.buffer, c.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(_transform, _call) {
    return this;
  }
  pipelineClose(_transform) {
    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(format3(PTR_INIT_COMPOSITE_STRUCT, s));
  }
  erase(s);
  const c = s.segment.allocate(getByteLength(size));
  const res = initPointer(c.segment, c.byteOffset, s);
  setStructPointer(res.offsetWords, size, res.pointer);
}
function initStructAt(index, StructClass, p) {
  const s = getPointerAs(index, StructClass, p);
  initStruct(StructClass._capnp.size, s);
  return s;
}
function checkPointerBounds(index, s) {
  const { pointerLength } = getSize(s);
  if (index < 0 || index >= pointerLength) {
    throw new Error(
      format3(PTR_STRUCT_POINTER_OUT_OF_BOUNDS, s, index, pointerLength)
    );
  }
}
function getInterfaceClientOrNullAt(index, s) {
  return getInterfaceClientOrNull(getPointer(index, s));
}
function getInterfaceClientOrNull(p) {
  let client = null;
  const capId = getInterfacePointer(p);
  const { capTable } = p.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 r2 = initPointer(
      srcPtrContent.segment,
      srcPtrContent.byteOffset,
      dstPtr
    );
    const a = srcPtrTarget.segment.getUint8(srcPtrTarget.byteOffset) & 3;
    const b = srcPtrTarget.segment.getUint32(srcPtrTarget.byteOffset + 4);
    r2.pointer.segment.setUint32(r2.pointer.byteOffset, a | r2.offsetWords << 2);
    r2.pointer.segment.setUint32(r2.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 v2 = ds.segment.getUint8(ds.byteOffset + byteOffset);
  if (defaultMask === void 0) {
    return (v2 & bitMask) !== 0;
  }
  const defaultValue = defaultMask.getUint8(0);
  return ((v2 ^ 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 v2 = ds.segment.getUint32(ds.byteOffset + byteOffset) ^ defaultMask.getUint32(0, true);
  TMP_WORD.setUint32(0, v2, 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 v2 = ds.segment.getUint16(ds.byteOffset + byteOffset) ^ defaultMask.getUint16(0, true);
  TMP_WORD.setUint16(0, v2, 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 v2 = ds.segment.getUint32(ds.byteOffset + byteOffset) ^ defaultMask.getUint16(0, true);
  TMP_WORD.setUint32(0, v2, 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 v2 = ds.segment.getUint8(ds.byteOffset + byteOffset) ^ defaultMask.getUint8(0);
  TMP_WORD.setUint8(0, v2);
  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 r2 = initPointer(
            srcPtrContent.segment,
            srcPtrContent.byteOffset,
            dstPtr
          );
          const a = srcPtrTarget.segment.getUint8(srcPtrTarget.byteOffset) & 3;
          const b = srcPtrTarget.segment.getUint32(srcPtrTarget.byteOffset + 4);
          r2.pointer.segment.setUint32(
            r2.pointer.byteOffset,
            a | r2.offsetWords << 2
          );
          r2.pointer.segment.setUint32(r2.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 c = getContent(s, true);
    c.byteOffset -= 8;
    return getStructSize(c);
  }
  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 v2 = TMP_WORD.getUint32(0, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint32(0, true);
    ds.segment.setUint32(ds.byteOffset + byteOffset, v2);
    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 v2 = TMP_WORD.getUint16(0, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint16(0, true);
    ds.segment.setUint16(ds.byteOffset + byteOffset, v2);
    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 v2 = TMP_WORD.getUint32(0, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint32(0, true);
    ds.segment.setUint32(ds.byteOffset + byteOffset, v2);
    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 v2 = TMP_WORD.getUint8(0) ^ defaultMask.getUint8(0);
    ds.segment.setUint8(ds.byteOffset + byteOffset, v2);
    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(format3(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(
      format3(
        PTR_STRUCT_DATA_OUT_OF_BOUNDS,
        s,
        byteLength,
        byteOffset,
        dataByteLength
      )
    );
  }
}

// ../../node_modules/.pnpm/capnp-es@0.0.14_typescript@5.8.3/node_modules/capnp-es/dist/shared/capnp-es.Cbyn5538.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(format3(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 format3("MultiSegmentArena_segments:%d", getNumSegments$2(this));
  }
};
function allocate$2(minSize, m2) {
  const b = new ArrayBuffer(padToWord$1(Math.max(minSize, DEFAULT_BUFFER_SIZE)));
  m2.buffers.push(b);
  return new ArenaAllocationResult(m2.buffers.length - 1, b);
}
function getBuffer$2(id, m2) {
  if (id < 0 || id >= m2.buffers.length) {
    throw new Error(format3(SEG_ID_OUT_OF_BOUNDS, id));
  }
  return m2.buffers[id];
}
function getNumSegments$2(m2) {
  return m2.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(format3(SEG_NOT_WORD_ALIGNED, buffer.byteLength));
    }
    this.buffer = buffer;
  }
  toString() {
    return format3("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(format3(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 assertNever2(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 assertNever2(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 assertNever2(a);
    }
  }
}
function getNumSegments(a) {
  switch (a.kind) {
    case ArenaKind.MULTI_SEGMENT: {
      return MultiSegmentArena.getNumSegments(a);
    }
    case ArenaKind.SINGLE_SEGMENT: {
      return SingleSegmentArena.getNumSegments();
    }
    default: {
      return assertNever2(a);
    }
  }
}
function getHammingWeight(x2) {
  let w2 = x2 - (x2 >> 1 & 1431655765);
  w2 = (w2 & 858993459) + (w2 >> 2 & 858993459);
  return (w2 + (w2 >> 4) & 252645135) * 16843009 >> 24;
}
function getTagByte(a, b, c, d2, e, f, g, h2) {
  return (a === 0 ? 0 : 1) | (b === 0 ? 0 : 2) | (c === 0 ? 0 : 4) | (d2 === 0 ? 0 : 8) | (e === 0 ? 0 : 16) | (f === 0 ? 0 : 32) | (g === 0 ? 0 : 64) | (h2 === 0 ? 0 : 128);
}
function getUnpackedByteLength(packed) {
  const p = new Uint8Array(packed);
  let wordCount = 0;
  let lastTag = 119;
  for (let i = 0; i < p.byteLength; ) {
    const tag = p[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, c, d2, e, f, g, h2) {
  return (a === 0 ? 1 : 0) + (b === 0 ? 1 : 0) + (c === 0 ? 1 : 0) + (d2 === 0 ? 1 : 0) + (e === 0 ? 1 : 0) + (f === 0 ? 1 : 0) + (g === 0 ? 1 : 0) + (h2 === 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 c = src[srcByteOffset + 2];
    const d2 = src[srcByteOffset + 3];
    const e = src[srcByteOffset + 4];
    const f = src[srcByteOffset + 5];
    const g = src[srcByteOffset + 6];
    const h2 = src[srcByteOffset + 7];
    const tag = getTagByte(a, b, c, d2, e, f, g, h2);
    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, c, d2, e, f, g, h2);
        if (zeroCount >= PACK_SPAN_THRESHOLD || rangeWordCount >= 255) {
          dst[spanWordCountOffset] = rangeWordCount;
          rangeWordCount = 0;
          skipWriteWord = false;
        } else {
          dst.push(a, b, c, d2, e, f, g, h2);
          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 (c !== 0) dst.push(c);
    if (d2 !== 0) dst.push(d2);
    if (e !== 0) dst.push(e);
    if (f !== 0) dst.push(f);
    if (g !== 0) dst.push(g);
    if (h2 !== 0) dst.push(h2);
    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(format3(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 format3(
      "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(m2) {
  const numSegments = Arena.getNumSegments(m2._capnp.arena);
  m2._capnp.segments = Array.from({ length: numSegments });
  for (let i = 0; i < numSegments; i++) {
    if (i === 0 && Arena.getBuffer(i, m2._capnp.arena).byteLength < 8) {
      throw new Error(MSG_SEGMENT_TOO_SMALL);
    }
    const buffer = Arena.getBuffer(i, m2._capnp.arena);
    const segment = new Segment(i, m2, buffer, buffer.byteLength);
    m2._capnp.segments[i] = segment;
  }
}
function isArrayBufferView(src) {
  return src.byteOffset !== void 0;
}
function isAnyArena(o) {
  return o.kind !== void 0;
}
function allocateSegment(byteLength, m2) {
  const res = Arena.allocate(byteLength, m2._capnp.segments, m2._capnp.arena);
  let s;
  if (res.id === m2._capnp.segments.length) {
    s = new Segment(res.id, m2, res.buffer);
    m2._capnp.segments.push(s);
  } else if (res.id < 0 || res.id > m2._capnp.segments.length) {
    throw new Error(format3(MSG_SEGMENT_OUT_OF_BOUNDS, res.id, m2));
  } else {
    s = m2._capnp.segments[res.id];
    s.replaceBuffer(res.buffer);
  }
  return s;
}
function dump2(m2) {
  let r2 = "";
  if (m2._capnp.segments.length === 0) {
    return "================\nNo Segments\n================\n";
  }
  for (let i = 0; i < m2._capnp.segments.length; i++) {
    r2 += `================
Segment #${i}
================
`;
    const { buffer, byteLength } = m2._capnp.segments[i];
    const b = new Uint8Array(buffer, 0, byteLength);
    r2 += dumpBuffer(b);
  }
  return r2;
}
function getRoot(RootStruct, m2) {
  const root = new RootStruct(m2.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, m2) {
  const segmentLength = m2._capnp.segments.length;
  if (id === 0 && segmentLength === 0) {
    const arenaSegments = Arena.getNumSegments(m2._capnp.arena);
    if (arenaSegments === 0) {
      allocateSegment(DEFAULT_BUFFER_SIZE, m2);
    } else {
      m2._capnp.segments[0] = new Segment(
        0,
        m2,
        Arena.getBuffer(0, m2._capnp.arena)
      );
    }
    if (!m2._capnp.segments[0].hasCapacity(8)) {
      throw new Error(MSG_SEGMENT_TOO_SMALL);
    }
    m2._capnp.segments[0].allocate(8);
    return m2._capnp.segments[0];
  }
  if (id < 0 || id >= segmentLength) {
    throw new Error(format3(MSG_SEGMENT_OUT_OF_BOUNDS, id, m2));
  }
  return m2._capnp.segments[id];
}
function initRoot(RootStruct, m2) {
  const root = new RootStruct(m2.getSegment(0), 0);
  initStruct(RootStruct._capnp.size, root);
  return root;
}
function readRawPointer(data2) {
  return new Pointer(new Message(data2).getSegment(0), 0);
}
function setRoot(src, m2) {
  copyFrom(src, new Pointer(m2.getSegment(0), 0));
}
function toArrayBuffer(m2) {
  const streamFrame = getStreamFrame(m2);
  if (m2._capnp.segments.length === 0) {
    getSegment(0, m2);
  }
  const { segments } = m2._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(m2) {
  const streamFrame = pack(getStreamFrame(m2));
  if (m2._capnp.segments.length === 0) {
    m2.getSegment(0);
  }
  const segments = m2._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(m2) {
  const { length } = m2._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 m2._capnp.segments.entries()) {
    out.setUint32(i * 4 + 4, s.byteLength / 8, true);
  }
  return out.buffer;
}
function copy(m2) {
  return new Message(Arena.copy(m2._capnp.arena));
}

// ../../node_modules/.pnpm/capnp-es@0.0.14_typescript@5.8.3/node_modules/capnp-es/dist/shared/capnp-es.B-d--Ayq.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 (x2) => {
    const dv = new DataView(new ArrayBuffer(byteLength));
    setter.call(dv, 0, x2, 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.14_typescript@5.8.3/node_modules/capnp-es/dist/shared/capnp-es.BDJXoNr3.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(p) {
    return getAsInterface(p);
  }
  getCapId() {
    return getCapID(this);
  }
  getClient() {
    return getClient(this);
  }
  [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
    return format3(
      "Interface_%d@%a,%d,limit:%x",
      this.segment.id,
      this.byteOffset,
      this.getCapId(),
      this._capnp.depthLimit
    );
  }
};
function getAsInterface(p) {
  if (getTargetPointerType(p) === PointerType.OTHER) {
    return new Interface(p.segment, p.byteOffset, p._capnp.depthLimit);
  }
  return null;
}
function isInterface(p) {
  return getTargetPointerType(p) === 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.14_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 c = getContent(this);
      return new PointerClass(
        c.segment,
        c.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 c = getContent(this);
    const v2 = c.segment.getUint8(c.byteOffset + byteOffset);
    return (v2 & bitMask) !== 0;
  }
  set(index, value) {
    const bitMask = 1 << index % 8;
    const c = getContent(this);
    const byteOffset = c.byteOffset + (index >>> 3);
    const v2 = c.segment.getUint8(byteOffset);
    c.segment.setUint8(byteOffset, value ? v2 | bitMask : v2 & ~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 c = getContent(this);
    return c.segment.getFloat32(c.byteOffset + index * 4);
  }
  set(index, value) {
    const c = getContent(this);
    c.segment.setFloat32(c.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 c = getContent(this);
    return c.segment.getFloat64(c.byteOffset + index * 8);
  }
  set(index, value) {
    const c = getContent(this);
    c.segment.setFloat64(c.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 c = getContent(this);
    return c.segment.getInt8(c.byteOffset + index);
  }
  set(index, value) {
    const c = getContent(this);
    c.segment.setInt8(c.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 c = getContent(this);
    return c.segment.getInt16(c.byteOffset + index * 2);
  }
  set(index, value) {
    const c = getContent(this);
    c.segment.setInt16(c.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 c = getContent(this);
    return c.segment.getInt32(c.byteOffset + index * 4);
  }
  set(index, value) {
    const c = getContent(this);
    c.segment.setInt32(c.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 c = getContent(this);
    return c.segment.getInt64(c.byteOffset + index * 8);
  }
  set(index, value) {
    const c = getContent(this);
    c.segment.setInt64(c.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 c = getContent(this);
    c.byteOffset += index * 8;
    return Text.fromPointer(c).get(0);
  }
  set(index, value) {
    const c = getContent(this);
    c.byteOffset += index * 8;
    Text.fromPointer(c).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 c = getContent(this);
    return c.segment.getUint8(c.byteOffset + index);
  }
  set(index, value) {
    const c = getContent(this);
    c.segment.setUint8(c.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 c = getContent(this);
    return c.segment.getUint16(c.byteOffset + index * 2);
  }
  set(index, value) {
    const c = getContent(this);
    c.segment.setUint16(c.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 c = getContent(this);
    return c.segment.getUint32(c.byteOffset + index * 4);
  }
  set(index, value) {
    const c = getContent(this);
    c.segment.setUint32(c.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 c = getContent(this);
    return c.segment.getUint64(c.byteOffset + index * 8);
  }
  set(index, value) {
    const c = getContent(this);
    c.segment.setUint64(c.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_Which = {
  /**
   * 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>`.
   *
   */
  HTTP: 0,
  /**
   * 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().)
   *
   */
  HTTPS: 1
};
var Socket = class extends Struct {
  static HTTP = Socket_Which.HTTP;
  static HTTPS = Socket_Which.HTTPS;
  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(_2) {
    utils.setUint16(0, 1, 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 = {
  /**
   * 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.
   *
   */
  UNSPECIFIED: 0,
  /**
   * (This catches when someone forgets to specify one of the union members. Do not set this.)
   *
   */
  WORKER: 1,
  /**
   * A Worker!
   *
   */
  NETWORK: 2,
  /**
   * A service that implements access to a network. fetch() requests are routed according to
   * the URL hostname.
   *
   */
  EXTERNAL: 3,
  /**
   * A service that forwards all requests to a specific remote server. Typically used to
   * connect to a back-end server on your internal network.
   *
   */
  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(_2) {
    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(_2) {
    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 = {
  /**
   * Name (or path) used to import the module.
   *
   */
  ES_MODULE: 0,
  /**
   * An ES module file with imports and exports.
   *
   * As with `serviceWorkerScript`, above, the value is the raw source code.
   *
   */
  COMMON_JS_MODULE: 1,
  /**
   * A common JS module, using require().
   *
   */
  TEXT: 2,
  /**
   * A raw text blob. Importing this will produce a string with the value.
   *
   */
  DATA: 3,
  /**
   * A raw data blob. Importing this will produce an ArrayBuffer with the value.
   *
   */
  WASM: 4,
  /**
   * 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.
   *
   */
  JSON: 5,
  /**
   * Importing this will produce the result of parsing the given text as JSON.
   *
   */
  OBSOLETE: 6,
  /**
   * This position used to be the nodeJsCompatModule type that has now been
   * obsoleted.
   *
   */
  PYTHON_MODULE: 7,
  /**
   * A Python module. All bundles containing this value type are converted into a JS/WASM Worker
   * Bundle prior to execution.
   *
   */
  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 PYTHON_REQUIREMENT = Worker_Module_Which.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);
  }
  /**
   * A Python package that is required by this bundle. The package must be supported by
   * Pyodide (https://pyodide.org/en/stable/usage/packages-in-pyodide.html). All packages listed
   * will be installed prior to the execution of the worker.
   *
   * The value of this field is ignored and should always be an empty string. Only the module
   * name matters. The field should have been declared `Void`, but it's difficult to change now.
   *
   */
  get pythonRequirement() {
    utils.testWhich("pythonRequirement", utils.getUint16(0, this), 8, this);
    return utils.getText(1, this);
  }
  get _isPythonRequirement() {
    return utils.getUint16(0, this) === 8;
  }
  set pythonRequirement(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,
  R2ADMIN: 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 R2ADMIN = Worker_Binding_Type_Which.R2ADMIN;
  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(_2) {
    utils.setUint16(0, 0, this);
  }
  get _isText() {
    return utils.getUint16(0, this) === 1;
  }
  set text(_2) {
    utils.setUint16(0, 1, this);
  }
  get _isData() {
    return utils.getUint16(0, this) === 2;
  }
  set data(_2) {
    utils.setUint16(0, 2, this);
  }
  get _isJson() {
    return utils.getUint16(0, this) === 3;
  }
  set json(_2) {
    utils.setUint16(0, 3, this);
  }
  get _isWasm() {
    return utils.getUint16(0, this) === 4;
  }
  set wasm(_2) {
    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(_2) {
    utils.setUint16(0, 6, this);
  }
  get _isDurableObjectNamespace() {
    return utils.getUint16(0, this) === 7;
  }
  set durableObjectNamespace(_2) {
    utils.setUint16(0, 7, this);
  }
  get _isKvNamespace() {
    return utils.getUint16(0, this) === 8;
  }
  set kvNamespace(_2) {
    utils.setUint16(0, 8, this);
  }
  get _isR2Bucket() {
    return utils.getUint16(0, this) === 9;
  }
  set r2Bucket(_2) {
    utils.setUint16(0, 9, this);
  }
  get _isR2Admin() {
    return utils.getUint16(0, this) === 10;
  }
  set r2Admin(_2) {
    utils.setUint16(0, 10, this);
  }
  get _isQueue() {
    return utils.getUint16(0, this) === 11;
  }
  set queue(_2) {
    utils.setUint16(0, 11, this);
  }
  get _isAnalyticsEngine() {
    return utils.getUint16(0, this) === 12;
  }
  set analyticsEngine(_2) {
    utils.setUint16(0, 12, this);
  }
  get _isHyperdrive() {
    return utils.getUint16(0, this) === 13;
  }
  set hyperdrive(_2) {
    utils.setUint16(0, 13, this);
  }
  get _isDurableObjectClass() {
    return utils.getUint16(0, this) === 14;
  }
  set durableObjectClass(_2) {
    utils.setUint16(0, 14, this);
  }
  get _isWorkerdDebugPort() {
    return utils.getUint16(0, this) === 15;
  }
  set workerdDebugPort(_2) {
    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 = {
  UNSPECIFIED: 0,
  /**
   * (This catches when someone forgets to specify one of the union members. Do not set this.)
   *
   */
  PARAMETER: 1,
  /**
   * 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.
   *
   */
  TEXT: 2,
  /**
   * A string.
   *
   */
  DATA: 3,
  /**
   * An ArrayBuffer.
   *
   */
  JSON: 4,
  /**
   * A value parsed from JSON.
   *
   */
  WASM_MODULE: 5,
  /**
   * 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.
   *
   */
  CRYPTO_KEY: 6,
  /**
   * 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.
   *
   */
  SERVICE: 7,
  /**
   * A binding representing access to an in-memory cache.
   *
   */
  DURABLE_OBJECT_CLASS: 19,
  /**
   * Binding to a named service (possibly, a worker).
   *
   */
  DURABLE_OBJECT_NAMESPACE: 8,
  /**
   * 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"
   *
   */
  KV_NAMESPACE: 9,
  /**
   * 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.
   *
   */
  R2BUCKET: 10,
  R2ADMIN: 11,
  /**
   * R2 bucket and admin API bindings. Similar to KV namespaces, these turn operations into
   * HTTP requests aimed at the named service.
   *
   */
  WRAPPED: 12,
  /**
   * Wraps a collection of inner bindings in a common api functionality.
   *
   */
  QUEUE: 13,
  /**
   * A Queue binding, implemented by the named service. Requests to the
   * namespace will be converted into HTTP requests targeting the given
   * service name.
   *
   */
  FROM_ENVIRONMENT: 14,
  /**
   * 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`.
   *
   */
  ANALYTICS_ENGINE: 15,
  /**
   * 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
   *
   */
  HYPERDRIVE: 16,
  /**
   * A binding for Hyperdrive. Allows workers to use Hyperdrive caching & pooling for Postgres
   * databases.
   *
   */
  UNSAFE_EVAL: 17,
  /**
   * A simple binding that enables access to the UnsafeEval API.
   *
   */
  MEMORY_CACHE: 18,
  /**
   * A Durable Object class binding, without an actual storage namespace. This can be used to
   * implement a facet.
   *
   */
  WORKER_LOADER: 20,
  /**
   * 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.
   *
   */
  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 R2ADMIN = Worker_Binding_Which.R2ADMIN;
  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(_2) {
    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(_2) {
    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);
  }
  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));
  }
  _adoptR2Admin(value) {
    utils.setUint16(0, 11, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownR2Admin() {
    return utils.disown(this.r2Admin);
  }
  /**
   * R2 bucket and admin API bindings. Similar to KV namespaces, these turn operations into
   * HTTP requests aimed at the named service.
   *
   */
  get r2Admin() {
    utils.testWhich("r2Admin", utils.getUint16(0, this), 11, this);
    return utils.getStruct(1, ServiceDesignator, this);
  }
  _hasR2Admin() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initR2Admin() {
    utils.setUint16(0, 11, this);
    return utils.initStructAt(1, ServiceDesignator, this);
  }
  get _isR2Admin() {
    return utils.getUint16(0, this) === 11;
  }
  set r2Admin(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(_2) {
    utils.setUint16(0, 16, this);
  }
  get _isUnsafeEval() {
    return utils.getUint16(0, this) === 17;
  }
  set unsafeEval(_2) {
    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(_2) {
    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(_2) {
    utils.setUint16(0, 20, this);
  }
  get _isWorkerdDebugPort() {
    return utils.getUint16(0, this) === 21;
  }
  set workerdDebugPort(_2) {
    utils.setUint16(0, 21, this);
  }
  toString() {
    return "Worker_Binding_" + super.toString();
  }
  which() {
    return utils.getUint16(0, this);
  }
};
var Worker_DurableObjectNamespace_ContainerOptions = class extends Struct {
  static _capnp = {
    displayName: "ContainerOptions",
    id: "a609621a4d236cd7",
    size: new ObjectSize(0, 1)
  };
  /**
   * 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);
  }
  toString() {
    return "Worker_DurableObjectNamespace_ContainerOptions_" + super.toString();
  }
};
var Worker_DurableObjectNamespace_Which = {
  /**
   * 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.
   *
   */
  UNIQUE_KEY: 0,
  /**
   * 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.
   *
   */
  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(_2) {
    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, 13)
  };
  get _isNone() {
    return utils.getUint16(2, this) === 0;
  }
  set none(_2) {
    utils.setUint16(2, 0, this);
  }
  get _isInMemory() {
    return utils.getUint16(2, this) === 1;
  }
  set inMemory(_2) {
    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, 13)
  };
  get _isNone() {
    return utils.getUint16(4, this) === 0;
  }
  set none(_2) {
    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, 13),
    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);
  }
  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 = {
  /**
   * 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().)
   *
   */
  HTTP: 0,
  /**
   * Talk to the server over unencrypted HTTP.
   *
   */
  HTTPS: 1,
  /**
   * Talk to the server over encrypted HTTPS.
   *
   */
  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(_2) {
    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(_2) {
    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.
   *
   */
  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._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/runtime/config/index.ts
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(config) {
  const debugPath = process.env.MINIFLARE_WORKERD_CONFIG_DEBUG;
  if (debugPath) {
    (0, import_node_fs6.writeFileSync)(debugPath, JSON.stringify(config, null, 2));
  }
  const message = new Message();
  const struct = message.initRoot(Config);
  encodeCapnpStruct(config, struct);
  return Buffer.from(message.toArrayBuffer());
}

// src/runtime/index.ts
var ControlMessageSchema = external_exports.discriminatedUnion("event", [
  external_exports.object({
    event: external_exports.literal("listen"),
    socket: external_exports.string(),
    port: external_exports.number()
  }),
  external_exports.object({
    event: external_exports.literal("listen-inspector"),
    port: external_exports.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 data2 = message.data;
      const socket = data2.event === "listen-inspector" ? kInspectorSocket : data2.socket;
      const index = requiredSockets.indexOf(socket);
      if (index === -1) continue;
      socketPorts.set(socket, data2.port);
      requiredSockets.splice(index, 1);
      if (requiredSockets.length === 0) return socketPorts;
    }
  } finally {
    options?.signal?.removeEventListener("abort", abortListener);
  }
}
function waitForExit(process7) {
  return new Promise((resolve6) => {
    process7.once("exit", () => resolve6());
  });
}
function pipeOutput(stdout2, stderr2) {
  import_node_readline.default.createInterface(stdout2).on("line", (data2) => console.log(data2));
  import_node_readline.default.createInterface(stderr2).on("line", (data2) => console.error(red2(data2)));
}
function getRuntimeCommand() {
  return process.env.MINIFLARE_WORKERD_PATH ?? import_workerd4.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.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((v2) => !!v2);
  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.`
      );
    }
  }
};
var Runtime = class {
  #process;
  #processExitPromise;
  async updateConfig(configBuffer, options, workerNames, abortSignal) {
    await this.dispose();
    const command = getRuntimeCommand();
    const args = getRuntimeArgs(options);
    const FORCE_COLOR2 = $.enabled ? "1" : "0";
    const runtimeProcess = import_node_child_process.default.spawn(command, args, {
      stdio: ["pipe", "pipe", "pipe", "pipe"],
      env: { ...process.env, FORCE_COLOR: FORCE_COLOR2 }
    });
    const startupLogBuffer = new StartupLogBuffer();
    this.#process = runtimeProcess;
    this.#processExitPromise = waitForExit(runtimeProcess);
    const handleRuntimeStdio = options.handleRuntimeStdio ?? (options.handleStructuredLogs ? (
      // If `handleStructuredLogs` is provided then by default Miniflare should not pipe through the stream's output
      () => {
      }
    ) : pipeOutput);
    handleRuntimeStdio(
      runtimeProcess.stdout.pipe(startupLogBuffer.stdoutStream),
      runtimeProcess.stderr.pipe(startupLogBuffer.stderrStream)
    );
    if (options.handleStructuredLogs) {
      handleStructuredLogsFromStream(
        startupLogBuffer.stdoutStream,
        options.handleStructuredLogs
      );
      handleStructuredLogsFromStream(
        startupLogBuffer.stderrStream,
        options.handleStructuredLogs
      );
    }
    const controlPipe = runtimeProcess.stdio[3];
    (0, import_node_assert9.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 waitForPorts(controlPipe, options);
    if (ports?.has(kInspectorSocket) && process.env.VSCODE_INSPECTOR_OPTIONS) {
      const bootloaderPath = process.env.NODE_OPTIONS?.match(/--require "(.*?)"/)?.[1];
      if (!bootloaderPath) {
        return ports;
      }
      const watchdogPath = import_node_path9.default.resolve(bootloaderPath, "../watchdog.js");
      const info = getInspectorOptions();
      for (const name of workerNames) {
        const p = (0, import_node_child_process.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_crypto2.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
        });
        p.unref();
      }
    }
    startupLogBuffer.stopBuffering();
    if (ports === void 0 && !abortSignal.aborted) {
      startupLogBuffer.handleStartupFailure();
    }
    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;
  }
};
function getSafeCompatibilityDate() {
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
  if (import_workerd4.compatibilityDate > today) {
    return today;
  }
  return import_workerd4.compatibilityDate;
}
var supportedCompatibilityDate = getSafeCompatibilityDate();

// 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/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_fs12 = __toESM(require("fs"));
var import_path12 = __toESM(require("path"));
var import_url12 = __toESM(require("url"));
var contents12;
function cache_worker_default() {
  if (contents12 !== void 0) return contents12;
  const filePath = import_path12.default.join(__dirname, "workers", "cache/cache.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/cache/cache-entry.worker.ts
var import_fs13 = __toESM(require("fs"));
var import_path13 = __toESM(require("path"));
var import_url13 = __toESM(require("url"));
var contents13;
function cache_entry_worker_default() {
  if (contents13 !== void 0) return contents13;
  const filePath = import_path13.default.join(__dirname, "workers", "cache/cache-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/cache/cache-entry-noop.worker.ts
var import_fs14 = __toESM(require("fs"));
var import_path14 = __toESM(require("path"));
var import_url14 = __toESM(require("url"));
var contents14;
function cache_entry_noop_worker_default() {
  if (contents14 !== void 0) return contents14;
  const filePath = import_path14.default.join(__dirname, "workers", "cache/cache-entry-noop.worker.js");
  contents14 = import_fs14.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url14.default.pathToFileURL(filePath);
  return contents14;
}

// src/plugins/cache/index.ts
var CacheOptionsSchema = external_exports.object({
  cache: external_exports.boolean().optional(),
  cacheWarnUsage: external_exports.boolean().optional()
});
var CacheSharedOptionsSchema = external_exports.object({
  cachePersist: PersistenceSchema
});
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 = {
  options: CacheOptionsSchema,
  sharedOptions: CacheSharedOptionsSchema,
  getBindings() {
    return [];
  },
  getNodeBindings() {
    return {};
  },
  async getServices({
    sharedOptions,
    options,
    workerIndex,
    tmpPath,
    defaultPersistRoot,
    unsafeStickyBlobs
  }) {
    const cache = options.cache ?? true;
    const cacheWarnUsage = options.cacheWarnUsage ?? false;
    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
          },
          {
            name: CacheBindings.MAYBE_JSON_CACHE_WARN_USAGE,
            json: JSON.stringify(cacheWarnUsage)
          }
        ]
      };
    } 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 persist = sharedOptions.cachePersist;
      const persistPath = getPersistPath(
        CACHE_PLUGIN_NAME,
        tmpPath,
        defaultPersistRoot,
        persist
      );
      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(unsafeStickyBlobs)
          ]
        }
      };
      services.push(storageService, objectService);
    }
    return services;
  },
  getPersistPath({ cachePersist }, tmpPath) {
    return getPersistPath(CACHE_PLUGIN_NAME, tmpPath, void 0, cachePersist);
  }
};

// src/plugins/do/index.ts
var import_promises5 = __toESM(require("node:fs/promises"));
var DOContainerOptionsSchema = external_exports.object({
  imageName: external_exports.string()
});
var DurableObject = external_exports.object({
  className: external_exports.string(),
  scriptName: external_exports.string().optional(),
  useSQLite: external_exports.boolean().optional(),
  // Allow `uniqueKey` to be customised. We use in Wrangler when setting
  // up stub Durable Objects that proxy requests to Durable Objects in
  // another `workerd` process, to ensure the IDs created by the stub
  // object can be used by the real object too.
  unsafeUniqueKey: external_exports.union([external_exports.string(), external_exports.literal(kUnsafeEphemeralUniqueKey)]).optional(),
  // Prevents the Durable Object being evicted.
  unsafePreventEviction: external_exports.boolean().optional(),
  remoteProxyConnectionString: external_exports.custom().optional(),
  container: external_exports.custom().optional()
});
var DurableObjectsOptionsSchema = external_exports.object({
  durableObjects: external_exports.record(external_exports.union([external_exports.string(), DurableObject])).optional(),
  // Not all DOs are configured as bindings! Include these in a different key
  // These might just be configured via migrations, but should still be allocated storage for e.g. ctx.exports support
  additionalUnboundDurableObjects: external_exports.array(DurableObject).optional()
});
var DurableObjectsSharedOptionsSchema = external_exports.object({
  durableObjectsPersist: PersistenceSchema
});
function normaliseDurableObject(designator) {
  const isObject = typeof designator === "object";
  const className = isObject ? designator.className : designator;
  const scriptName = isObject && designator.scriptName !== void 0 ? designator.scriptName : void 0;
  const serviceName = scriptName ? getUserServiceName(scriptName) : void 0;
  const enableSql = isObject ? designator.useSQLite : void 0;
  const unsafeUniqueKey = isObject ? designator.unsafeUniqueKey : void 0;
  const unsafePreventEviction = isObject ? designator.unsafePreventEviction : void 0;
  const remoteProxyConnectionString = isObject ? designator.remoteProxyConnectionString : void 0;
  const container = isObject ? designator.container : void 0;
  return {
    className,
    scriptName,
    serviceName,
    enableSql,
    unsafeUniqueKey,
    unsafePreventEviction,
    remoteProxyConnectionString,
    container
  };
}
var DURABLE_OBJECTS_PLUGIN_NAME = "do";
var DURABLE_OBJECTS_STORAGE_SERVICE_NAME = `${DURABLE_OBJECTS_PLUGIN_NAME}:storage`;
var DURABLE_OBJECTS_PLUGIN = {
  options: DurableObjectsOptionsSchema,
  sharedOptions: DurableObjectsSharedOptionsSchema,
  getBindings(options) {
    return Object.entries(options.durableObjects ?? {}).map(
      ([name, klass]) => {
        const { className, serviceName } = normaliseDurableObject(klass);
        return {
          name,
          durableObjectNamespace: { className, serviceName }
        };
      }
    );
  },
  getNodeBindings(options) {
    const objects = Object.keys(options.durableObjects ?? {});
    return Object.fromEntries(
      objects.map((name) => [name, new ProxyNodeBinding()])
    );
  },
  async getServices({
    sharedOptions,
    tmpPath,
    defaultPersistRoot,
    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,
      defaultPersistRoot,
      sharedOptions.durableObjectsPersist
    );
    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 }
      }
    ];
  },
  getPersistPath({ durableObjectsPersist }, tmpPath) {
    return getPersistPath(
      DURABLE_OBJECTS_PLUGIN_NAME,
      tmpPath,
      void 0,
      durableObjectsPersist
    );
  }
};

// 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 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_assert11 = __toESM(require("node:assert"));

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/core/do-wrapper.worker.ts
var import_fs15 = __toESM(require("fs"));
var import_path15 = __toESM(require("path"));
var import_url15 = __toESM(require("url"));
var contents15;
function do_wrapper_worker_default() {
  if (contents15 !== void 0) return contents15;
  const filePath = import_path15.default.join(__dirname, "workers", "core/do-wrapper.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/local-explorer/explorer.worker.ts
var import_fs16 = __toESM(require("fs"));
var import_path16 = __toESM(require("path"));
var import_url16 = __toESM(require("url"));
var contents16;
function explorer_worker_default() {
  if (contents16 !== void 0) return contents16;
  const filePath = import_path16.default.join(__dirname, "workers", "local-explorer/explorer.worker.js");
  contents16 = import_fs16.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url16.default.pathToFileURL(filePath);
  return contents16;
}

// src/shared/external-service.ts
var import_node_assert10 = __toESM(require("node:assert"));
function normaliseServiceDesignator(service) {
  let serviceName;
  let entrypoint;
  let remoteProxyConnectionString;
  if (typeof service === "string") {
    serviceName = service;
  } else if (typeof service === "object" && "name" in service) {
    serviceName = service.name !== kCurrentWorker ? service.name : void 0;
    entrypoint = service.entrypoint;
    remoteProxyConnectionString = service.remoteProxyConnectionString;
  }
  return {
    serviceName,
    entrypoint,
    remoteProxyConnectionString
  };
}
function createProxyFallbackService(serviceName, entrypoints) {
  return {
    name: `proxy:fallback:${serviceName}`,
    worker: {
      compatibilityDate: "2025-05-01",
      modules: [
        {
          name: "fallback-service.mjs",
          esModule: [
            `
                            import { WorkerEntrypoint } from "cloudflare:workers";

                            ${CREATE_PROXY_PROTOTYPE_CLASS_HELPER_SCRIPT}

                            function createFallbackWorkerEntrypointClass({ service, entrypoint }) {
                                const klass = createProxyPrototypeClass(WorkerEntrypoint, (key) => {
                                    throw new Error(
                                       \`Cannot access "\${key}" as we couldn't find a local dev session for the "\${entrypoint}" entrypoint of service "\${service}" to proxy to.\`
                                    );
                                });

                                // Return regular HTTP response for HTTP requests
                                klass.prototype.fetch = function(request) {
                                    const message = \`Couldn't find a local dev session for the "\${entrypoint}" entrypoint of service "\${service}" to proxy to\`;
                                    return new Response(message, { status: 503 });
                                };

								// For tail handler support
								klass.prototype.tail = function(events) {
                                    // no-op
                                };

                                return klass;
                            }
                        `,
            ...Array.from(entrypoints).map(
              (entrypoint = "default") => `export ${entrypoint === "default" ? "default" : `const ${entrypoint} =`} createFallbackWorkerEntrypointClass({ service: "${serviceName}", entrypoint: "${entrypoint}" });`
            )
          ].join("\n")
        }
      ]
    }
  };
}
var INBOUND_DO_PROXY_SERVICE_NAME = "proxy:do:inbound";
var OUTBOUND_DO_PROXY_SERVICE_NAME = "proxy:do:outbound";
var INBOUND_DO_PROXY_SERVICE_PATH = "__WRANGLER_EXTERNAL_DURABLE_OBJECTS_WORKER";
function createInboundDoProxyService(internalObjects) {
  return {
    // This is treated as a user service to support custom routes
    name: getUserServiceName(INBOUND_DO_PROXY_SERVICE_NAME),
    worker: {
      compatibilityDate: "2025-05-01",
      // Define bindings for each internal durable objects
      bindings: internalObjects.map(([scriptName, className]) => ({
        name: `${scriptName}_${className}`,
        durableObjectNamespace: {
          className,
          serviceName: getUserServiceName(scriptName)
        }
      })),
      modules: [
        {
          name: "proxy.mjs",
          esModule: `
                        const HEADER_URL = "${PROXY_OBJECT_URL_HEADER}";
                        const HEADER_NAME = "${PROXY_OBJECT_NAME_HEADER}";
                        const HEADER_SCRIPT = "${PROXY_OBJECT_SCRIPT_HEADER}";
                        const HEADER_ID = "${PROXY_OBJECT_ID_HEADER}";
                        const HEADER_CF_BLOB = "${PROXY_OBJECT_CF_BLOB_HEADER}";

                        export default {
                            async fetch(request, env) {
                                const originalUrl = request.headers.get(HEADER_URL);
                                const className = request.headers.get(HEADER_NAME);
                                const scriptName = request.headers.get(HEADER_SCRIPT);
                                const idString = request.headers.get(HEADER_ID);
                                const cfBlob = request.headers.get(HEADER_CF_BLOB);
                                if (originalUrl === null || className === null || idString === null || cfBlob === null) {
                                    return new Response("Received Durable Object proxy request with missing headers", { status: 400 });
                                }
                                if (scriptName === null) {
                                    return new Response("Durable object proxy to a vite dev session requires wrangler v4.x.x or later", { status: 501 });
                                }
                                request = new Request(originalUrl, request);
                                request.headers.delete(HEADER_URL);
                                request.headers.delete(HEADER_NAME);
                                request.headers.delete(HEADER_SCRIPT);
                                request.headers.delete(HEADER_ID);
                                request.headers.delete(HEADER_CF_BLOB);
                                const ns = env[scriptName + '_' + className];
                                const id = ns.idFromString(idString);
                                const stub = ns.get(id);
                                return stub.fetch(request, { cf: JSON.parse(cfBlob) });
                            }
                        }
                    `
        }
      ]
    }
  };
}
var unsafeVariableCharRegex = /[^0-9a-zA-Z_\$]/g;
function getOutboundDoProxyClassName(scriptName, className) {
  return `${scriptName.replace(unsafeVariableCharRegex, "_")}_${className}`;
}
function createOutboundDoProxyService(externalObjects, loopbackAddress, isProxyEnabled) {
  return {
    // The DO plugin will prefix the script name with the user service name
    // This makes sure it matches the result script name on the worker binding
    name: getUserServiceName(OUTBOUND_DO_PROXY_SERVICE_NAME),
    worker: {
      compatibilityDate: "2025-05-01",
      // Use in-memory storage for the stub object classes *declared* by this
      // script. They don't need to persist anything, and would end up using the
      // incorrect unsafe unique key.
      durableObjectStorage: { inMemory: kVoid },
      durableObjectNamespaces: externalObjects.map(
        ([scriptName, className]) => ({
          className: getOutboundDoProxyClassName(scriptName, className),
          uniqueKey: `${scriptName}-${className}`
        })
      ),
      modules: [
        {
          name: "proxy.mjs",
          esModule: [
            `
                            import { DurableObject } from "cloudflare:workers";

                            ${CREATE_PROXY_PROTOTYPE_CLASS_HELPER_SCRIPT}

                            function createProxyDurableObjectClass({ scriptName, className, proxyUrl }) {
                                const klass = createProxyPrototypeClass(DurableObject, (key) => {
									const message = ${isProxyEnabled ? `\`Cannot access "\${className}#\${key}" as Durable Object RPC is not yet supported between multiple dev sessions.\`` : `\`Couldn't find the durable Object "\${className}" of script "\${scriptName}".\``};

                                    throw new Error(message);
                                });

                                // Forward regular HTTP requests to the other dev session
                                klass.prototype.fetch = function(request) {
                                    const proxyRequest = new Request(proxyUrl, request);
                                    proxyRequest.headers.set("${PROXY_OBJECT_URL_HEADER}", request.url);
                                    proxyRequest.headers.set("${PROXY_OBJECT_NAME_HEADER}", className);
                                    proxyRequest.headers.set("${PROXY_OBJECT_SCRIPT_HEADER}", scriptName);
                                    proxyRequest.headers.set("${PROXY_OBJECT_ID_HEADER}", this.ctx.id.toString());
                                    proxyRequest.headers.set("${PROXY_OBJECT_CF_BLOB_HEADER}", JSON.stringify(request.cf ?? {}));
                                    return fetch(proxyRequest);
                                };

                                return klass;
                            }
                        `,
            ...Array.from(externalObjects).map(
              ([scriptName, className]) => `export const ${getOutboundDoProxyClassName(scriptName, className)} = createProxyDurableObjectClass({ scriptName: "${scriptName}", className: "${className}", proxyUrl: "${loopbackAddress}" });`
            )
          ].join("\n")
        }
      ]
    }
  };
}
function getHttpProxyOptions(service, entrypoint) {
  return {
    style: HttpOptions_Style.PROXY,
    // To make sure `request.cf` is set correctly
    cfBlobHeader: CoreHeaders.CF_BLOB,
    // Use the service name and entrypoint as the host to proxy RPC calls
    capnpConnectHost: `${encodeURIComponent(service)}:${encodeURIComponent(entrypoint ?? "default")}`,
    // The headers are injected only for fetch and are used for proxying fetch requests
    injectRequestHeaders: [
      {
        name: PROXY_SERVICE_HEADER,
        value: service
      },
      {
        name: PROXY_ENTRYPOINT_HEADER,
        value: entrypoint ?? "default"
      }
    ]
  };
}
function getProxyFallbackServiceSocketName(service, entrypoint) {
  return `proxy-fallback-${service}-${entrypoint ?? "default"}`;
}
function getProtocol(url38) {
  const protocol = url38.protocol.substring(0, url38.protocol.length - 1);
  (0, import_node_assert10.default)(
    protocol === "http" || protocol === "https",
    "Expected protocol to be http or https"
  );
  return protocol;
}
var PROXY_OBJECT_URL_HEADER = "X-Miniflare-Durable-Object-URL";
var PROXY_OBJECT_NAME_HEADER = "X-Miniflare-Durable-Object-Name";
var PROXY_OBJECT_ID_HEADER = "X-Miniflare-Durable-Object-Id";
var PROXY_OBJECT_CF_BLOB_HEADER = "X-Miniflare-Durable-Object-Cf-Blob";
var PROXY_OBJECT_SCRIPT_HEADER = "X-Miniflare-Durable-Object-Script";
var PROXY_SERVICE_HEADER = "X-Miniflare-Proxy-Service";
var PROXY_ENTRYPOINT_HEADER = "X-Miniflare-Proxy-Entrypoint";
var CREATE_PROXY_PROTOTYPE_CLASS_HELPER_SCRIPT = `
    const HANDLER_RESERVED_KEYS = new Set([
        "alarm",
        "connect",
        "scheduled",
        "self",
        "tail",
        "tailStream",
        "test",
        "trace",
        "webSocketClose",
        "webSocketError",
        "webSocketMessage",
    ]);

    function createProxyPrototypeClass(handlerSuperKlass, getUnknownPrototypeKey) {
        // Build a class with a "Proxy"-prototype, so we can intercept RPC calls and
        // throw unsupported exceptions :see_no_evil:
        function klass(ctx, env) {
            // Delay proxying prototype until construction, so workerd sees this as a
            // regular class when introspecting it. This check fails if we don't do this:
            // https://github.com/cloudflare/workerd/blob/9e915ed637d65adb3c57522607d2cd8b8d692b6b/src/workerd/io/worker.c%2B%2B#L1920-L1921
            klass.prototype = new Proxy(klass.prototype, {
                get(target, key, receiver) {
                    const value = Reflect.get(target, key, receiver);
                    if (value !== undefined) return value;
                    if (HANDLER_RESERVED_KEYS.has(key)) return;
                    return getUnknownPrototypeKey(key);
                }
            });

            return Reflect.construct(handlerSuperKlass, [ctx, env], klass);
        }

        Reflect.setPrototypeOf(klass.prototype, handlerSuperKlass.prototype);
        Reflect.setPrototypeOf(klass, handlerSuperKlass);

        return klass;
    }
`;

// src/plugins/core/explorer.ts
function getExplorerServices(options) {
  const {
    localExplorerUiPath,
    proxyBindings,
    bindingIdMap,
    hasDurableObjects,
    workerNames,
    explorerWorkerOpts,
    telemetry
  } = 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)
    }
  ];
  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_assert11.default)(innerBinding && "service" in innerBinding);
      const databaseId = innerBinding.service?.name?.replace(/^d1:db:/, "");
      (0, import_node_assert11.default)(databaseId);
      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 = binding.kvNamespace.name.replace(/^kv:ns:/, "");
      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 = binding.r2Bucket.name.replace(/^r2:bucket:/, "");
      IDToBindingName.r2[bucketName] = binding.name;
    }
  }
  for (const [serviceName, classMap] of durableObjectClassNames) {
    if (serviceName === getUserServiceName(OUTBOUND_DO_PROXY_SERVICE_NAME)) {
      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.core.name;
    if (!workerName) {
      continue;
    }
    const bindings = {
      kv: [],
      d1: [],
      r2: [],
      do: [],
      workflows: []
    };
    for (const [bindingName, ns] of namespaceEntries(
      workerOpts.kv.kvNamespaces
    )) {
      bindings.kv.push({ id: ns.id, bindingName });
    }
    for (const [bindingName, db] of namespaceEntries(
      workerOpts.d1.d1Databases
    )) {
      bindings.d1.push({ id: db.id, bindingName });
    }
    for (const [bindingName, bucket] of namespaceEntries(
      workerOpts.r2.r2Buckets
    )) {
      bindings.r2.push({ id: bucket.id, bindingName });
    }
    for (const [bindingName, designator] of Object.entries(
      workerOpts.do.durableObjects ?? {}
    )) {
      const doInfo = normaliseDurableObject(designator);
      const scriptName = doInfo.scriptName ?? workerName;
      const serviceName = getUserServiceName(scriptName);
      const uniqueKey = `${scriptName}-${doInfo.className}`;
      const classMap = durableObjectClassNames.get(serviceName);
      const classInfo = classMap?.get(doInfo.className);
      const useSqlite = classInfo?.enableSql ?? false;
      bindings.do.push({
        id: uniqueKey,
        bindingName,
        className: doInfo.className,
        scriptName,
        useSqlite
      });
    }
    for (const [bindingName, workflow] of Object.entries(
      workerOpts.workflows.workflows ?? {}
    )) {
      bindings.workflows.push({
        id: workflow.name,
        bindingName,
        className: workflow.className,
        scriptName: workflow.scriptName ?? 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_assert12 = __toESM(require("node:assert"));
var import_node_fs7 = require("node:fs");
var import_node_module = require("node:module");
var import_node_path10 = __toESM(require("node:path"));
var import_node_url3 = require("node:url");
var import_node_util2 = require("node:util");

// ../../node_modules/.pnpm/acorn@8.14.0/node_modules/acorn/dist/acorn.mjs
var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 80, 3, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 343, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 726, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 2, 60, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 42, 9, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 496, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191];
var nonASCIIidentifierChars = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ACE\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65";
var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC";
var reservedWords = {
  3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
  5: "class enum extends super const export import",
  6: "enum",
  strict: "implements interface let package private protected public static yield",
  strictBind: "eval arguments"
};
var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
var keywords$1 = {
  5: ecma5AndLessKeywords,
  "5module": ecma5AndLessKeywords + " export import",
  6: ecma5AndLessKeywords + " const class extends export import super"
};
var keywordRelationalOperator = /^in(stanceof)?$/;
var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
function isInAstralSet(code, set) {
  var pos = 65536;
  for (var i = 0; i < set.length; i += 2) {
    pos += set[i];
    if (pos > code) {
      return false;
    }
    pos += set[i + 1];
    if (pos >= code) {
      return true;
    }
  }
  return false;
}
function isIdentifierStart(code, astral) {
  if (code < 65) {
    return code === 36;
  }
  if (code < 91) {
    return true;
  }
  if (code < 97) {
    return code === 95;
  }
  if (code < 123) {
    return true;
  }
  if (code <= 65535) {
    return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));
  }
  if (astral === false) {
    return false;
  }
  return isInAstralSet(code, astralIdentifierStartCodes);
}
function isIdentifierChar(code, astral) {
  if (code < 48) {
    return code === 36;
  }
  if (code < 58) {
    return true;
  }
  if (code < 65) {
    return false;
  }
  if (code < 91) {
    return true;
  }
  if (code < 97) {
    return code === 95;
  }
  if (code < 123) {
    return true;
  }
  if (code <= 65535) {
    return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));
  }
  if (astral === false) {
    return false;
  }
  return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
}
var TokenType = function TokenType2(label, conf) {
  if (conf === void 0) conf = {};
  this.label = label;
  this.keyword = conf.keyword;
  this.beforeExpr = !!conf.beforeExpr;
  this.startsExpr = !!conf.startsExpr;
  this.isLoop = !!conf.isLoop;
  this.isAssign = !!conf.isAssign;
  this.prefix = !!conf.prefix;
  this.postfix = !!conf.postfix;
  this.binop = conf.binop || null;
  this.updateContext = null;
};
function binop(name, prec) {
  return new TokenType(name, { beforeExpr: true, binop: prec });
}
var beforeExpr = { beforeExpr: true };
var startsExpr = { startsExpr: true };
var keywords = {};
function kw(name, options) {
  if (options === void 0) options = {};
  options.keyword = name;
  return keywords[name] = new TokenType(name, options);
}
var types$1 = {
  num: new TokenType("num", startsExpr),
  regexp: new TokenType("regexp", startsExpr),
  string: new TokenType("string", startsExpr),
  name: new TokenType("name", startsExpr),
  privateId: new TokenType("privateId", startsExpr),
  eof: new TokenType("eof"),
  // Punctuation token types.
  bracketL: new TokenType("[", { beforeExpr: true, startsExpr: true }),
  bracketR: new TokenType("]"),
  braceL: new TokenType("{", { beforeExpr: true, startsExpr: true }),
  braceR: new TokenType("}"),
  parenL: new TokenType("(", { beforeExpr: true, startsExpr: true }),
  parenR: new TokenType(")"),
  comma: new TokenType(",", beforeExpr),
  semi: new TokenType(";", beforeExpr),
  colon: new TokenType(":", beforeExpr),
  dot: new TokenType("."),
  question: new TokenType("?", beforeExpr),
  questionDot: new TokenType("?."),
  arrow: new TokenType("=>", beforeExpr),
  template: new TokenType("template"),
  invalidTemplate: new TokenType("invalidTemplate"),
  ellipsis: new TokenType("...", beforeExpr),
  backQuote: new TokenType("`", startsExpr),
  dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }),
  // Operators. These carry several kinds of properties to help the
  // parser use them properly (the presence of these properties is
  // what categorizes them as operators).
  //
  // `binop`, when present, specifies that this operator is a binary
  // operator, and will refer to its precedence.
  //
  // `prefix` and `postfix` mark the operator as a prefix or postfix
  // unary operator.
  //
  // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  // binary operators with a very low precedence, that should result
  // in AssignmentExpression nodes.
  eq: new TokenType("=", { beforeExpr: true, isAssign: true }),
  assign: new TokenType("_=", { beforeExpr: true, isAssign: true }),
  incDec: new TokenType("++/--", { prefix: true, postfix: true, startsExpr: true }),
  prefix: new TokenType("!/~", { beforeExpr: true, prefix: true, startsExpr: true }),
  logicalOR: binop("||", 1),
  logicalAND: binop("&&", 2),
  bitwiseOR: binop("|", 3),
  bitwiseXOR: binop("^", 4),
  bitwiseAND: binop("&", 5),
  equality: binop("==/!=/===/!==", 6),
  relational: binop("</>/<=/>=", 7),
  bitShift: binop("<</>>/>>>", 8),
  plusMin: new TokenType("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }),
  modulo: binop("%", 10),
  star: binop("*", 10),
  slash: binop("/", 10),
  starstar: new TokenType("**", { beforeExpr: true }),
  coalesce: binop("??", 1),
  // Keyword token types.
  _break: kw("break"),
  _case: kw("case", beforeExpr),
  _catch: kw("catch"),
  _continue: kw("continue"),
  _debugger: kw("debugger"),
  _default: kw("default", beforeExpr),
  _do: kw("do", { isLoop: true, beforeExpr: true }),
  _else: kw("else", beforeExpr),
  _finally: kw("finally"),
  _for: kw("for", { isLoop: true }),
  _function: kw("function", startsExpr),
  _if: kw("if"),
  _return: kw("return", beforeExpr),
  _switch: kw("switch"),
  _throw: kw("throw", beforeExpr),
  _try: kw("try"),
  _var: kw("var"),
  _const: kw("const"),
  _while: kw("while", { isLoop: true }),
  _with: kw("with"),
  _new: kw("new", { beforeExpr: true, startsExpr: true }),
  _this: kw("this", startsExpr),
  _super: kw("super", startsExpr),
  _class: kw("class", startsExpr),
  _extends: kw("extends", beforeExpr),
  _export: kw("export"),
  _import: kw("import", startsExpr),
  _null: kw("null", startsExpr),
  _true: kw("true", startsExpr),
  _false: kw("false", startsExpr),
  _in: kw("in", { beforeExpr: true, binop: 7 }),
  _instanceof: kw("instanceof", { beforeExpr: true, binop: 7 }),
  _typeof: kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true }),
  _void: kw("void", { beforeExpr: true, prefix: true, startsExpr: true }),
  _delete: kw("delete", { beforeExpr: true, prefix: true, startsExpr: true })
};
var lineBreak = /\r\n?|\n|\u2028|\u2029/;
var lineBreakG = new RegExp(lineBreak.source, "g");
function isNewLine(code) {
  return code === 10 || code === 13 || code === 8232 || code === 8233;
}
function nextLineBreak(code, from, end) {
  if (end === void 0) end = code.length;
  for (var i = from; i < end; i++) {
    var next = code.charCodeAt(i);
    if (isNewLine(next)) {
      return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1;
    }
  }
  return -1;
}
var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
var ref = Object.prototype;
var hasOwnProperty = ref.hasOwnProperty;
var toString = ref.toString;
var hasOwn = Object.hasOwn || (function(obj, propName) {
  return hasOwnProperty.call(obj, propName);
});
var isArray = Array.isArray || (function(obj) {
  return toString.call(obj) === "[object Array]";
});
var regexpCache = /* @__PURE__ */ Object.create(null);
function wordsRegexp(words) {
  return regexpCache[words] || (regexpCache[words] = new RegExp("^(?:" + words.replace(/ /g, "|") + ")$"));
}
function codePointToString(code) {
  if (code <= 65535) {
    return String.fromCharCode(code);
  }
  code -= 65536;
  return String.fromCharCode((code >> 10) + 55296, (code & 1023) + 56320);
}
var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
var Position = function Position2(line, col) {
  this.line = line;
  this.column = col;
};
Position.prototype.offset = function offset(n) {
  return new Position(this.line, this.column + n);
};
var SourceLocation = function SourceLocation2(p, start, end) {
  this.start = start;
  this.end = end;
  if (p.sourceFile !== null) {
    this.source = p.sourceFile;
  }
};
function getLineInfo(input, offset2) {
  for (var line = 1, cur = 0; ; ) {
    var nextBreak = nextLineBreak(input, cur, offset2);
    if (nextBreak < 0) {
      return new Position(line, offset2 - cur);
    }
    ++line;
    cur = nextBreak;
  }
}
var defaultOptions = {
  // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"`
  // (the latest version the library supports). This influences
  // support for strict mode, the set of reserved words, and support
  // for new syntax features.
  ecmaVersion: null,
  // `sourceType` indicates the mode the code should be parsed in.
  // Can be either `"script"` or `"module"`. This influences global
  // strict mode and parsing of `import` and `export` declarations.
  sourceType: "script",
  // `onInsertedSemicolon` can be a callback that will be called when
  // a semicolon is automatically inserted. It will be passed the
  // position of the inserted semicolon as an offset, and if
  // `locations` is enabled, it is given the location as a `{line,
  // column}` object as second argument.
  onInsertedSemicolon: null,
  // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  // trailing commas.
  onTrailingComma: null,
  // By default, reserved words are only enforced if ecmaVersion >= 5.
  // Set `allowReserved` to a boolean value to explicitly turn this on
  // an off. When this option has the value "never", reserved words
  // and keywords can also not be used as property names.
  allowReserved: null,
  // When enabled, a return at the top level is not considered an
  // error.
  allowReturnOutsideFunction: false,
  // When enabled, import/export statements are not constrained to
  // appearing at the top of the program, and an import.meta expression
  // in a script isn't considered an error.
  allowImportExportEverywhere: false,
  // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  // When enabled, await identifiers are allowed to appear at the top-level scope,
  // but they are still not allowed in non-async functions.
  allowAwaitOutsideFunction: null,
  // When enabled, super identifiers are not constrained to
  // appearing in methods and do not raise an error when they appear elsewhere.
  allowSuperOutsideMethod: null,
  // When enabled, hashbang directive in the beginning of file is
  // allowed and treated as a line comment. Enabled by default when
  // `ecmaVersion` >= 2023.
  allowHashBang: false,
  // By default, the parser will verify that private properties are
  // only used in places where they are valid and have been declared.
  // Set this to false to turn such checks off.
  checkPrivateFields: true,
  // When `locations` is on, `loc` properties holding objects with
  // `start` and `end` properties in `{line, column}` form (with
  // line being 1-based and column 0-based) will be attached to the
  // nodes.
  locations: false,
  // A function can be passed as `onToken` option, which will
  // cause Acorn to call that function with object in the same
  // format as tokens returned from `tokenizer().getToken()`. Note
  // that you are not allowed to call the parser from the
  // callback—that will corrupt its internal state.
  onToken: null,
  // A function can be passed as `onComment` option, which will
  // cause Acorn to call that function with `(block, text, start,
  // end)` parameters whenever a comment is skipped. `block` is a
  // boolean indicating whether this is a block (`/* */`) comment,
  // `text` is the content of the comment, and `start` and `end` are
  // character offsets that denote the start and end of the comment.
  // When the `locations` option is on, two more parameters are
  // passed, the full `{line, column}` locations of the start and
  // end of the comments. Note that you are not allowed to call the
  // parser from the callback—that will corrupt its internal state.
  // When this option has an array as value, objects representing the
  // comments are pushed to it.
  onComment: null,
  // Nodes have their start and end characters offsets recorded in
  // `start` and `end` properties (directly on the node, rather than
  // the `loc` object, which holds line/column data. To also add a
  // [semi-standardized][range] `range` property holding a `[start,
  // end]` array with the same numbers, set the `ranges` option to
  // `true`.
  //
  // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  ranges: false,
  // It is possible to parse multiple files into a single AST by
  // passing the tree produced by parsing the first file as
  // `program` option in subsequent parses. This will add the
  // toplevel forms of the parsed file to the `Program` (top) node
  // of an existing parse tree.
  program: null,
  // When `locations` is on, you can pass this to record the source
  // file in every node's `loc` object.
  sourceFile: null,
  // This value, if given, is stored in every node, whether
  // `locations` is on or off.
  directSourceFile: null,
  // When enabled, parenthesized expressions are represented by
  // (non-standard) ParenthesizedExpression nodes
  preserveParens: false
};
var warnedAboutEcmaVersion = false;
function getOptions(opts) {
  var options = {};
  for (var opt in defaultOptions) {
    options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt];
  }
  if (options.ecmaVersion === "latest") {
    options.ecmaVersion = 1e8;
  } else if (options.ecmaVersion == null) {
    if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
      warnedAboutEcmaVersion = true;
      console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
    }
    options.ecmaVersion = 11;
  } else if (options.ecmaVersion >= 2015) {
    options.ecmaVersion -= 2009;
  }
  if (options.allowReserved == null) {
    options.allowReserved = options.ecmaVersion < 5;
  }
  if (!opts || opts.allowHashBang == null) {
    options.allowHashBang = options.ecmaVersion >= 14;
  }
  if (isArray(options.onToken)) {
    var tokens = options.onToken;
    options.onToken = function(token) {
      return tokens.push(token);
    };
  }
  if (isArray(options.onComment)) {
    options.onComment = pushComment(options, options.onComment);
  }
  return options;
}
function pushComment(options, array) {
  return function(block, text, start, end, startLoc, endLoc) {
    var comment = {
      type: block ? "Block" : "Line",
      value: text,
      start,
      end
    };
    if (options.locations) {
      comment.loc = new SourceLocation(this, startLoc, endLoc);
    }
    if (options.ranges) {
      comment.range = [start, end];
    }
    array.push(comment);
  };
}
var SCOPE_TOP = 1;
var SCOPE_FUNCTION = 2;
var SCOPE_ASYNC = 4;
var SCOPE_GENERATOR = 8;
var SCOPE_ARROW = 16;
var SCOPE_SIMPLE_CATCH = 32;
var SCOPE_SUPER = 64;
var SCOPE_DIRECT_SUPER = 128;
var SCOPE_CLASS_STATIC_BLOCK = 256;
var SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
function functionFlags(async, generator) {
  return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0);
}
var BIND_NONE = 0;
var BIND_VAR = 1;
var BIND_LEXICAL = 2;
var BIND_FUNCTION = 3;
var BIND_SIMPLE_CATCH = 4;
var BIND_OUTSIDE = 5;
var Parser = function Parser2(options, input, startPos) {
  this.options = options = getOptions(options);
  this.sourceFile = options.sourceFile;
  this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  var reserved = "";
  if (options.allowReserved !== true) {
    reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
    if (options.sourceType === "module") {
      reserved += " await";
    }
  }
  this.reservedWords = wordsRegexp(reserved);
  var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  this.reservedWordsStrict = wordsRegexp(reservedStrict);
  this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  this.input = String(input);
  this.containsEsc = false;
  if (startPos) {
    this.pos = startPos;
    this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
    this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  } else {
    this.pos = this.lineStart = 0;
    this.curLine = 1;
  }
  this.type = types$1.eof;
  this.value = null;
  this.start = this.end = this.pos;
  this.startLoc = this.endLoc = this.curPosition();
  this.lastTokEndLoc = this.lastTokStartLoc = null;
  this.lastTokStart = this.lastTokEnd = this.pos;
  this.context = this.initialContext();
  this.exprAllowed = true;
  this.inModule = options.sourceType === "module";
  this.strict = this.inModule || this.strictDirective(this.pos);
  this.potentialArrowAt = -1;
  this.potentialArrowInForAwait = false;
  this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  this.labels = [];
  this.undefinedExports = /* @__PURE__ */ Object.create(null);
  if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") {
    this.skipLineComment(2);
  }
  this.scopeStack = [];
  this.enterScope(SCOPE_TOP);
  this.regexpState = null;
  this.privateNameStack = [];
};
var prototypeAccessors = { inFunction: { configurable: true }, inGenerator: { configurable: true }, inAsync: { configurable: true }, canAwait: { configurable: true }, allowSuper: { configurable: true }, allowDirectSuper: { configurable: true }, treatFunctionsAsVar: { configurable: true }, allowNewDotTarget: { configurable: true }, inClassStaticBlock: { configurable: true } };
Parser.prototype.parse = function parse5() {
  var node = this.options.program || this.startNode();
  this.nextToken();
  return this.parseTopLevel(node);
};
prototypeAccessors.inFunction.get = function() {
  return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
};
prototypeAccessors.inGenerator.get = function() {
  return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit;
};
prototypeAccessors.inAsync.get = function() {
  return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit;
};
prototypeAccessors.canAwait.get = function() {
  for (var i = this.scopeStack.length - 1; i >= 0; i--) {
    var scope = this.scopeStack[i];
    if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) {
      return false;
    }
    if (scope.flags & SCOPE_FUNCTION) {
      return (scope.flags & SCOPE_ASYNC) > 0;
    }
  }
  return this.inModule && this.options.ecmaVersion >= 13 || this.options.allowAwaitOutsideFunction;
};
prototypeAccessors.allowSuper.get = function() {
  var ref2 = this.currentThisScope();
  var flags = ref2.flags;
  var inClassFieldInit = ref2.inClassFieldInit;
  return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod;
};
prototypeAccessors.allowDirectSuper.get = function() {
  return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
};
prototypeAccessors.treatFunctionsAsVar.get = function() {
  return this.treatFunctionsAsVarInScope(this.currentScope());
};
prototypeAccessors.allowNewDotTarget.get = function() {
  var ref2 = this.currentThisScope();
  var flags = ref2.flags;
  var inClassFieldInit = ref2.inClassFieldInit;
  return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit;
};
prototypeAccessors.inClassStaticBlock.get = function() {
  return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0;
};
Parser.extend = function extend() {
  var plugins = [], len = arguments.length;
  while (len--) plugins[len] = arguments[len];
  var cls = this;
  for (var i = 0; i < plugins.length; i++) {
    cls = plugins[i](cls);
  }
  return cls;
};
Parser.parse = function parse6(input, options) {
  return new this(options, input).parse();
};
Parser.parseExpressionAt = function parseExpressionAt(input, pos, options) {
  var parser = new this(options, input, pos);
  parser.nextToken();
  return parser.parseExpression();
};
Parser.tokenizer = function tokenizer(input, options) {
  return new this(options, input);
};
Object.defineProperties(Parser.prototype, prototypeAccessors);
var pp$9 = Parser.prototype;
var literal = /^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;
pp$9.strictDirective = function(start) {
  if (this.options.ecmaVersion < 5) {
    return false;
  }
  for (; ; ) {
    skipWhiteSpace.lastIndex = start;
    start += skipWhiteSpace.exec(this.input)[0].length;
    var match = literal.exec(this.input.slice(start));
    if (!match) {
      return false;
    }
    if ((match[1] || match[2]) === "use strict") {
      skipWhiteSpace.lastIndex = start + match[0].length;
      var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
      var next = this.input.charAt(end);
      return next === ";" || next === "}" || lineBreak.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=");
    }
    start += match[0].length;
    skipWhiteSpace.lastIndex = start;
    start += skipWhiteSpace.exec(this.input)[0].length;
    if (this.input[start] === ";") {
      start++;
    }
  }
};
pp$9.eat = function(type) {
  if (this.type === type) {
    this.next();
    return true;
  } else {
    return false;
  }
};
pp$9.isContextual = function(name) {
  return this.type === types$1.name && this.value === name && !this.containsEsc;
};
pp$9.eatContextual = function(name) {
  if (!this.isContextual(name)) {
    return false;
  }
  this.next();
  return true;
};
pp$9.expectContextual = function(name) {
  if (!this.eatContextual(name)) {
    this.unexpected();
  }
};
pp$9.canInsertSemicolon = function() {
  return this.type === types$1.eof || this.type === types$1.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
};
pp$9.insertSemicolon = function() {
  if (this.canInsertSemicolon()) {
    if (this.options.onInsertedSemicolon) {
      this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc);
    }
    return true;
  }
};
pp$9.semicolon = function() {
  if (!this.eat(types$1.semi) && !this.insertSemicolon()) {
    this.unexpected();
  }
};
pp$9.afterTrailingComma = function(tokType, notNext) {
  if (this.type === tokType) {
    if (this.options.onTrailingComma) {
      this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc);
    }
    if (!notNext) {
      this.next();
    }
    return true;
  }
};
pp$9.expect = function(type) {
  this.eat(type) || this.unexpected();
};
pp$9.unexpected = function(pos) {
  this.raise(pos != null ? pos : this.start, "Unexpected token");
};
var DestructuringErrors = function DestructuringErrors2() {
  this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1;
};
pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  if (!refDestructuringErrors) {
    return;
  }
  if (refDestructuringErrors.trailingComma > -1) {
    this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element");
  }
  var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  if (parens > -1) {
    this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern");
  }
};
pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  if (!refDestructuringErrors) {
    return false;
  }
  var shorthandAssign = refDestructuringErrors.shorthandAssign;
  var doubleProto = refDestructuringErrors.doubleProto;
  if (!andThrow) {
    return shorthandAssign >= 0 || doubleProto >= 0;
  }
  if (shorthandAssign >= 0) {
    this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns");
  }
  if (doubleProto >= 0) {
    this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property");
  }
};
pp$9.checkYieldAwaitInDefaultParams = function() {
  if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) {
    this.raise(this.yieldPos, "Yield expression cannot be a default value");
  }
  if (this.awaitPos) {
    this.raise(this.awaitPos, "Await expression cannot be a default value");
  }
};
pp$9.isSimpleAssignTarget = function(expr) {
  if (expr.type === "ParenthesizedExpression") {
    return this.isSimpleAssignTarget(expr.expression);
  }
  return expr.type === "Identifier" || expr.type === "MemberExpression";
};
var pp$8 = Parser.prototype;
pp$8.parseTopLevel = function(node) {
  var exports2 = /* @__PURE__ */ Object.create(null);
  if (!node.body) {
    node.body = [];
  }
  while (this.type !== types$1.eof) {
    var stmt = this.parseStatement(null, true, exports2);
    node.body.push(stmt);
  }
  if (this.inModule) {
    for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) {
      var name = list[i];
      this.raiseRecoverable(this.undefinedExports[name].start, "Export '" + name + "' is not defined");
    }
  }
  this.adaptDirectivePrologue(node.body);
  this.next();
  node.sourceType = this.options.sourceType;
  return this.finishNode(node, "Program");
};
var loopLabel = { kind: "loop" };
var switchLabel = { kind: "switch" };
pp$8.isLet = function(context) {
  if (this.options.ecmaVersion < 6 || !this.isContextual("let")) {
    return false;
  }
  skipWhiteSpace.lastIndex = this.pos;
  var skip = skipWhiteSpace.exec(this.input);
  var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  if (nextCh === 91 || nextCh === 92) {
    return true;
  }
  if (context) {
    return false;
  }
  if (nextCh === 123 || nextCh > 55295 && nextCh < 56320) {
    return true;
  }
  if (isIdentifierStart(nextCh, true)) {
    var pos = next + 1;
    while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) {
      ++pos;
    }
    if (nextCh === 92 || nextCh > 55295 && nextCh < 56320) {
      return true;
    }
    var ident = this.input.slice(next, pos);
    if (!keywordRelationalOperator.test(ident)) {
      return true;
    }
  }
  return false;
};
pp$8.isAsyncFunction = function() {
  if (this.options.ecmaVersion < 8 || !this.isContextual("async")) {
    return false;
  }
  skipWhiteSpace.lastIndex = this.pos;
  var skip = skipWhiteSpace.exec(this.input);
  var next = this.pos + skip[0].length, after;
  return !lineBreak.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 55295 && after < 56320));
};
pp$8.parseStatement = function(context, topLevel, exports2) {
  var starttype = this.type, node = this.startNode(), kind;
  if (this.isLet(context)) {
    starttype = types$1._var;
    kind = "let";
  }
  switch (starttype) {
    case types$1._break:
    case types$1._continue:
      return this.parseBreakContinueStatement(node, starttype.keyword);
    case types$1._debugger:
      return this.parseDebuggerStatement(node);
    case types$1._do:
      return this.parseDoStatement(node);
    case types$1._for:
      return this.parseForStatement(node);
    case types$1._function:
      if (context && (this.strict || context !== "if" && context !== "label") && this.options.ecmaVersion >= 6) {
        this.unexpected();
      }
      return this.parseFunctionStatement(node, false, !context);
    case types$1._class:
      if (context) {
        this.unexpected();
      }
      return this.parseClass(node, true);
    case types$1._if:
      return this.parseIfStatement(node);
    case types$1._return:
      return this.parseReturnStatement(node);
    case types$1._switch:
      return this.parseSwitchStatement(node);
    case types$1._throw:
      return this.parseThrowStatement(node);
    case types$1._try:
      return this.parseTryStatement(node);
    case types$1._const:
    case types$1._var:
      kind = kind || this.value;
      if (context && kind !== "var") {
        this.unexpected();
      }
      return this.parseVarStatement(node, kind);
    case types$1._while:
      return this.parseWhileStatement(node);
    case types$1._with:
      return this.parseWithStatement(node);
    case types$1.braceL:
      return this.parseBlock(true, node);
    case types$1.semi:
      return this.parseEmptyStatement(node);
    case types$1._export:
    case types$1._import:
      if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
        skipWhiteSpace.lastIndex = this.pos;
        var skip = skipWhiteSpace.exec(this.input);
        var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
        if (nextCh === 40 || nextCh === 46) {
          return this.parseExpressionStatement(node, this.parseExpression());
        }
      }
      if (!this.options.allowImportExportEverywhere) {
        if (!topLevel) {
          this.raise(this.start, "'import' and 'export' may only appear at the top level");
        }
        if (!this.inModule) {
          this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
        }
      }
      return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports2);
    // If the statement does not start with a statement keyword or a
    // brace, it's an ExpressionStatement or LabeledStatement. We
    // simply start parsing an expression, and afterwards, if the
    // next token is a colon and the expression was a simple
    // Identifier node, we switch to interpreting it as a label.
    default:
      if (this.isAsyncFunction()) {
        if (context) {
          this.unexpected();
        }
        this.next();
        return this.parseFunctionStatement(node, true, !context);
      }
      var maybeName = this.value, expr = this.parseExpression();
      if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) {
        return this.parseLabeledStatement(node, maybeName, expr, context);
      } else {
        return this.parseExpressionStatement(node, expr);
      }
  }
};
pp$8.parseBreakContinueStatement = function(node, keyword) {
  var isBreak = keyword === "break";
  this.next();
  if (this.eat(types$1.semi) || this.insertSemicolon()) {
    node.label = null;
  } else if (this.type !== types$1.name) {
    this.unexpected();
  } else {
    node.label = this.parseIdent();
    this.semicolon();
  }
  var i = 0;
  for (; i < this.labels.length; ++i) {
    var lab = this.labels[i];
    if (node.label == null || lab.name === node.label.name) {
      if (lab.kind != null && (isBreak || lab.kind === "loop")) {
        break;
      }
      if (node.label && isBreak) {
        break;
      }
    }
  }
  if (i === this.labels.length) {
    this.raise(node.start, "Unsyntactic " + keyword);
  }
  return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
};
pp$8.parseDebuggerStatement = function(node) {
  this.next();
  this.semicolon();
  return this.finishNode(node, "DebuggerStatement");
};
pp$8.parseDoStatement = function(node) {
  this.next();
  this.labels.push(loopLabel);
  node.body = this.parseStatement("do");
  this.labels.pop();
  this.expect(types$1._while);
  node.test = this.parseParenExpression();
  if (this.options.ecmaVersion >= 6) {
    this.eat(types$1.semi);
  } else {
    this.semicolon();
  }
  return this.finishNode(node, "DoWhileStatement");
};
pp$8.parseForStatement = function(node) {
  this.next();
  var awaitAt = this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await") ? this.lastTokStart : -1;
  this.labels.push(loopLabel);
  this.enterScope(0);
  this.expect(types$1.parenL);
  if (this.type === types$1.semi) {
    if (awaitAt > -1) {
      this.unexpected(awaitAt);
    }
    return this.parseFor(node, null);
  }
  var isLet = this.isLet();
  if (this.type === types$1._var || this.type === types$1._const || isLet) {
    var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
    this.next();
    this.parseVar(init$1, true, kind);
    this.finishNode(init$1, "VariableDeclaration");
    if ((this.type === types$1._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && init$1.declarations.length === 1) {
      if (this.options.ecmaVersion >= 9) {
        if (this.type === types$1._in) {
          if (awaitAt > -1) {
            this.unexpected(awaitAt);
          }
        } else {
          node.await = awaitAt > -1;
        }
      }
      return this.parseForIn(node, init$1);
    }
    if (awaitAt > -1) {
      this.unexpected(awaitAt);
    }
    return this.parseFor(node, init$1);
  }
  var startsWithLet = this.isContextual("let"), isForOf = false;
  var containsEsc = this.containsEsc;
  var refDestructuringErrors = new DestructuringErrors();
  var initPos = this.start;
  var init2 = awaitAt > -1 ? this.parseExprSubscripts(refDestructuringErrors, "await") : this.parseExpression(true, refDestructuringErrors);
  if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
    if (awaitAt > -1) {
      if (this.type === types$1._in) {
        this.unexpected(awaitAt);
      }
      node.await = true;
    } else if (isForOf && this.options.ecmaVersion >= 8) {
      if (init2.start === initPos && !containsEsc && init2.type === "Identifier" && init2.name === "async") {
        this.unexpected();
      } else if (this.options.ecmaVersion >= 9) {
        node.await = false;
      }
    }
    if (startsWithLet && isForOf) {
      this.raise(init2.start, "The left-hand side of a for-of loop may not start with 'let'.");
    }
    this.toAssignable(init2, false, refDestructuringErrors);
    this.checkLValPattern(init2);
    return this.parseForIn(node, init2);
  } else {
    this.checkExpressionErrors(refDestructuringErrors, true);
  }
  if (awaitAt > -1) {
    this.unexpected(awaitAt);
  }
  return this.parseFor(node, init2);
};
pp$8.parseFunctionStatement = function(node, isAsync3, declarationPosition) {
  this.next();
  return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync3);
};
pp$8.parseIfStatement = function(node) {
  this.next();
  node.test = this.parseParenExpression();
  node.consequent = this.parseStatement("if");
  node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
  return this.finishNode(node, "IfStatement");
};
pp$8.parseReturnStatement = function(node) {
  if (!this.inFunction && !this.options.allowReturnOutsideFunction) {
    this.raise(this.start, "'return' outside of function");
  }
  this.next();
  if (this.eat(types$1.semi) || this.insertSemicolon()) {
    node.argument = null;
  } else {
    node.argument = this.parseExpression();
    this.semicolon();
  }
  return this.finishNode(node, "ReturnStatement");
};
pp$8.parseSwitchStatement = function(node) {
  this.next();
  node.discriminant = this.parseParenExpression();
  node.cases = [];
  this.expect(types$1.braceL);
  this.labels.push(switchLabel);
  this.enterScope(0);
  var cur;
  for (var sawDefault = false; this.type !== types$1.braceR; ) {
    if (this.type === types$1._case || this.type === types$1._default) {
      var isCase = this.type === types$1._case;
      if (cur) {
        this.finishNode(cur, "SwitchCase");
      }
      node.cases.push(cur = this.startNode());
      cur.consequent = [];
      this.next();
      if (isCase) {
        cur.test = this.parseExpression();
      } else {
        if (sawDefault) {
          this.raiseRecoverable(this.lastTokStart, "Multiple default clauses");
        }
        sawDefault = true;
        cur.test = null;
      }
      this.expect(types$1.colon);
    } else {
      if (!cur) {
        this.unexpected();
      }
      cur.consequent.push(this.parseStatement(null));
    }
  }
  this.exitScope();
  if (cur) {
    this.finishNode(cur, "SwitchCase");
  }
  this.next();
  this.labels.pop();
  return this.finishNode(node, "SwitchStatement");
};
pp$8.parseThrowStatement = function(node) {
  this.next();
  if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) {
    this.raise(this.lastTokEnd, "Illegal newline after throw");
  }
  node.argument = this.parseExpression();
  this.semicolon();
  return this.finishNode(node, "ThrowStatement");
};
var empty$1 = [];
pp$8.parseCatchClauseParam = function() {
  var param = this.parseBindingAtom();
  var simple2 = param.type === "Identifier";
  this.enterScope(simple2 ? SCOPE_SIMPLE_CATCH : 0);
  this.checkLValPattern(param, simple2 ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  this.expect(types$1.parenR);
  return param;
};
pp$8.parseTryStatement = function(node) {
  this.next();
  node.block = this.parseBlock();
  node.handler = null;
  if (this.type === types$1._catch) {
    var clause = this.startNode();
    this.next();
    if (this.eat(types$1.parenL)) {
      clause.param = this.parseCatchClauseParam();
    } else {
      if (this.options.ecmaVersion < 10) {
        this.unexpected();
      }
      clause.param = null;
      this.enterScope(0);
    }
    clause.body = this.parseBlock(false);
    this.exitScope();
    node.handler = this.finishNode(clause, "CatchClause");
  }
  node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
  if (!node.handler && !node.finalizer) {
    this.raise(node.start, "Missing catch or finally clause");
  }
  return this.finishNode(node, "TryStatement");
};
pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) {
  this.next();
  this.parseVar(node, false, kind, allowMissingInitializer);
  this.semicolon();
  return this.finishNode(node, "VariableDeclaration");
};
pp$8.parseWhileStatement = function(node) {
  this.next();
  node.test = this.parseParenExpression();
  this.labels.push(loopLabel);
  node.body = this.parseStatement("while");
  this.labels.pop();
  return this.finishNode(node, "WhileStatement");
};
pp$8.parseWithStatement = function(node) {
  if (this.strict) {
    this.raise(this.start, "'with' in strict mode");
  }
  this.next();
  node.object = this.parseParenExpression();
  node.body = this.parseStatement("with");
  return this.finishNode(node, "WithStatement");
};
pp$8.parseEmptyStatement = function(node) {
  this.next();
  return this.finishNode(node, "EmptyStatement");
};
pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
  for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) {
    var label = list[i$1];
    if (label.name === maybeName) {
      this.raise(expr.start, "Label '" + maybeName + "' is already declared");
    }
  }
  var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
  for (var i = this.labels.length - 1; i >= 0; i--) {
    var label$1 = this.labels[i];
    if (label$1.statementStart === node.start) {
      label$1.statementStart = this.start;
      label$1.kind = kind;
    } else {
      break;
    }
  }
  this.labels.push({ name: maybeName, kind, statementStart: this.start });
  node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  this.labels.pop();
  node.label = expr;
  return this.finishNode(node, "LabeledStatement");
};
pp$8.parseExpressionStatement = function(node, expr) {
  node.expression = expr;
  this.semicolon();
  return this.finishNode(node, "ExpressionStatement");
};
pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  if (createNewLexicalScope === void 0) createNewLexicalScope = true;
  if (node === void 0) node = this.startNode();
  node.body = [];
  this.expect(types$1.braceL);
  if (createNewLexicalScope) {
    this.enterScope(0);
  }
  while (this.type !== types$1.braceR) {
    var stmt = this.parseStatement(null);
    node.body.push(stmt);
  }
  if (exitStrict) {
    this.strict = false;
  }
  this.next();
  if (createNewLexicalScope) {
    this.exitScope();
  }
  return this.finishNode(node, "BlockStatement");
};
pp$8.parseFor = function(node, init2) {
  node.init = init2;
  this.expect(types$1.semi);
  node.test = this.type === types$1.semi ? null : this.parseExpression();
  this.expect(types$1.semi);
  node.update = this.type === types$1.parenR ? null : this.parseExpression();
  this.expect(types$1.parenR);
  node.body = this.parseStatement("for");
  this.exitScope();
  this.labels.pop();
  return this.finishNode(node, "ForStatement");
};
pp$8.parseForIn = function(node, init2) {
  var isForIn = this.type === types$1._in;
  this.next();
  if (init2.type === "VariableDeclaration" && init2.declarations[0].init != null && (!isForIn || this.options.ecmaVersion < 8 || this.strict || init2.kind !== "var" || init2.declarations[0].id.type !== "Identifier")) {
    this.raise(
      init2.start,
      (isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer"
    );
  }
  node.left = init2;
  node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  this.expect(types$1.parenR);
  node.body = this.parseStatement("for");
  this.exitScope();
  this.labels.pop();
  return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
};
pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) {
  node.declarations = [];
  node.kind = kind;
  for (; ; ) {
    var decl = this.startNode();
    this.parseVarId(decl, kind);
    if (this.eat(types$1.eq)) {
      decl.init = this.parseMaybeAssign(isFor);
    } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
      this.unexpected();
    } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
      this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
    } else {
      decl.init = null;
    }
    node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
    if (!this.eat(types$1.comma)) {
      break;
    }
  }
  return node;
};
pp$8.parseVarId = function(decl, kind) {
  decl.id = this.parseBindingAtom();
  this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
};
var FUNC_STATEMENT = 1;
var FUNC_HANGING_STATEMENT = 2;
var FUNC_NULLABLE_ID = 4;
pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync3, forInit) {
  this.initFunction(node);
  if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync3) {
    if (this.type === types$1.star && statement & FUNC_HANGING_STATEMENT) {
      this.unexpected();
    }
    node.generator = this.eat(types$1.star);
  }
  if (this.options.ecmaVersion >= 8) {
    node.async = !!isAsync3;
  }
  if (statement & FUNC_STATEMENT) {
    node.id = statement & FUNC_NULLABLE_ID && this.type !== types$1.name ? null : this.parseIdent();
    if (node.id && !(statement & FUNC_HANGING_STATEMENT)) {
      this.checkLValSimple(node.id, this.strict || node.generator || node.async ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION);
    }
  }
  var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;
  this.enterScope(functionFlags(node.async, node.generator));
  if (!(statement & FUNC_STATEMENT)) {
    node.id = this.type === types$1.name ? this.parseIdent() : null;
  }
  this.parseFunctionParams(node);
  this.parseFunctionBody(node, allowExpressionBody, false, forInit);
  this.yieldPos = oldYieldPos;
  this.awaitPos = oldAwaitPos;
  this.awaitIdentPos = oldAwaitIdentPos;
  return this.finishNode(node, statement & FUNC_STATEMENT ? "FunctionDeclaration" : "FunctionExpression");
};
pp$8.parseFunctionParams = function(node) {
  this.expect(types$1.parenL);
  node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  this.checkYieldAwaitInDefaultParams();
};
pp$8.parseClass = function(node, isStatement) {
  this.next();
  var oldStrict = this.strict;
  this.strict = true;
  this.parseClassId(node, isStatement);
  this.parseClassSuper(node);
  var privateNameMap = this.enterClassBody();
  var classBody = this.startNode();
  var hadConstructor = false;
  classBody.body = [];
  this.expect(types$1.braceL);
  while (this.type !== types$1.braceR) {
    var element = this.parseClassElement(node.superClass !== null);
    if (element) {
      classBody.body.push(element);
      if (element.type === "MethodDefinition" && element.kind === "constructor") {
        if (hadConstructor) {
          this.raiseRecoverable(element.start, "Duplicate constructor in the same class");
        }
        hadConstructor = true;
      } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
        this.raiseRecoverable(element.key.start, "Identifier '#" + element.key.name + "' has already been declared");
      }
    }
  }
  this.strict = oldStrict;
  this.next();
  node.body = this.finishNode(classBody, "ClassBody");
  this.exitClassBody();
  return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
};
pp$8.parseClassElement = function(constructorAllowsSuper) {
  if (this.eat(types$1.semi)) {
    return null;
  }
  var ecmaVersion = this.options.ecmaVersion;
  var node = this.startNode();
  var keyName = "";
  var isGenerator = false;
  var isAsync3 = false;
  var kind = "method";
  var isStatic = false;
  if (this.eatContextual("static")) {
    if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
      this.parseClassStaticBlock(node);
      return node;
    }
    if (this.isClassElementNameStart() || this.type === types$1.star) {
      isStatic = true;
    } else {
      keyName = "static";
    }
  }
  node.static = isStatic;
  if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
    if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
      isAsync3 = true;
    } else {
      keyName = "async";
    }
  }
  if (!keyName && (ecmaVersion >= 9 || !isAsync3) && this.eat(types$1.star)) {
    isGenerator = true;
  }
  if (!keyName && !isAsync3 && !isGenerator) {
    var lastValue = this.value;
    if (this.eatContextual("get") || this.eatContextual("set")) {
      if (this.isClassElementNameStart()) {
        kind = lastValue;
      } else {
        keyName = lastValue;
      }
    }
  }
  if (keyName) {
    node.computed = false;
    node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
    node.key.name = keyName;
    this.finishNode(node.key, "Identifier");
  } else {
    this.parseClassElementName(node);
  }
  if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync3) {
    var isConstructor = !node.static && checkKeyName(node, "constructor");
    var allowsDirectSuper = isConstructor && constructorAllowsSuper;
    if (isConstructor && kind !== "method") {
      this.raise(node.key.start, "Constructor can't have get/set modifier");
    }
    node.kind = isConstructor ? "constructor" : kind;
    this.parseClassMethod(node, isGenerator, isAsync3, allowsDirectSuper);
  } else {
    this.parseClassField(node);
  }
  return node;
};
pp$8.isClassElementNameStart = function() {
  return this.type === types$1.name || this.type === types$1.privateId || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword;
};
pp$8.parseClassElementName = function(element) {
  if (this.type === types$1.privateId) {
    if (this.value === "constructor") {
      this.raise(this.start, "Classes can't have an element named '#constructor'");
    }
    element.computed = false;
    element.key = this.parsePrivateIdent();
  } else {
    this.parsePropertyName(element);
  }
};
pp$8.parseClassMethod = function(method, isGenerator, isAsync3, allowsDirectSuper) {
  var key = method.key;
  if (method.kind === "constructor") {
    if (isGenerator) {
      this.raise(key.start, "Constructor can't be a generator");
    }
    if (isAsync3) {
      this.raise(key.start, "Constructor can't be an async method");
    }
  } else if (method.static && checkKeyName(method, "prototype")) {
    this.raise(key.start, "Classes may not have a static property named prototype");
  }
  var value = method.value = this.parseMethod(isGenerator, isAsync3, allowsDirectSuper);
  if (method.kind === "get" && value.params.length !== 0) {
    this.raiseRecoverable(value.start, "getter should have no params");
  }
  if (method.kind === "set" && value.params.length !== 1) {
    this.raiseRecoverable(value.start, "setter should have exactly one param");
  }
  if (method.kind === "set" && value.params[0].type === "RestElement") {
    this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params");
  }
  return this.finishNode(method, "MethodDefinition");
};
pp$8.parseClassField = function(field) {
  if (checkKeyName(field, "constructor")) {
    this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  } else if (field.static && checkKeyName(field, "prototype")) {
    this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  }
  if (this.eat(types$1.eq)) {
    var scope = this.currentThisScope();
    var inClassFieldInit = scope.inClassFieldInit;
    scope.inClassFieldInit = true;
    field.value = this.parseMaybeAssign();
    scope.inClassFieldInit = inClassFieldInit;
  } else {
    field.value = null;
  }
  this.semicolon();
  return this.finishNode(field, "PropertyDefinition");
};
pp$8.parseClassStaticBlock = function(node) {
  node.body = [];
  var oldLabels = this.labels;
  this.labels = [];
  this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
  while (this.type !== types$1.braceR) {
    var stmt = this.parseStatement(null);
    node.body.push(stmt);
  }
  this.next();
  this.exitScope();
  this.labels = oldLabels;
  return this.finishNode(node, "StaticBlock");
};
pp$8.parseClassId = function(node, isStatement) {
  if (this.type === types$1.name) {
    node.id = this.parseIdent();
    if (isStatement) {
      this.checkLValSimple(node.id, BIND_LEXICAL, false);
    }
  } else {
    if (isStatement === true) {
      this.unexpected();
    }
    node.id = null;
  }
};
pp$8.parseClassSuper = function(node) {
  node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null;
};
pp$8.enterClassBody = function() {
  var element = { declared: /* @__PURE__ */ Object.create(null), used: [] };
  this.privateNameStack.push(element);
  return element.declared;
};
pp$8.exitClassBody = function() {
  var ref2 = this.privateNameStack.pop();
  var declared = ref2.declared;
  var used = ref2.used;
  if (!this.options.checkPrivateFields) {
    return;
  }
  var len = this.privateNameStack.length;
  var parent = len === 0 ? null : this.privateNameStack[len - 1];
  for (var i = 0; i < used.length; ++i) {
    var id = used[i];
    if (!hasOwn(declared, id.name)) {
      if (parent) {
        parent.used.push(id);
      } else {
        this.raiseRecoverable(id.start, "Private field '#" + id.name + "' must be declared in an enclosing class");
      }
    }
  }
};
function isPrivateNameConflicted(privateNameMap, element) {
  var name = element.key.name;
  var curr = privateNameMap[name];
  var next = "true";
  if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
    next = (element.static ? "s" : "i") + element.kind;
  }
  if (curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget") {
    privateNameMap[name] = "true";
    return false;
  } else if (!curr) {
    privateNameMap[name] = next;
    return false;
  } else {
    return true;
  }
}
function checkKeyName(node, name) {
  var computed = node.computed;
  var key = node.key;
  return !computed && (key.type === "Identifier" && key.name === name || key.type === "Literal" && key.value === name);
}
pp$8.parseExportAllDeclaration = function(node, exports2) {
  if (this.options.ecmaVersion >= 11) {
    if (this.eatContextual("as")) {
      node.exported = this.parseModuleExportName();
      this.checkExport(exports2, node.exported, this.lastTokStart);
    } else {
      node.exported = null;
    }
  }
  this.expectContextual("from");
  if (this.type !== types$1.string) {
    this.unexpected();
  }
  node.source = this.parseExprAtom();
  if (this.options.ecmaVersion >= 16) {
    node.attributes = this.parseWithClause();
  }
  this.semicolon();
  return this.finishNode(node, "ExportAllDeclaration");
};
pp$8.parseExport = function(node, exports2) {
  this.next();
  if (this.eat(types$1.star)) {
    return this.parseExportAllDeclaration(node, exports2);
  }
  if (this.eat(types$1._default)) {
    this.checkExport(exports2, "default", this.lastTokStart);
    node.declaration = this.parseExportDefaultDeclaration();
    return this.finishNode(node, "ExportDefaultDeclaration");
  }
  if (this.shouldParseExportStatement()) {
    node.declaration = this.parseExportDeclaration(node);
    if (node.declaration.type === "VariableDeclaration") {
      this.checkVariableExport(exports2, node.declaration.declarations);
    } else {
      this.checkExport(exports2, node.declaration.id, node.declaration.id.start);
    }
    node.specifiers = [];
    node.source = null;
  } else {
    node.declaration = null;
    node.specifiers = this.parseExportSpecifiers(exports2);
    if (this.eatContextual("from")) {
      if (this.type !== types$1.string) {
        this.unexpected();
      }
      node.source = this.parseExprAtom();
      if (this.options.ecmaVersion >= 16) {
        node.attributes = this.parseWithClause();
      }
    } else {
      for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
        var spec = list[i];
        this.checkUnreserved(spec.local);
        this.checkLocalExport(spec.local);
        if (spec.local.type === "Literal") {
          this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
        }
      }
      node.source = null;
    }
    this.semicolon();
  }
  return this.finishNode(node, "ExportNamedDeclaration");
};
pp$8.parseExportDeclaration = function(node) {
  return this.parseStatement(null);
};
pp$8.parseExportDefaultDeclaration = function() {
  var isAsync3;
  if (this.type === types$1._function || (isAsync3 = this.isAsyncFunction())) {
    var fNode = this.startNode();
    this.next();
    if (isAsync3) {
      this.next();
    }
    return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync3);
  } else if (this.type === types$1._class) {
    var cNode = this.startNode();
    return this.parseClass(cNode, "nullableID");
  } else {
    var declaration = this.parseMaybeAssign();
    this.semicolon();
    return declaration;
  }
};
pp$8.checkExport = function(exports2, name, pos) {
  if (!exports2) {
    return;
  }
  if (typeof name !== "string") {
    name = name.type === "Identifier" ? name.name : name.value;
  }
  if (hasOwn(exports2, name)) {
    this.raiseRecoverable(pos, "Duplicate export '" + name + "'");
  }
  exports2[name] = true;
};
pp$8.checkPatternExport = function(exports2, pat) {
  var type = pat.type;
  if (type === "Identifier") {
    this.checkExport(exports2, pat, pat.start);
  } else if (type === "ObjectPattern") {
    for (var i = 0, list = pat.properties; i < list.length; i += 1) {
      var prop = list[i];
      this.checkPatternExport(exports2, prop);
    }
  } else if (type === "ArrayPattern") {
    for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
      var elt = list$1[i$1];
      if (elt) {
        this.checkPatternExport(exports2, elt);
      }
    }
  } else if (type === "Property") {
    this.checkPatternExport(exports2, pat.value);
  } else if (type === "AssignmentPattern") {
    this.checkPatternExport(exports2, pat.left);
  } else if (type === "RestElement") {
    this.checkPatternExport(exports2, pat.argument);
  }
};
pp$8.checkVariableExport = function(exports2, decls) {
  if (!exports2) {
    return;
  }
  for (var i = 0, list = decls; i < list.length; i += 1) {
    var decl = list[i];
    this.checkPatternExport(exports2, decl.id);
  }
};
pp$8.shouldParseExportStatement = function() {
  return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction();
};
pp$8.parseExportSpecifier = function(exports2) {
  var node = this.startNode();
  node.local = this.parseModuleExportName();
  node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
  this.checkExport(
    exports2,
    node.exported,
    node.exported.start
  );
  return this.finishNode(node, "ExportSpecifier");
};
pp$8.parseExportSpecifiers = function(exports2) {
  var nodes = [], first = true;
  this.expect(types$1.braceL);
  while (!this.eat(types$1.braceR)) {
    if (!first) {
      this.expect(types$1.comma);
      if (this.afterTrailingComma(types$1.braceR)) {
        break;
      }
    } else {
      first = false;
    }
    nodes.push(this.parseExportSpecifier(exports2));
  }
  return nodes;
};
pp$8.parseImport = function(node) {
  this.next();
  if (this.type === types$1.string) {
    node.specifiers = empty$1;
    node.source = this.parseExprAtom();
  } else {
    node.specifiers = this.parseImportSpecifiers();
    this.expectContextual("from");
    node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
  }
  if (this.options.ecmaVersion >= 16) {
    node.attributes = this.parseWithClause();
  }
  this.semicolon();
  return this.finishNode(node, "ImportDeclaration");
};
pp$8.parseImportSpecifier = function() {
  var node = this.startNode();
  node.imported = this.parseModuleExportName();
  if (this.eatContextual("as")) {
    node.local = this.parseIdent();
  } else {
    this.checkUnreserved(node.imported);
    node.local = node.imported;
  }
  this.checkLValSimple(node.local, BIND_LEXICAL);
  return this.finishNode(node, "ImportSpecifier");
};
pp$8.parseImportDefaultSpecifier = function() {
  var node = this.startNode();
  node.local = this.parseIdent();
  this.checkLValSimple(node.local, BIND_LEXICAL);
  return this.finishNode(node, "ImportDefaultSpecifier");
};
pp$8.parseImportNamespaceSpecifier = function() {
  var node = this.startNode();
  this.next();
  this.expectContextual("as");
  node.local = this.parseIdent();
  this.checkLValSimple(node.local, BIND_LEXICAL);
  return this.finishNode(node, "ImportNamespaceSpecifier");
};
pp$8.parseImportSpecifiers = function() {
  var nodes = [], first = true;
  if (this.type === types$1.name) {
    nodes.push(this.parseImportDefaultSpecifier());
    if (!this.eat(types$1.comma)) {
      return nodes;
    }
  }
  if (this.type === types$1.star) {
    nodes.push(this.parseImportNamespaceSpecifier());
    return nodes;
  }
  this.expect(types$1.braceL);
  while (!this.eat(types$1.braceR)) {
    if (!first) {
      this.expect(types$1.comma);
      if (this.afterTrailingComma(types$1.braceR)) {
        break;
      }
    } else {
      first = false;
    }
    nodes.push(this.parseImportSpecifier());
  }
  return nodes;
};
pp$8.parseWithClause = function() {
  var nodes = [];
  if (!this.eat(types$1._with)) {
    return nodes;
  }
  this.expect(types$1.braceL);
  var attributeKeys = {};
  var first = true;
  while (!this.eat(types$1.braceR)) {
    if (!first) {
      this.expect(types$1.comma);
      if (this.afterTrailingComma(types$1.braceR)) {
        break;
      }
    } else {
      first = false;
    }
    var attr = this.parseImportAttribute();
    var keyName = attr.key.type === "Identifier" ? attr.key.name : attr.key.value;
    if (hasOwn(attributeKeys, keyName)) {
      this.raiseRecoverable(attr.key.start, "Duplicate attribute key '" + keyName + "'");
    }
    attributeKeys[keyName] = true;
    nodes.push(attr);
  }
  return nodes;
};
pp$8.parseImportAttribute = function() {
  var node = this.startNode();
  node.key = this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never");
  this.expect(types$1.colon);
  if (this.type !== types$1.string) {
    this.unexpected();
  }
  node.value = this.parseExprAtom();
  return this.finishNode(node, "ImportAttribute");
};
pp$8.parseModuleExportName = function() {
  if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
    var stringLiteral = this.parseLiteral(this.value);
    if (loneSurrogate.test(stringLiteral.value)) {
      this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
    }
    return stringLiteral;
  }
  return this.parseIdent(true);
};
pp$8.adaptDirectivePrologue = function(statements) {
  for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
    statements[i].directive = statements[i].expression.raw.slice(1, -1);
  }
};
pp$8.isDirectiveCandidate = function(statement) {
  return this.options.ecmaVersion >= 5 && statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && // Reject parenthesized strings.
  (this.input[statement.start] === '"' || this.input[statement.start] === "'");
};
var pp$7 = Parser.prototype;
pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
  if (this.options.ecmaVersion >= 6 && node) {
    switch (node.type) {
      case "Identifier":
        if (this.inAsync && node.name === "await") {
          this.raise(node.start, "Cannot use 'await' as identifier inside an async function");
        }
        break;
      case "ObjectPattern":
      case "ArrayPattern":
      case "AssignmentPattern":
      case "RestElement":
        break;
      case "ObjectExpression":
        node.type = "ObjectPattern";
        if (refDestructuringErrors) {
          this.checkPatternErrors(refDestructuringErrors, true);
        }
        for (var i = 0, list = node.properties; i < list.length; i += 1) {
          var prop = list[i];
          this.toAssignable(prop, isBinding);
          if (prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")) {
            this.raise(prop.argument.start, "Unexpected token");
          }
        }
        break;
      case "Property":
        if (node.kind !== "init") {
          this.raise(node.key.start, "Object pattern can't contain getter or setter");
        }
        this.toAssignable(node.value, isBinding);
        break;
      case "ArrayExpression":
        node.type = "ArrayPattern";
        if (refDestructuringErrors) {
          this.checkPatternErrors(refDestructuringErrors, true);
        }
        this.toAssignableList(node.elements, isBinding);
        break;
      case "SpreadElement":
        node.type = "RestElement";
        this.toAssignable(node.argument, isBinding);
        if (node.argument.type === "AssignmentPattern") {
          this.raise(node.argument.start, "Rest elements cannot have a default value");
        }
        break;
      case "AssignmentExpression":
        if (node.operator !== "=") {
          this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
        }
        node.type = "AssignmentPattern";
        delete node.operator;
        this.toAssignable(node.left, isBinding);
        break;
      case "ParenthesizedExpression":
        this.toAssignable(node.expression, isBinding, refDestructuringErrors);
        break;
      case "ChainExpression":
        this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
        break;
      case "MemberExpression":
        if (!isBinding) {
          break;
        }
      default:
        this.raise(node.start, "Assigning to rvalue");
    }
  } else if (refDestructuringErrors) {
    this.checkPatternErrors(refDestructuringErrors, true);
  }
  return node;
};
pp$7.toAssignableList = function(exprList, isBinding) {
  var end = exprList.length;
  for (var i = 0; i < end; i++) {
    var elt = exprList[i];
    if (elt) {
      this.toAssignable(elt, isBinding);
    }
  }
  if (end) {
    var last = exprList[end - 1];
    if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") {
      this.unexpected(last.argument.start);
    }
  }
  return exprList;
};
pp$7.parseSpread = function(refDestructuringErrors) {
  var node = this.startNode();
  this.next();
  node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  return this.finishNode(node, "SpreadElement");
};
pp$7.parseRestBinding = function() {
  var node = this.startNode();
  this.next();
  if (this.options.ecmaVersion === 6 && this.type !== types$1.name) {
    this.unexpected();
  }
  node.argument = this.parseBindingAtom();
  return this.finishNode(node, "RestElement");
};
pp$7.parseBindingAtom = function() {
  if (this.options.ecmaVersion >= 6) {
    switch (this.type) {
      case types$1.bracketL:
        var node = this.startNode();
        this.next();
        node.elements = this.parseBindingList(types$1.bracketR, true, true);
        return this.finishNode(node, "ArrayPattern");
      case types$1.braceL:
        return this.parseObj(true);
    }
  }
  return this.parseIdent();
};
pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) {
  var elts = [], first = true;
  while (!this.eat(close)) {
    if (first) {
      first = false;
    } else {
      this.expect(types$1.comma);
    }
    if (allowEmpty && this.type === types$1.comma) {
      elts.push(null);
    } else if (allowTrailingComma && this.afterTrailingComma(close)) {
      break;
    } else if (this.type === types$1.ellipsis) {
      var rest = this.parseRestBinding();
      this.parseBindingListItem(rest);
      elts.push(rest);
      if (this.type === types$1.comma) {
        this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");
      }
      this.expect(close);
      break;
    } else {
      elts.push(this.parseAssignableListItem(allowModifiers));
    }
  }
  return elts;
};
pp$7.parseAssignableListItem = function(allowModifiers) {
  var elem = this.parseMaybeDefault(this.start, this.startLoc);
  this.parseBindingListItem(elem);
  return elem;
};
pp$7.parseBindingListItem = function(param) {
  return param;
};
pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
  left = left || this.parseBindingAtom();
  if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) {
    return left;
  }
  var node = this.startNodeAt(startPos, startLoc);
  node.left = left;
  node.right = this.parseMaybeAssign();
  return this.finishNode(node, "AssignmentPattern");
};
pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
  if (bindingType === void 0) bindingType = BIND_NONE;
  var isBind = bindingType !== BIND_NONE;
  switch (expr.type) {
    case "Identifier":
      if (this.strict && this.reservedWordsStrictBind.test(expr.name)) {
        this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
      }
      if (isBind) {
        if (bindingType === BIND_LEXICAL && expr.name === "let") {
          this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name");
        }
        if (checkClashes) {
          if (hasOwn(checkClashes, expr.name)) {
            this.raiseRecoverable(expr.start, "Argument name clash");
          }
          checkClashes[expr.name] = true;
        }
        if (bindingType !== BIND_OUTSIDE) {
          this.declareName(expr.name, bindingType, expr.start);
        }
      }
      break;
    case "ChainExpression":
      this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
      break;
    case "MemberExpression":
      if (isBind) {
        this.raiseRecoverable(expr.start, "Binding member expression");
      }
      break;
    case "ParenthesizedExpression":
      if (isBind) {
        this.raiseRecoverable(expr.start, "Binding parenthesized expression");
      }
      return this.checkLValSimple(expr.expression, bindingType, checkClashes);
    default:
      this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  }
};
pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
  if (bindingType === void 0) bindingType = BIND_NONE;
  switch (expr.type) {
    case "ObjectPattern":
      for (var i = 0, list = expr.properties; i < list.length; i += 1) {
        var prop = list[i];
        this.checkLValInnerPattern(prop, bindingType, checkClashes);
      }
      break;
    case "ArrayPattern":
      for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
        var elem = list$1[i$1];
        if (elem) {
          this.checkLValInnerPattern(elem, bindingType, checkClashes);
        }
      }
      break;
    default:
      this.checkLValSimple(expr, bindingType, checkClashes);
  }
};
pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  if (bindingType === void 0) bindingType = BIND_NONE;
  switch (expr.type) {
    case "Property":
      this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
      break;
    case "AssignmentPattern":
      this.checkLValPattern(expr.left, bindingType, checkClashes);
      break;
    case "RestElement":
      this.checkLValPattern(expr.argument, bindingType, checkClashes);
      break;
    default:
      this.checkLValPattern(expr, bindingType, checkClashes);
  }
};
var TokContext = function TokContext2(token, isExpr, preserveSpace, override, generator) {
  this.token = token;
  this.isExpr = !!isExpr;
  this.preserveSpace = !!preserveSpace;
  this.override = override;
  this.generator = !!generator;
};
var types3 = {
  b_stat: new TokContext("{", false),
  b_expr: new TokContext("{", true),
  b_tmpl: new TokContext("${", false),
  p_stat: new TokContext("(", false),
  p_expr: new TokContext("(", true),
  q_tmpl: new TokContext("`", true, true, function(p) {
    return p.tryReadTemplateToken();
  }),
  f_stat: new TokContext("function", false),
  f_expr: new TokContext("function", true),
  f_expr_gen: new TokContext("function", true, false, null, true),
  f_gen: new TokContext("function", false, false, null, true)
};
var pp$6 = Parser.prototype;
pp$6.initialContext = function() {
  return [types3.b_stat];
};
pp$6.curContext = function() {
  return this.context[this.context.length - 1];
};
pp$6.braceIsBlock = function(prevType) {
  var parent = this.curContext();
  if (parent === types3.f_expr || parent === types3.f_stat) {
    return true;
  }
  if (prevType === types$1.colon && (parent === types3.b_stat || parent === types3.b_expr)) {
    return !parent.isExpr;
  }
  if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed) {
    return lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
  }
  if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow) {
    return true;
  }
  if (prevType === types$1.braceL) {
    return parent === types3.b_stat;
  }
  if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name) {
    return false;
  }
  return !this.exprAllowed;
};
pp$6.inGeneratorContext = function() {
  for (var i = this.context.length - 1; i >= 1; i--) {
    var context = this.context[i];
    if (context.token === "function") {
      return context.generator;
    }
  }
  return false;
};
pp$6.updateContext = function(prevType) {
  var update, type = this.type;
  if (type.keyword && prevType === types$1.dot) {
    this.exprAllowed = false;
  } else if (update = type.updateContext) {
    update.call(this, prevType);
  } else {
    this.exprAllowed = type.beforeExpr;
  }
};
pp$6.overrideContext = function(tokenCtx) {
  if (this.curContext() !== tokenCtx) {
    this.context[this.context.length - 1] = tokenCtx;
  }
};
types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
  if (this.context.length === 1) {
    this.exprAllowed = true;
    return;
  }
  var out = this.context.pop();
  if (out === types3.b_stat && this.curContext().token === "function") {
    out = this.context.pop();
  }
  this.exprAllowed = !out.isExpr;
};
types$1.braceL.updateContext = function(prevType) {
  this.context.push(this.braceIsBlock(prevType) ? types3.b_stat : types3.b_expr);
  this.exprAllowed = true;
};
types$1.dollarBraceL.updateContext = function() {
  this.context.push(types3.b_tmpl);
  this.exprAllowed = true;
};
types$1.parenL.updateContext = function(prevType) {
  var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
  this.context.push(statementParens ? types3.p_stat : types3.p_expr);
  this.exprAllowed = true;
};
types$1.incDec.updateContext = function() {
};
types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
  if (prevType.beforeExpr && prevType !== types$1._else && !(prevType === types$1.semi && this.curContext() !== types3.p_stat) && !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types3.b_stat)) {
    this.context.push(types3.f_expr);
  } else {
    this.context.push(types3.f_stat);
  }
  this.exprAllowed = false;
};
types$1.colon.updateContext = function() {
  if (this.curContext().token === "function") {
    this.context.pop();
  }
  this.exprAllowed = true;
};
types$1.backQuote.updateContext = function() {
  if (this.curContext() === types3.q_tmpl) {
    this.context.pop();
  } else {
    this.context.push(types3.q_tmpl);
  }
  this.exprAllowed = false;
};
types$1.star.updateContext = function(prevType) {
  if (prevType === types$1._function) {
    var index = this.context.length - 1;
    if (this.context[index] === types3.f_expr) {
      this.context[index] = types3.f_expr_gen;
    } else {
      this.context[index] = types3.f_gen;
    }
  }
  this.exprAllowed = true;
};
types$1.name.updateContext = function(prevType) {
  var allowed = false;
  if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
    if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) {
      allowed = true;
    }
  }
  this.exprAllowed = allowed;
};
var pp$5 = Parser.prototype;
pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") {
    return;
  }
  if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) {
    return;
  }
  var key = prop.key;
  var name;
  switch (key.type) {
    case "Identifier":
      name = key.name;
      break;
    case "Literal":
      name = String(key.value);
      break;
    default:
      return;
  }
  var kind = prop.kind;
  if (this.options.ecmaVersion >= 6) {
    if (name === "__proto__" && kind === "init") {
      if (propHash.proto) {
        if (refDestructuringErrors) {
          if (refDestructuringErrors.doubleProto < 0) {
            refDestructuringErrors.doubleProto = key.start;
          }
        } else {
          this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
        }
      }
      propHash.proto = true;
    }
    return;
  }
  name = "$" + name;
  var other = propHash[name];
  if (other) {
    var redefinition;
    if (kind === "init") {
      redefinition = this.strict && other.init || other.get || other.set;
    } else {
      redefinition = other.init || other[kind];
    }
    if (redefinition) {
      this.raiseRecoverable(key.start, "Redefinition of property");
    }
  } else {
    other = propHash[name] = {
      init: false,
      get: false,
      set: false
    };
  }
  other[kind] = true;
};
pp$5.parseExpression = function(forInit, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  if (this.type === types$1.comma) {
    var node = this.startNodeAt(startPos, startLoc);
    node.expressions = [expr];
    while (this.eat(types$1.comma)) {
      node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors));
    }
    return this.finishNode(node, "SequenceExpression");
  }
  return expr;
};
pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  if (this.isContextual("yield")) {
    if (this.inGenerator) {
      return this.parseYield(forInit);
    } else {
      this.exprAllowed = false;
    }
  }
  var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
  if (refDestructuringErrors) {
    oldParenAssign = refDestructuringErrors.parenthesizedAssign;
    oldTrailingComma = refDestructuringErrors.trailingComma;
    oldDoubleProto = refDestructuringErrors.doubleProto;
    refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  } else {
    refDestructuringErrors = new DestructuringErrors();
    ownDestructuringErrors = true;
  }
  var startPos = this.start, startLoc = this.startLoc;
  if (this.type === types$1.parenL || this.type === types$1.name) {
    this.potentialArrowAt = this.start;
    this.potentialArrowInForAwait = forInit === "await";
  }
  var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  if (afterLeftParse) {
    left = afterLeftParse.call(this, left, startPos, startLoc);
  }
  if (this.type.isAssign) {
    var node = this.startNodeAt(startPos, startLoc);
    node.operator = this.value;
    if (this.type === types$1.eq) {
      left = this.toAssignable(left, false, refDestructuringErrors);
    }
    if (!ownDestructuringErrors) {
      refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
    }
    if (refDestructuringErrors.shorthandAssign >= left.start) {
      refDestructuringErrors.shorthandAssign = -1;
    }
    if (this.type === types$1.eq) {
      this.checkLValPattern(left);
    } else {
      this.checkLValSimple(left);
    }
    node.left = left;
    this.next();
    node.right = this.parseMaybeAssign(forInit);
    if (oldDoubleProto > -1) {
      refDestructuringErrors.doubleProto = oldDoubleProto;
    }
    return this.finishNode(node, "AssignmentExpression");
  } else {
    if (ownDestructuringErrors) {
      this.checkExpressionErrors(refDestructuringErrors, true);
    }
  }
  if (oldParenAssign > -1) {
    refDestructuringErrors.parenthesizedAssign = oldParenAssign;
  }
  if (oldTrailingComma > -1) {
    refDestructuringErrors.trailingComma = oldTrailingComma;
  }
  return left;
};
pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseExprOps(forInit, refDestructuringErrors);
  if (this.checkExpressionErrors(refDestructuringErrors)) {
    return expr;
  }
  if (this.eat(types$1.question)) {
    var node = this.startNodeAt(startPos, startLoc);
    node.test = expr;
    node.consequent = this.parseMaybeAssign();
    this.expect(types$1.colon);
    node.alternate = this.parseMaybeAssign(forInit);
    return this.finishNode(node, "ConditionalExpression");
  }
  return expr;
};
pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
  if (this.checkExpressionErrors(refDestructuringErrors)) {
    return expr;
  }
  return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit);
};
pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  var prec = this.type.binop;
  if (prec != null && (!forInit || this.type !== types$1._in)) {
    if (prec > minPrec) {
      var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
      var coalesce = this.type === types$1.coalesce;
      if (coalesce) {
        prec = types$1.logicalAND.binop;
      }
      var op = this.value;
      this.next();
      var startPos = this.start, startLoc = this.startLoc;
      var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
      var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
      if (logical && this.type === types$1.coalesce || coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND)) {
        this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
      }
      return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit);
    }
  }
  return left;
};
pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  if (right.type === "PrivateIdentifier") {
    this.raise(right.start, "Private identifier can only be left side of binary expression");
  }
  var node = this.startNodeAt(startPos, startLoc);
  node.left = left;
  node.operator = op;
  node.right = right;
  return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression");
};
pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
  var startPos = this.start, startLoc = this.startLoc, expr;
  if (this.isContextual("await") && this.canAwait) {
    expr = this.parseAwait(forInit);
    sawUnary = true;
  } else if (this.type.prefix) {
    var node = this.startNode(), update = this.type === types$1.incDec;
    node.operator = this.value;
    node.prefix = true;
    this.next();
    node.argument = this.parseMaybeUnary(null, true, update, forInit);
    this.checkExpressionErrors(refDestructuringErrors, true);
    if (update) {
      this.checkLValSimple(node.argument);
    } else if (this.strict && node.operator === "delete" && isLocalVariableAccess(node.argument)) {
      this.raiseRecoverable(node.start, "Deleting local variable in strict mode");
    } else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) {
      this.raiseRecoverable(node.start, "Private fields can not be deleted");
    } else {
      sawUnary = true;
    }
    expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  } else if (!sawUnary && this.type === types$1.privateId) {
    if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) {
      this.unexpected();
    }
    expr = this.parsePrivateIdent();
    if (this.type !== types$1._in) {
      this.unexpected();
    }
  } else {
    expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
    if (this.checkExpressionErrors(refDestructuringErrors)) {
      return expr;
    }
    while (this.type.postfix && !this.canInsertSemicolon()) {
      var node$1 = this.startNodeAt(startPos, startLoc);
      node$1.operator = this.value;
      node$1.prefix = false;
      node$1.argument = expr;
      this.checkLValSimple(expr);
      this.next();
      expr = this.finishNode(node$1, "UpdateExpression");
    }
  }
  if (!incDec && this.eat(types$1.starstar)) {
    if (sawUnary) {
      this.unexpected(this.lastTokStart);
    } else {
      return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false);
    }
  } else {
    return expr;
  }
};
function isLocalVariableAccess(node) {
  return node.type === "Identifier" || node.type === "ParenthesizedExpression" && isLocalVariableAccess(node.expression);
}
function isPrivateFieldAccess(node) {
  return node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) || node.type === "ParenthesizedExpression" && isPrivateFieldAccess(node.expression);
}
pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseExprAtom(refDestructuringErrors, forInit);
  if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") {
    return expr;
  }
  var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
  if (refDestructuringErrors && result.type === "MemberExpression") {
    if (refDestructuringErrors.parenthesizedAssign >= result.start) {
      refDestructuringErrors.parenthesizedAssign = -1;
    }
    if (refDestructuringErrors.parenthesizedBind >= result.start) {
      refDestructuringErrors.parenthesizedBind = -1;
    }
    if (refDestructuringErrors.trailingComma >= result.start) {
      refDestructuringErrors.trailingComma = -1;
    }
  }
  return result;
};
pp$5.parseSubscripts = function(base2, startPos, startLoc, noCalls, forInit) {
  var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base2.type === "Identifier" && base2.name === "async" && this.lastTokEnd === base2.end && !this.canInsertSemicolon() && base2.end - base2.start === 5 && this.potentialArrowAt === base2.start;
  var optionalChained = false;
  while (true) {
    var element = this.parseSubscript(base2, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
    if (element.optional) {
      optionalChained = true;
    }
    if (element === base2 || element.type === "ArrowFunctionExpression") {
      if (optionalChained) {
        var chainNode = this.startNodeAt(startPos, startLoc);
        chainNode.expression = element;
        element = this.finishNode(chainNode, "ChainExpression");
      }
      return element;
    }
    base2 = element;
  }
};
pp$5.shouldParseAsyncArrow = function() {
  return !this.canInsertSemicolon() && this.eat(types$1.arrow);
};
pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) {
  return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit);
};
pp$5.parseSubscript = function(base2, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
  var optionalSupported = this.options.ecmaVersion >= 11;
  var optional = optionalSupported && this.eat(types$1.questionDot);
  if (noCalls && optional) {
    this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions");
  }
  var computed = this.eat(types$1.bracketL);
  if (computed || optional && this.type !== types$1.parenL && this.type !== types$1.backQuote || this.eat(types$1.dot)) {
    var node = this.startNodeAt(startPos, startLoc);
    node.object = base2;
    if (computed) {
      node.property = this.parseExpression();
      this.expect(types$1.bracketR);
    } else if (this.type === types$1.privateId && base2.type !== "Super") {
      node.property = this.parsePrivateIdent();
    } else {
      node.property = this.parseIdent(this.options.allowReserved !== "never");
    }
    node.computed = !!computed;
    if (optionalSupported) {
      node.optional = optional;
    }
    base2 = this.finishNode(node, "MemberExpression");
  } else if (!noCalls && this.eat(types$1.parenL)) {
    var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
    this.yieldPos = 0;
    this.awaitPos = 0;
    this.awaitIdentPos = 0;
    var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
    if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) {
      this.checkPatternErrors(refDestructuringErrors, false);
      this.checkYieldAwaitInDefaultParams();
      if (this.awaitIdentPos > 0) {
        this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function");
      }
      this.yieldPos = oldYieldPos;
      this.awaitPos = oldAwaitPos;
      this.awaitIdentPos = oldAwaitIdentPos;
      return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit);
    }
    this.checkExpressionErrors(refDestructuringErrors, true);
    this.yieldPos = oldYieldPos || this.yieldPos;
    this.awaitPos = oldAwaitPos || this.awaitPos;
    this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
    var node$1 = this.startNodeAt(startPos, startLoc);
    node$1.callee = base2;
    node$1.arguments = exprList;
    if (optionalSupported) {
      node$1.optional = optional;
    }
    base2 = this.finishNode(node$1, "CallExpression");
  } else if (this.type === types$1.backQuote) {
    if (optional || optionalChained) {
      this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
    }
    var node$2 = this.startNodeAt(startPos, startLoc);
    node$2.tag = base2;
    node$2.quasi = this.parseTemplate({ isTagged: true });
    base2 = this.finishNode(node$2, "TaggedTemplateExpression");
  }
  return base2;
};
pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) {
  if (this.type === types$1.slash) {
    this.readRegexp();
  }
  var node, canBeArrow = this.potentialArrowAt === this.start;
  switch (this.type) {
    case types$1._super:
      if (!this.allowSuper) {
        this.raise(this.start, "'super' keyword outside a method");
      }
      node = this.startNode();
      this.next();
      if (this.type === types$1.parenL && !this.allowDirectSuper) {
        this.raise(node.start, "super() call outside constructor of a subclass");
      }
      if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL) {
        this.unexpected();
      }
      return this.finishNode(node, "Super");
    case types$1._this:
      node = this.startNode();
      this.next();
      return this.finishNode(node, "ThisExpression");
    case types$1.name:
      var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
      var id = this.parseIdent(false);
      if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
        this.overrideContext(types3.f_expr);
        return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit);
      }
      if (canBeArrow && !this.canInsertSemicolon()) {
        if (this.eat(types$1.arrow)) {
          return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit);
        }
        if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc && (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
          id = this.parseIdent(false);
          if (this.canInsertSemicolon() || !this.eat(types$1.arrow)) {
            this.unexpected();
          }
          return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit);
        }
      }
      return id;
    case types$1.regexp:
      var value = this.value;
      node = this.parseLiteral(value.value);
      node.regex = { pattern: value.pattern, flags: value.flags };
      return node;
    case types$1.num:
    case types$1.string:
      return this.parseLiteral(this.value);
    case types$1._null:
    case types$1._true:
    case types$1._false:
      node = this.startNode();
      node.value = this.type === types$1._null ? null : this.type === types$1._true;
      node.raw = this.type.keyword;
      this.next();
      return this.finishNode(node, "Literal");
    case types$1.parenL:
      var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
      if (refDestructuringErrors) {
        if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) {
          refDestructuringErrors.parenthesizedAssign = start;
        }
        if (refDestructuringErrors.parenthesizedBind < 0) {
          refDestructuringErrors.parenthesizedBind = start;
        }
      }
      return expr;
    case types$1.bracketL:
      node = this.startNode();
      this.next();
      node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
      return this.finishNode(node, "ArrayExpression");
    case types$1.braceL:
      this.overrideContext(types3.b_expr);
      return this.parseObj(false, refDestructuringErrors);
    case types$1._function:
      node = this.startNode();
      this.next();
      return this.parseFunction(node, 0);
    case types$1._class:
      return this.parseClass(this.startNode(), false);
    case types$1._new:
      return this.parseNew();
    case types$1.backQuote:
      return this.parseTemplate();
    case types$1._import:
      if (this.options.ecmaVersion >= 11) {
        return this.parseExprImport(forNew);
      } else {
        return this.unexpected();
      }
    default:
      return this.parseExprAtomDefault();
  }
};
pp$5.parseExprAtomDefault = function() {
  this.unexpected();
};
pp$5.parseExprImport = function(forNew) {
  var node = this.startNode();
  if (this.containsEsc) {
    this.raiseRecoverable(this.start, "Escape sequence in keyword import");
  }
  this.next();
  if (this.type === types$1.parenL && !forNew) {
    return this.parseDynamicImport(node);
  } else if (this.type === types$1.dot) {
    var meta = this.startNodeAt(node.start, node.loc && node.loc.start);
    meta.name = "import";
    node.meta = this.finishNode(meta, "Identifier");
    return this.parseImportMeta(node);
  } else {
    this.unexpected();
  }
};
pp$5.parseDynamicImport = function(node) {
  this.next();
  node.source = this.parseMaybeAssign();
  if (this.options.ecmaVersion >= 16) {
    if (!this.eat(types$1.parenR)) {
      this.expect(types$1.comma);
      if (!this.afterTrailingComma(types$1.parenR)) {
        node.options = this.parseMaybeAssign();
        if (!this.eat(types$1.parenR)) {
          this.expect(types$1.comma);
          if (!this.afterTrailingComma(types$1.parenR)) {
            this.unexpected();
          }
        }
      } else {
        node.options = null;
      }
    } else {
      node.options = null;
    }
  } else {
    if (!this.eat(types$1.parenR)) {
      var errorPos = this.start;
      if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
        this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
      } else {
        this.unexpected(errorPos);
      }
    }
  }
  return this.finishNode(node, "ImportExpression");
};
pp$5.parseImportMeta = function(node) {
  this.next();
  var containsEsc = this.containsEsc;
  node.property = this.parseIdent(true);
  if (node.property.name !== "meta") {
    this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'");
  }
  if (containsEsc) {
    this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters");
  }
  if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) {
    this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module");
  }
  return this.finishNode(node, "MetaProperty");
};
pp$5.parseLiteral = function(value) {
  var node = this.startNode();
  node.value = value;
  node.raw = this.input.slice(this.start, this.end);
  if (node.raw.charCodeAt(node.raw.length - 1) === 110) {
    node.bigint = node.raw.slice(0, -1).replace(/_/g, "");
  }
  this.next();
  return this.finishNode(node, "Literal");
};
pp$5.parseParenExpression = function() {
  this.expect(types$1.parenL);
  var val = this.parseExpression();
  this.expect(types$1.parenR);
  return val;
};
pp$5.shouldParseArrow = function(exprList) {
  return !this.canInsertSemicolon();
};
pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
  var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  if (this.options.ecmaVersion >= 6) {
    this.next();
    var innerStartPos = this.start, innerStartLoc = this.startLoc;
    var exprList = [], first = true, lastIsComma = false;
    var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
    this.yieldPos = 0;
    this.awaitPos = 0;
    while (this.type !== types$1.parenR) {
      first ? first = false : this.expect(types$1.comma);
      if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
        lastIsComma = true;
        break;
      } else if (this.type === types$1.ellipsis) {
        spreadStart = this.start;
        exprList.push(this.parseParenItem(this.parseRestBinding()));
        if (this.type === types$1.comma) {
          this.raiseRecoverable(
            this.start,
            "Comma is not permitted after the rest element"
          );
        }
        break;
      } else {
        exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
      }
    }
    var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
    this.expect(types$1.parenR);
    if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) {
      this.checkPatternErrors(refDestructuringErrors, false);
      this.checkYieldAwaitInDefaultParams();
      this.yieldPos = oldYieldPos;
      this.awaitPos = oldAwaitPos;
      return this.parseParenArrowList(startPos, startLoc, exprList, forInit);
    }
    if (!exprList.length || lastIsComma) {
      this.unexpected(this.lastTokStart);
    }
    if (spreadStart) {
      this.unexpected(spreadStart);
    }
    this.checkExpressionErrors(refDestructuringErrors, true);
    this.yieldPos = oldYieldPos || this.yieldPos;
    this.awaitPos = oldAwaitPos || this.awaitPos;
    if (exprList.length > 1) {
      val = this.startNodeAt(innerStartPos, innerStartLoc);
      val.expressions = exprList;
      this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
    } else {
      val = exprList[0];
    }
  } else {
    val = this.parseParenExpression();
  }
  if (this.options.preserveParens) {
    var par = this.startNodeAt(startPos, startLoc);
    par.expression = val;
    return this.finishNode(par, "ParenthesizedExpression");
  } else {
    return val;
  }
};
pp$5.parseParenItem = function(item) {
  return item;
};
pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
  return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit);
};
var empty = [];
pp$5.parseNew = function() {
  if (this.containsEsc) {
    this.raiseRecoverable(this.start, "Escape sequence in keyword new");
  }
  var node = this.startNode();
  this.next();
  if (this.options.ecmaVersion >= 6 && this.type === types$1.dot) {
    var meta = this.startNodeAt(node.start, node.loc && node.loc.start);
    meta.name = "new";
    node.meta = this.finishNode(meta, "Identifier");
    this.next();
    var containsEsc = this.containsEsc;
    node.property = this.parseIdent(true);
    if (node.property.name !== "target") {
      this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'");
    }
    if (containsEsc) {
      this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters");
    }
    if (!this.allowNewDotTarget) {
      this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block");
    }
    return this.finishNode(node, "MetaProperty");
  }
  var startPos = this.start, startLoc = this.startLoc;
  node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false);
  if (this.eat(types$1.parenL)) {
    node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false);
  } else {
    node.arguments = empty;
  }
  return this.finishNode(node, "NewExpression");
};
pp$5.parseTemplateElement = function(ref2) {
  var isTagged = ref2.isTagged;
  var elem = this.startNode();
  if (this.type === types$1.invalidTemplate) {
    if (!isTagged) {
      this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
    }
    elem.value = {
      raw: this.value.replace(/\r\n?/g, "\n"),
      cooked: null
    };
  } else {
    elem.value = {
      raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
      cooked: this.value
    };
  }
  this.next();
  elem.tail = this.type === types$1.backQuote;
  return this.finishNode(elem, "TemplateElement");
};
pp$5.parseTemplate = function(ref2) {
  if (ref2 === void 0) ref2 = {};
  var isTagged = ref2.isTagged;
  if (isTagged === void 0) isTagged = false;
  var node = this.startNode();
  this.next();
  node.expressions = [];
  var curElt = this.parseTemplateElement({ isTagged });
  node.quasis = [curElt];
  while (!curElt.tail) {
    if (this.type === types$1.eof) {
      this.raise(this.pos, "Unterminated template literal");
    }
    this.expect(types$1.dollarBraceL);
    node.expressions.push(this.parseExpression());
    this.expect(types$1.braceR);
    node.quasis.push(curElt = this.parseTemplateElement({ isTagged }));
  }
  this.next();
  return this.finishNode(node, "TemplateLiteral");
};
pp$5.isAsyncProp = function(prop) {
  return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || this.options.ecmaVersion >= 9 && this.type === types$1.star) && !lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
};
pp$5.parseObj = function(isPattern, refDestructuringErrors) {
  var node = this.startNode(), first = true, propHash = {};
  node.properties = [];
  this.next();
  while (!this.eat(types$1.braceR)) {
    if (!first) {
      this.expect(types$1.comma);
      if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) {
        break;
      }
    } else {
      first = false;
    }
    var prop = this.parseProperty(isPattern, refDestructuringErrors);
    if (!isPattern) {
      this.checkPropClash(prop, propHash, refDestructuringErrors);
    }
    node.properties.push(prop);
  }
  return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
};
pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
  var prop = this.startNode(), isGenerator, isAsync3, startPos, startLoc;
  if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
    if (isPattern) {
      prop.argument = this.parseIdent(false);
      if (this.type === types$1.comma) {
        this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");
      }
      return this.finishNode(prop, "RestElement");
    }
    prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
    if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
      refDestructuringErrors.trailingComma = this.start;
    }
    return this.finishNode(prop, "SpreadElement");
  }
  if (this.options.ecmaVersion >= 6) {
    prop.method = false;
    prop.shorthand = false;
    if (isPattern || refDestructuringErrors) {
      startPos = this.start;
      startLoc = this.startLoc;
    }
    if (!isPattern) {
      isGenerator = this.eat(types$1.star);
    }
  }
  var containsEsc = this.containsEsc;
  this.parsePropertyName(prop);
  if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
    isAsync3 = true;
    isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
    this.parsePropertyName(prop);
  } else {
    isAsync3 = false;
  }
  this.parsePropertyValue(prop, isPattern, isGenerator, isAsync3, startPos, startLoc, refDestructuringErrors, containsEsc);
  return this.finishNode(prop, "Property");
};
pp$5.parseGetterSetter = function(prop) {
  prop.kind = prop.key.name;
  this.parsePropertyName(prop);
  prop.value = this.parseMethod(false);
  var paramCount = prop.kind === "get" ? 0 : 1;
  if (prop.value.params.length !== paramCount) {
    var start = prop.value.start;
    if (prop.kind === "get") {
      this.raiseRecoverable(start, "getter should have no params");
    } else {
      this.raiseRecoverable(start, "setter should have exactly one param");
    }
  } else {
    if (prop.kind === "set" && prop.value.params[0].type === "RestElement") {
      this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params");
    }
  }
};
pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync3, startPos, startLoc, refDestructuringErrors, containsEsc) {
  if ((isGenerator || isAsync3) && this.type === types$1.colon) {
    this.unexpected();
  }
  if (this.eat(types$1.colon)) {
    prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
    prop.kind = "init";
  } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
    if (isPattern) {
      this.unexpected();
    }
    prop.kind = "init";
    prop.method = true;
    prop.value = this.parseMethod(isGenerator, isAsync3);
  } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
    if (isGenerator || isAsync3) {
      this.unexpected();
    }
    this.parseGetterSetter(prop);
  } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
    if (isGenerator || isAsync3) {
      this.unexpected();
    }
    this.checkUnreserved(prop.key);
    if (prop.key.name === "await" && !this.awaitIdentPos) {
      this.awaitIdentPos = startPos;
    }
    prop.kind = "init";
    if (isPattern) {
      prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
    } else if (this.type === types$1.eq && refDestructuringErrors) {
      if (refDestructuringErrors.shorthandAssign < 0) {
        refDestructuringErrors.shorthandAssign = this.start;
      }
      prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
    } else {
      prop.value = this.copyNode(prop.key);
    }
    prop.shorthand = true;
  } else {
    this.unexpected();
  }
};
pp$5.parsePropertyName = function(prop) {
  if (this.options.ecmaVersion >= 6) {
    if (this.eat(types$1.bracketL)) {
      prop.computed = true;
      prop.key = this.parseMaybeAssign();
      this.expect(types$1.bracketR);
      return prop.key;
    } else {
      prop.computed = false;
    }
  }
  return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never");
};
pp$5.initFunction = function(node) {
  node.id = null;
  if (this.options.ecmaVersion >= 6) {
    node.generator = node.expression = false;
  }
  if (this.options.ecmaVersion >= 8) {
    node.async = false;
  }
};
pp$5.parseMethod = function(isGenerator, isAsync3, allowDirectSuper) {
  var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  this.initFunction(node);
  if (this.options.ecmaVersion >= 6) {
    node.generator = isGenerator;
  }
  if (this.options.ecmaVersion >= 8) {
    node.async = !!isAsync3;
  }
  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;
  this.enterScope(functionFlags(isAsync3, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  this.expect(types$1.parenL);
  node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  this.checkYieldAwaitInDefaultParams();
  this.parseFunctionBody(node, false, true, false);
  this.yieldPos = oldYieldPos;
  this.awaitPos = oldAwaitPos;
  this.awaitIdentPos = oldAwaitIdentPos;
  return this.finishNode(node, "FunctionExpression");
};
pp$5.parseArrowExpression = function(node, params, isAsync3, forInit) {
  var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  this.enterScope(functionFlags(isAsync3, false) | SCOPE_ARROW);
  this.initFunction(node);
  if (this.options.ecmaVersion >= 8) {
    node.async = !!isAsync3;
  }
  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;
  node.params = this.toAssignableList(params, true);
  this.parseFunctionBody(node, true, false, forInit);
  this.yieldPos = oldYieldPos;
  this.awaitPos = oldAwaitPos;
  this.awaitIdentPos = oldAwaitIdentPos;
  return this.finishNode(node, "ArrowFunctionExpression");
};
pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
  var isExpression = isArrowFunction && this.type !== types$1.braceL;
  var oldStrict = this.strict, useStrict = false;
  if (isExpression) {
    node.body = this.parseMaybeAssign(forInit);
    node.expression = true;
    this.checkParams(node, false);
  } else {
    var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
    if (!oldStrict || nonSimple) {
      useStrict = this.strictDirective(this.end);
      if (useStrict && nonSimple) {
        this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list");
      }
    }
    var oldLabels = this.labels;
    this.labels = [];
    if (useStrict) {
      this.strict = true;
    }
    this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
    if (this.strict && node.id) {
      this.checkLValSimple(node.id, BIND_OUTSIDE);
    }
    node.body = this.parseBlock(false, void 0, useStrict && !oldStrict);
    node.expression = false;
    this.adaptDirectivePrologue(node.body.body);
    this.labels = oldLabels;
  }
  this.exitScope();
};
pp$5.isSimpleParamList = function(params) {
  for (var i = 0, list = params; i < list.length; i += 1) {
    var param = list[i];
    if (param.type !== "Identifier") {
      return false;
    }
  }
  return true;
};
pp$5.checkParams = function(node, allowDuplicates) {
  var nameHash = /* @__PURE__ */ Object.create(null);
  for (var i = 0, list = node.params; i < list.length; i += 1) {
    var param = list[i];
    this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  }
};
pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  var elts = [], first = true;
  while (!this.eat(close)) {
    if (!first) {
      this.expect(types$1.comma);
      if (allowTrailingComma && this.afterTrailingComma(close)) {
        break;
      }
    } else {
      first = false;
    }
    var elt = void 0;
    if (allowEmpty && this.type === types$1.comma) {
      elt = null;
    } else if (this.type === types$1.ellipsis) {
      elt = this.parseSpread(refDestructuringErrors);
      if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0) {
        refDestructuringErrors.trailingComma = this.start;
      }
    } else {
      elt = this.parseMaybeAssign(false, refDestructuringErrors);
    }
    elts.push(elt);
  }
  return elts;
};
pp$5.checkUnreserved = function(ref2) {
  var start = ref2.start;
  var end = ref2.end;
  var name = ref2.name;
  if (this.inGenerator && name === "yield") {
    this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator");
  }
  if (this.inAsync && name === "await") {
    this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function");
  }
  if (this.currentThisScope().inClassFieldInit && name === "arguments") {
    this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer");
  }
  if (this.inClassStaticBlock && (name === "arguments" || name === "await")) {
    this.raise(start, "Cannot use " + name + " in class static initialization block");
  }
  if (this.keywords.test(name)) {
    this.raise(start, "Unexpected keyword '" + name + "'");
  }
  if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) {
    return;
  }
  var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  if (re.test(name)) {
    if (!this.inAsync && name === "await") {
      this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function");
    }
    this.raiseRecoverable(start, "The keyword '" + name + "' is reserved");
  }
};
pp$5.parseIdent = function(liberal) {
  var node = this.parseIdentNode();
  this.next(!!liberal);
  this.finishNode(node, "Identifier");
  if (!liberal) {
    this.checkUnreserved(node);
    if (node.name === "await" && !this.awaitIdentPos) {
      this.awaitIdentPos = node.start;
    }
  }
  return node;
};
pp$5.parseIdentNode = function() {
  var node = this.startNode();
  if (this.type === types$1.name) {
    node.name = this.value;
  } else if (this.type.keyword) {
    node.name = this.type.keyword;
    if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
      this.context.pop();
    }
    this.type = types$1.name;
  } else {
    this.unexpected();
  }
  return node;
};
pp$5.parsePrivateIdent = function() {
  var node = this.startNode();
  if (this.type === types$1.privateId) {
    node.name = this.value;
  } else {
    this.unexpected();
  }
  this.next();
  this.finishNode(node, "PrivateIdentifier");
  if (this.options.checkPrivateFields) {
    if (this.privateNameStack.length === 0) {
      this.raise(node.start, "Private field '#" + node.name + "' must be declared in an enclosing class");
    } else {
      this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
    }
  }
  return node;
};
pp$5.parseYield = function(forInit) {
  if (!this.yieldPos) {
    this.yieldPos = this.start;
  }
  var node = this.startNode();
  this.next();
  if (this.type === types$1.semi || this.canInsertSemicolon() || this.type !== types$1.star && !this.type.startsExpr) {
    node.delegate = false;
    node.argument = null;
  } else {
    node.delegate = this.eat(types$1.star);
    node.argument = this.parseMaybeAssign(forInit);
  }
  return this.finishNode(node, "YieldExpression");
};
pp$5.parseAwait = function(forInit) {
  if (!this.awaitPos) {
    this.awaitPos = this.start;
  }
  var node = this.startNode();
  this.next();
  node.argument = this.parseMaybeUnary(null, true, false, forInit);
  return this.finishNode(node, "AwaitExpression");
};
var pp$4 = Parser.prototype;
pp$4.raise = function(pos, message) {
  var loc = getLineInfo(this.input, pos);
  message += " (" + loc.line + ":" + loc.column + ")";
  var err = new SyntaxError(message);
  err.pos = pos;
  err.loc = loc;
  err.raisedAt = this.pos;
  throw err;
};
pp$4.raiseRecoverable = pp$4.raise;
pp$4.curPosition = function() {
  if (this.options.locations) {
    return new Position(this.curLine, this.pos - this.lineStart);
  }
};
var pp$3 = Parser.prototype;
var Scope = function Scope2(flags) {
  this.flags = flags;
  this.var = [];
  this.lexical = [];
  this.functions = [];
  this.inClassFieldInit = false;
};
pp$3.enterScope = function(flags) {
  this.scopeStack.push(new Scope(flags));
};
pp$3.exitScope = function() {
  this.scopeStack.pop();
};
pp$3.treatFunctionsAsVarInScope = function(scope) {
  return scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_TOP;
};
pp$3.declareName = function(name, bindingType, pos) {
  var redeclared = false;
  if (bindingType === BIND_LEXICAL) {
    var scope = this.currentScope();
    redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
    scope.lexical.push(name);
    if (this.inModule && scope.flags & SCOPE_TOP) {
      delete this.undefinedExports[name];
    }
  } else if (bindingType === BIND_SIMPLE_CATCH) {
    var scope$1 = this.currentScope();
    scope$1.lexical.push(name);
  } else if (bindingType === BIND_FUNCTION) {
    var scope$2 = this.currentScope();
    if (this.treatFunctionsAsVar) {
      redeclared = scope$2.lexical.indexOf(name) > -1;
    } else {
      redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1;
    }
    scope$2.functions.push(name);
  } else {
    for (var i = this.scopeStack.length - 1; i >= 0; --i) {
      var scope$3 = this.scopeStack[i];
      if (scope$3.lexical.indexOf(name) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH && scope$3.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
        redeclared = true;
        break;
      }
      scope$3.var.push(name);
      if (this.inModule && scope$3.flags & SCOPE_TOP) {
        delete this.undefinedExports[name];
      }
      if (scope$3.flags & SCOPE_VAR) {
        break;
      }
    }
  }
  if (redeclared) {
    this.raiseRecoverable(pos, "Identifier '" + name + "' has already been declared");
  }
};
pp$3.checkLocalExport = function(id) {
  if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) {
    this.undefinedExports[id.name] = id;
  }
};
pp$3.currentScope = function() {
  return this.scopeStack[this.scopeStack.length - 1];
};
pp$3.currentVarScope = function() {
  for (var i = this.scopeStack.length - 1; ; i--) {
    var scope = this.scopeStack[i];
    if (scope.flags & SCOPE_VAR) {
      return scope;
    }
  }
};
pp$3.currentThisScope = function() {
  for (var i = this.scopeStack.length - 1; ; i--) {
    var scope = this.scopeStack[i];
    if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) {
      return scope;
    }
  }
};
var Node = function Node2(parser, pos, loc) {
  this.type = "";
  this.start = pos;
  this.end = 0;
  if (parser.options.locations) {
    this.loc = new SourceLocation(parser, loc);
  }
  if (parser.options.directSourceFile) {
    this.sourceFile = parser.options.directSourceFile;
  }
  if (parser.options.ranges) {
    this.range = [pos, 0];
  }
};
var pp$2 = Parser.prototype;
pp$2.startNode = function() {
  return new Node(this, this.start, this.startLoc);
};
pp$2.startNodeAt = function(pos, loc) {
  return new Node(this, pos, loc);
};
function finishNodeAt(node, type, pos, loc) {
  node.type = type;
  node.end = pos;
  if (this.options.locations) {
    node.loc.end = loc;
  }
  if (this.options.ranges) {
    node.range[1] = pos;
  }
  return node;
}
pp$2.finishNode = function(node, type) {
  return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc);
};
pp$2.finishNodeAt = function(node, type, pos, loc) {
  return finishNodeAt.call(this, node, type, pos, loc);
};
pp$2.copyNode = function(node) {
  var newNode = new Node(this, node.start, this.startLoc);
  for (var prop in node) {
    newNode[prop] = node[prop];
  }
  return newNode;
};
var scriptValuesAddedInUnicode = "Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz";
var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
var ecma11BinaryProperties = ecma10BinaryProperties;
var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
var ecma13BinaryProperties = ecma12BinaryProperties;
var ecma14BinaryProperties = ecma13BinaryProperties;
var unicodeBinaryProperties = {
  9: ecma9BinaryProperties,
  10: ecma10BinaryProperties,
  11: ecma11BinaryProperties,
  12: ecma12BinaryProperties,
  13: ecma13BinaryProperties,
  14: ecma14BinaryProperties
};
var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji";
var unicodeBinaryPropertiesOfStrings = {
  9: "",
  10: "",
  11: "",
  12: "",
  13: "",
  14: ecma14BinaryPropertiesOfStrings
};
var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
var ecma14ScriptValues = ecma13ScriptValues + " " + scriptValuesAddedInUnicode;
var unicodeScriptValues = {
  9: ecma9ScriptValues,
  10: ecma10ScriptValues,
  11: ecma11ScriptValues,
  12: ecma12ScriptValues,
  13: ecma13ScriptValues,
  14: ecma14ScriptValues
};
var data = {};
function buildUnicodeData(ecmaVersion) {
  var d2 = data[ecmaVersion] = {
    binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
    binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion]),
    nonBinary: {
      General_Category: wordsRegexp(unicodeGeneralCategoryValues),
      Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
    }
  };
  d2.nonBinary.Script_Extensions = d2.nonBinary.Script;
  d2.nonBinary.gc = d2.nonBinary.General_Category;
  d2.nonBinary.sc = d2.nonBinary.Script;
  d2.nonBinary.scx = d2.nonBinary.Script_Extensions;
}
for (i = 0, list = [9, 10, 11, 12, 13, 14]; i < list.length; i += 1) {
  ecmaVersion = list[i];
  buildUnicodeData(ecmaVersion);
}
var ecmaVersion;
var i;
var list;
var pp$1 = Parser.prototype;
var BranchID = function BranchID2(parent, base2) {
  this.parent = parent;
  this.base = base2 || this;
};
BranchID.prototype.separatedFrom = function separatedFrom(alt) {
  for (var self2 = this; self2; self2 = self2.parent) {
    for (var other = alt; other; other = other.parent) {
      if (self2.base === other.base && self2 !== other) {
        return true;
      }
    }
  }
  return false;
};
BranchID.prototype.sibling = function sibling() {
  return new BranchID(this.parent, this.base);
};
var RegExpValidationState = function RegExpValidationState2(parser) {
  this.parser = parser;
  this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : "");
  this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion];
  this.source = "";
  this.flags = "";
  this.start = 0;
  this.switchU = false;
  this.switchV = false;
  this.switchN = false;
  this.pos = 0;
  this.lastIntValue = 0;
  this.lastStringValue = "";
  this.lastAssertionIsQuantifiable = false;
  this.numCapturingParens = 0;
  this.maxBackReference = 0;
  this.groupNames = /* @__PURE__ */ Object.create(null);
  this.backReferenceNames = [];
  this.branchID = null;
};
RegExpValidationState.prototype.reset = function reset2(start, pattern, flags) {
  var unicodeSets = flags.indexOf("v") !== -1;
  var unicode = flags.indexOf("u") !== -1;
  this.start = start | 0;
  this.source = pattern + "";
  this.flags = flags;
  if (unicodeSets && this.parser.options.ecmaVersion >= 15) {
    this.switchU = true;
    this.switchV = true;
    this.switchN = true;
  } else {
    this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
    this.switchV = false;
    this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  }
};
RegExpValidationState.prototype.raise = function raise(message) {
  this.parser.raiseRecoverable(this.start, "Invalid regular expression: /" + this.source + "/: " + message);
};
RegExpValidationState.prototype.at = function at(i, forceU) {
  if (forceU === void 0) forceU = false;
  var s = this.source;
  var l = s.length;
  if (i >= l) {
    return -1;
  }
  var c = s.charCodeAt(i);
  if (!(forceU || this.switchU) || c <= 55295 || c >= 57344 || i + 1 >= l) {
    return c;
  }
  var next = s.charCodeAt(i + 1);
  return next >= 56320 && next <= 57343 ? (c << 10) + next - 56613888 : c;
};
RegExpValidationState.prototype.nextIndex = function nextIndex(i, forceU) {
  if (forceU === void 0) forceU = false;
  var s = this.source;
  var l = s.length;
  if (i >= l) {
    return l;
  }
  var c = s.charCodeAt(i), next;
  if (!(forceU || this.switchU) || c <= 55295 || c >= 57344 || i + 1 >= l || (next = s.charCodeAt(i + 1)) < 56320 || next > 57343) {
    return i + 1;
  }
  return i + 2;
};
RegExpValidationState.prototype.current = function current(forceU) {
  if (forceU === void 0) forceU = false;
  return this.at(this.pos, forceU);
};
RegExpValidationState.prototype.lookahead = function lookahead(forceU) {
  if (forceU === void 0) forceU = false;
  return this.at(this.nextIndex(this.pos, forceU), forceU);
};
RegExpValidationState.prototype.advance = function advance(forceU) {
  if (forceU === void 0) forceU = false;
  this.pos = this.nextIndex(this.pos, forceU);
};
RegExpValidationState.prototype.eat = function eat(ch, forceU) {
  if (forceU === void 0) forceU = false;
  if (this.current(forceU) === ch) {
    this.advance(forceU);
    return true;
  }
  return false;
};
RegExpValidationState.prototype.eatChars = function eatChars(chs, forceU) {
  if (forceU === void 0) forceU = false;
  var pos = this.pos;
  for (var i = 0, list = chs; i < list.length; i += 1) {
    var ch = list[i];
    var current2 = this.at(pos, forceU);
    if (current2 === -1 || current2 !== ch) {
      return false;
    }
    pos = this.nextIndex(pos, forceU);
  }
  this.pos = pos;
  return true;
};
pp$1.validateRegExpFlags = function(state) {
  var validFlags = state.validFlags;
  var flags = state.flags;
  var u = false;
  var v2 = false;
  for (var i = 0; i < flags.length; i++) {
    var flag = flags.charAt(i);
    if (validFlags.indexOf(flag) === -1) {
      this.raise(state.start, "Invalid regular expression flag");
    }
    if (flags.indexOf(flag, i + 1) > -1) {
      this.raise(state.start, "Duplicate regular expression flag");
    }
    if (flag === "u") {
      u = true;
    }
    if (flag === "v") {
      v2 = true;
    }
  }
  if (this.options.ecmaVersion >= 15 && u && v2) {
    this.raise(state.start, "Invalid regular expression flag");
  }
};
function hasProp(obj) {
  for (var _2 in obj) {
    return true;
  }
  return false;
}
pp$1.validateRegExpPattern = function(state) {
  this.regexp_pattern(state);
  if (!state.switchN && this.options.ecmaVersion >= 9 && hasProp(state.groupNames)) {
    state.switchN = true;
    this.regexp_pattern(state);
  }
};
pp$1.regexp_pattern = function(state) {
  state.pos = 0;
  state.lastIntValue = 0;
  state.lastStringValue = "";
  state.lastAssertionIsQuantifiable = false;
  state.numCapturingParens = 0;
  state.maxBackReference = 0;
  state.groupNames = /* @__PURE__ */ Object.create(null);
  state.backReferenceNames.length = 0;
  state.branchID = null;
  this.regexp_disjunction(state);
  if (state.pos !== state.source.length) {
    if (state.eat(
      41
      /* ) */
    )) {
      state.raise("Unmatched ')'");
    }
    if (state.eat(
      93
      /* ] */
    ) || state.eat(
      125
      /* } */
    )) {
      state.raise("Lone quantifier brackets");
    }
  }
  if (state.maxBackReference > state.numCapturingParens) {
    state.raise("Invalid escape");
  }
  for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
    var name = list[i];
    if (!state.groupNames[name]) {
      state.raise("Invalid named capture referenced");
    }
  }
};
pp$1.regexp_disjunction = function(state) {
  var trackDisjunction = this.options.ecmaVersion >= 16;
  if (trackDisjunction) {
    state.branchID = new BranchID(state.branchID, null);
  }
  this.regexp_alternative(state);
  while (state.eat(
    124
    /* | */
  )) {
    if (trackDisjunction) {
      state.branchID = state.branchID.sibling();
    }
    this.regexp_alternative(state);
  }
  if (trackDisjunction) {
    state.branchID = state.branchID.parent;
  }
  if (this.regexp_eatQuantifier(state, true)) {
    state.raise("Nothing to repeat");
  }
  if (state.eat(
    123
    /* { */
  )) {
    state.raise("Lone quantifier brackets");
  }
};
pp$1.regexp_alternative = function(state) {
  while (state.pos < state.source.length && this.regexp_eatTerm(state)) {
  }
};
pp$1.regexp_eatTerm = function(state) {
  if (this.regexp_eatAssertion(state)) {
    if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
      if (state.switchU) {
        state.raise("Invalid quantifier");
      }
    }
    return true;
  }
  if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
    this.regexp_eatQuantifier(state);
    return true;
  }
  return false;
};
pp$1.regexp_eatAssertion = function(state) {
  var start = state.pos;
  state.lastAssertionIsQuantifiable = false;
  if (state.eat(
    94
    /* ^ */
  ) || state.eat(
    36
    /* $ */
  )) {
    return true;
  }
  if (state.eat(
    92
    /* \ */
  )) {
    if (state.eat(
      66
      /* B */
    ) || state.eat(
      98
      /* b */
    )) {
      return true;
    }
    state.pos = start;
  }
  if (state.eat(
    40
    /* ( */
  ) && state.eat(
    63
    /* ? */
  )) {
    var lookbehind = false;
    if (this.options.ecmaVersion >= 9) {
      lookbehind = state.eat(
        60
        /* < */
      );
    }
    if (state.eat(
      61
      /* = */
    ) || state.eat(
      33
      /* ! */
    )) {
      this.regexp_disjunction(state);
      if (!state.eat(
        41
        /* ) */
      )) {
        state.raise("Unterminated group");
      }
      state.lastAssertionIsQuantifiable = !lookbehind;
      return true;
    }
  }
  state.pos = start;
  return false;
};
pp$1.regexp_eatQuantifier = function(state, noError) {
  if (noError === void 0) noError = false;
  if (this.regexp_eatQuantifierPrefix(state, noError)) {
    state.eat(
      63
      /* ? */
    );
    return true;
  }
  return false;
};
pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
  return state.eat(
    42
    /* * */
  ) || state.eat(
    43
    /* + */
  ) || state.eat(
    63
    /* ? */
  ) || this.regexp_eatBracedQuantifier(state, noError);
};
pp$1.regexp_eatBracedQuantifier = function(state, noError) {
  var start = state.pos;
  if (state.eat(
    123
    /* { */
  )) {
    var min = 0, max = -1;
    if (this.regexp_eatDecimalDigits(state)) {
      min = state.lastIntValue;
      if (state.eat(
        44
        /* , */
      ) && this.regexp_eatDecimalDigits(state)) {
        max = state.lastIntValue;
      }
      if (state.eat(
        125
        /* } */
      )) {
        if (max !== -1 && max < min && !noError) {
          state.raise("numbers out of order in {} quantifier");
        }
        return true;
      }
    }
    if (state.switchU && !noError) {
      state.raise("Incomplete quantifier");
    }
    state.pos = start;
  }
  return false;
};
pp$1.regexp_eatAtom = function(state) {
  return this.regexp_eatPatternCharacters(state) || state.eat(
    46
    /* . */
  ) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state);
};
pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
  var start = state.pos;
  if (state.eat(
    92
    /* \ */
  )) {
    if (this.regexp_eatAtomEscape(state)) {
      return true;
    }
    state.pos = start;
  }
  return false;
};
pp$1.regexp_eatUncapturingGroup = function(state) {
  var start = state.pos;
  if (state.eat(
    40
    /* ( */
  )) {
    if (state.eat(
      63
      /* ? */
    )) {
      if (this.options.ecmaVersion >= 16) {
        var addModifiers = this.regexp_eatModifiers(state);
        var hasHyphen = state.eat(
          45
          /* - */
        );
        if (addModifiers || hasHyphen) {
          for (var i = 0; i < addModifiers.length; i++) {
            var modifier = addModifiers.charAt(i);
            if (addModifiers.indexOf(modifier, i + 1) > -1) {
              state.raise("Duplicate regular expression modifiers");
            }
          }
          if (hasHyphen) {
            var removeModifiers = this.regexp_eatModifiers(state);
            if (!addModifiers && !removeModifiers && state.current() === 58) {
              state.raise("Invalid regular expression modifiers");
            }
            for (var i$1 = 0; i$1 < removeModifiers.length; i$1++) {
              var modifier$1 = removeModifiers.charAt(i$1);
              if (removeModifiers.indexOf(modifier$1, i$1 + 1) > -1 || addModifiers.indexOf(modifier$1) > -1) {
                state.raise("Duplicate regular expression modifiers");
              }
            }
          }
        }
      }
      if (state.eat(
        58
        /* : */
      )) {
        this.regexp_disjunction(state);
        if (state.eat(
          41
          /* ) */
        )) {
          return true;
        }
        state.raise("Unterminated group");
      }
    }
    state.pos = start;
  }
  return false;
};
pp$1.regexp_eatCapturingGroup = function(state) {
  if (state.eat(
    40
    /* ( */
  )) {
    if (this.options.ecmaVersion >= 9) {
      this.regexp_groupSpecifier(state);
    } else if (state.current() === 63) {
      state.raise("Invalid group");
    }
    this.regexp_disjunction(state);
    if (state.eat(
      41
      /* ) */
    )) {
      state.numCapturingParens += 1;
      return true;
    }
    state.raise("Unterminated group");
  }
  return false;
};
pp$1.regexp_eatModifiers = function(state) {
  var modifiers = "";
  var ch = 0;
  while ((ch = state.current()) !== -1 && isRegularExpressionModifier(ch)) {
    modifiers += codePointToString(ch);
    state.advance();
  }
  return modifiers;
};
function isRegularExpressionModifier(ch) {
  return ch === 105 || ch === 109 || ch === 115;
}
pp$1.regexp_eatExtendedAtom = function(state) {
  return state.eat(
    46
    /* . */
  ) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state);
};
pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
  if (this.regexp_eatBracedQuantifier(state, true)) {
    state.raise("Nothing to repeat");
  }
  return false;
};
pp$1.regexp_eatSyntaxCharacter = function(state) {
  var ch = state.current();
  if (isSyntaxCharacter(ch)) {
    state.lastIntValue = ch;
    state.advance();
    return true;
  }
  return false;
};
function isSyntaxCharacter(ch) {
  return ch === 36 || ch >= 40 && ch <= 43 || ch === 46 || ch === 63 || ch >= 91 && ch <= 94 || ch >= 123 && ch <= 125;
}
pp$1.regexp_eatPatternCharacters = function(state) {
  var start = state.pos;
  var ch = 0;
  while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
    state.advance();
  }
  return state.pos !== start;
};
pp$1.regexp_eatExtendedPatternCharacter = function(state) {
  var ch = state.current();
  if (ch !== -1 && ch !== 36 && !(ch >= 40 && ch <= 43) && ch !== 46 && ch !== 63 && ch !== 91 && ch !== 94 && ch !== 124) {
    state.advance();
    return true;
  }
  return false;
};
pp$1.regexp_groupSpecifier = function(state) {
  if (state.eat(
    63
    /* ? */
  )) {
    if (!this.regexp_eatGroupName(state)) {
      state.raise("Invalid group");
    }
    var trackDisjunction = this.options.ecmaVersion >= 16;
    var known = state.groupNames[state.lastStringValue];
    if (known) {
      if (trackDisjunction) {
        for (var i = 0, list = known; i < list.length; i += 1) {
          var altID = list[i];
          if (!altID.separatedFrom(state.branchID)) {
            state.raise("Duplicate capture group name");
          }
        }
      } else {
        state.raise("Duplicate capture group name");
      }
    }
    if (trackDisjunction) {
      (known || (state.groupNames[state.lastStringValue] = [])).push(state.branchID);
    } else {
      state.groupNames[state.lastStringValue] = true;
    }
  }
};
pp$1.regexp_eatGroupName = function(state) {
  state.lastStringValue = "";
  if (state.eat(
    60
    /* < */
  )) {
    if (this.regexp_eatRegExpIdentifierName(state) && state.eat(
      62
      /* > */
    )) {
      return true;
    }
    state.raise("Invalid capture group name");
  }
  return false;
};
pp$1.regexp_eatRegExpIdentifierName = function(state) {
  state.lastStringValue = "";
  if (this.regexp_eatRegExpIdentifierStart(state)) {
    state.lastStringValue += codePointToString(state.lastIntValue);
    while (this.regexp_eatRegExpIdentifierPart(state)) {
      state.lastStringValue += codePointToString(state.lastIntValue);
    }
    return true;
  }
  return false;
};
pp$1.regexp_eatRegExpIdentifierStart = function(state) {
  var start = state.pos;
  var forceU = this.options.ecmaVersion >= 11;
  var ch = state.current(forceU);
  state.advance(forceU);
  if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
    ch = state.lastIntValue;
  }
  if (isRegExpIdentifierStart(ch)) {
    state.lastIntValue = ch;
    return true;
  }
  state.pos = start;
  return false;
};
function isRegExpIdentifierStart(ch) {
  return isIdentifierStart(ch, true) || ch === 36 || ch === 95;
}
pp$1.regexp_eatRegExpIdentifierPart = function(state) {
  var start = state.pos;
  var forceU = this.options.ecmaVersion >= 11;
  var ch = state.current(forceU);
  state.advance(forceU);
  if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
    ch = state.lastIntValue;
  }
  if (isRegExpIdentifierPart(ch)) {
    state.lastIntValue = ch;
    return true;
  }
  state.pos = start;
  return false;
};
function isRegExpIdentifierPart(ch) {
  return isIdentifierChar(ch, true) || ch === 36 || ch === 95 || ch === 8204 || ch === 8205;
}
pp$1.regexp_eatAtomEscape = function(state) {
  if (this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || state.switchN && this.regexp_eatKGroupName(state)) {
    return true;
  }
  if (state.switchU) {
    if (state.current() === 99) {
      state.raise("Invalid unicode escape");
    }
    state.raise("Invalid escape");
  }
  return false;
};
pp$1.regexp_eatBackReference = function(state) {
  var start = state.pos;
  if (this.regexp_eatDecimalEscape(state)) {
    var n = state.lastIntValue;
    if (state.switchU) {
      if (n > state.maxBackReference) {
        state.maxBackReference = n;
      }
      return true;
    }
    if (n <= state.numCapturingParens) {
      return true;
    }
    state.pos = start;
  }
  return false;
};
pp$1.regexp_eatKGroupName = function(state) {
  if (state.eat(
    107
    /* k */
  )) {
    if (this.regexp_eatGroupName(state)) {
      state.backReferenceNames.push(state.lastStringValue);
      return true;
    }
    state.raise("Invalid named reference");
  }
  return false;
};
pp$1.regexp_eatCharacterEscape = function(state) {
  return this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || !state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state) || this.regexp_eatIdentityEscape(state);
};
pp$1.regexp_eatCControlLetter = function(state) {
  var start = state.pos;
  if (state.eat(
    99
    /* c */
  )) {
    if (this.regexp_eatControlLetter(state)) {
      return true;
    }
    state.pos = start;
  }
  return false;
};
pp$1.regexp_eatZero = function(state) {
  if (state.current() === 48 && !isDecimalDigit(state.lookahead())) {
    state.lastIntValue = 0;
    state.advance();
    return true;
  }
  return false;
};
pp$1.regexp_eatControlEscape = function(state) {
  var ch = state.current();
  if (ch === 116) {
    state.lastIntValue = 9;
    state.advance();
    return true;
  }
  if (ch === 110) {
    state.lastIntValue = 10;
    state.advance();
    return true;
  }
  if (ch === 118) {
    state.lastIntValue = 11;
    state.advance();
    return true;
  }
  if (ch === 102) {
    state.lastIntValue = 12;
    state.advance();
    return true;
  }
  if (ch === 114) {
    state.lastIntValue = 13;
    state.advance();
    return true;
  }
  return false;
};
pp$1.regexp_eatControlLetter = function(state) {
  var ch = state.current();
  if (isControlLetter(ch)) {
    state.lastIntValue = ch % 32;
    state.advance();
    return true;
  }
  return false;
};
function isControlLetter(ch) {
  return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122;
}
pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  if (forceU === void 0) forceU = false;
  var start = state.pos;
  var switchU = forceU || state.switchU;
  if (state.eat(
    117
    /* u */
  )) {
    if (this.regexp_eatFixedHexDigits(state, 4)) {
      var lead = state.lastIntValue;
      if (switchU && lead >= 55296 && lead <= 56319) {
        var leadSurrogateEnd = state.pos;
        if (state.eat(
          92
          /* \ */
        ) && state.eat(
          117
          /* u */
        ) && this.regexp_eatFixedHexDigits(state, 4)) {
          var trail = state.lastIntValue;
          if (trail >= 56320 && trail <= 57343) {
            state.lastIntValue = (lead - 55296) * 1024 + (trail - 56320) + 65536;
            return true;
          }
        }
        state.pos = leadSurrogateEnd;
        state.lastIntValue = lead;
      }
      return true;
    }
    if (switchU && state.eat(
      123
      /* { */
    ) && this.regexp_eatHexDigits(state) && state.eat(
      125
      /* } */
    ) && isValidUnicode(state.lastIntValue)) {
      return true;
    }
    if (switchU) {
      state.raise("Invalid unicode escape");
    }
    state.pos = start;
  }
  return false;
};
function isValidUnicode(ch) {
  return ch >= 0 && ch <= 1114111;
}
pp$1.regexp_eatIdentityEscape = function(state) {
  if (state.switchU) {
    if (this.regexp_eatSyntaxCharacter(state)) {
      return true;
    }
    if (state.eat(
      47
      /* / */
    )) {
      state.lastIntValue = 47;
      return true;
    }
    return false;
  }
  var ch = state.current();
  if (ch !== 99 && (!state.switchN || ch !== 107)) {
    state.lastIntValue = ch;
    state.advance();
    return true;
  }
  return false;
};
pp$1.regexp_eatDecimalEscape = function(state) {
  state.lastIntValue = 0;
  var ch = state.current();
  if (ch >= 49 && ch <= 57) {
    do {
      state.lastIntValue = 10 * state.lastIntValue + (ch - 48);
      state.advance();
    } while ((ch = state.current()) >= 48 && ch <= 57);
    return true;
  }
  return false;
};
var CharSetNone = 0;
var CharSetOk = 1;
var CharSetString = 2;
pp$1.regexp_eatCharacterClassEscape = function(state) {
  var ch = state.current();
  if (isCharacterClassEscape(ch)) {
    state.lastIntValue = -1;
    state.advance();
    return CharSetOk;
  }
  var negate = false;
  if (state.switchU && this.options.ecmaVersion >= 9 && ((negate = ch === 80) || ch === 112)) {
    state.lastIntValue = -1;
    state.advance();
    var result;
    if (state.eat(
      123
      /* { */
    ) && (result = this.regexp_eatUnicodePropertyValueExpression(state)) && state.eat(
      125
      /* } */
    )) {
      if (negate && result === CharSetString) {
        state.raise("Invalid property name");
      }
      return result;
    }
    state.raise("Invalid property name");
  }
  return CharSetNone;
};
function isCharacterClassEscape(ch) {
  return ch === 100 || ch === 68 || ch === 115 || ch === 83 || ch === 119 || ch === 87;
}
pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
  var start = state.pos;
  if (this.regexp_eatUnicodePropertyName(state) && state.eat(
    61
    /* = */
  )) {
    var name = state.lastStringValue;
    if (this.regexp_eatUnicodePropertyValue(state)) {
      var value = state.lastStringValue;
      this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
      return CharSetOk;
    }
  }
  state.pos = start;
  if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
    var nameOrValue = state.lastStringValue;
    return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  }
  return CharSetNone;
};
pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  if (!hasOwn(state.unicodeProperties.nonBinary, name)) {
    state.raise("Invalid property name");
  }
  if (!state.unicodeProperties.nonBinary[name].test(value)) {
    state.raise("Invalid property value");
  }
};
pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  if (state.unicodeProperties.binary.test(nameOrValue)) {
    return CharSetOk;
  }
  if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) {
    return CharSetString;
  }
  state.raise("Invalid property name");
};
pp$1.regexp_eatUnicodePropertyName = function(state) {
  var ch = 0;
  state.lastStringValue = "";
  while (isUnicodePropertyNameCharacter(ch = state.current())) {
    state.lastStringValue += codePointToString(ch);
    state.advance();
  }
  return state.lastStringValue !== "";
};
function isUnicodePropertyNameCharacter(ch) {
  return isControlLetter(ch) || ch === 95;
}
pp$1.regexp_eatUnicodePropertyValue = function(state) {
  var ch = 0;
  state.lastStringValue = "";
  while (isUnicodePropertyValueCharacter(ch = state.current())) {
    state.lastStringValue += codePointToString(ch);
    state.advance();
  }
  return state.lastStringValue !== "";
};
function isUnicodePropertyValueCharacter(ch) {
  return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch);
}
pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  return this.regexp_eatUnicodePropertyValue(state);
};
pp$1.regexp_eatCharacterClass = function(state) {
  if (state.eat(
    91
    /* [ */
  )) {
    var negate = state.eat(
      94
      /* ^ */
    );
    var result = this.regexp_classContents(state);
    if (!state.eat(
      93
      /* ] */
    )) {
      state.raise("Unterminated character class");
    }
    if (negate && result === CharSetString) {
      state.raise("Negated character class may contain strings");
    }
    return true;
  }
  return false;
};
pp$1.regexp_classContents = function(state) {
  if (state.current() === 93) {
    return CharSetOk;
  }
  if (state.switchV) {
    return this.regexp_classSetExpression(state);
  }
  this.regexp_nonEmptyClassRanges(state);
  return CharSetOk;
};
pp$1.regexp_nonEmptyClassRanges = function(state) {
  while (this.regexp_eatClassAtom(state)) {
    var left = state.lastIntValue;
    if (state.eat(
      45
      /* - */
    ) && this.regexp_eatClassAtom(state)) {
      var right = state.lastIntValue;
      if (state.switchU && (left === -1 || right === -1)) {
        state.raise("Invalid character class");
      }
      if (left !== -1 && right !== -1 && left > right) {
        state.raise("Range out of order in character class");
      }
    }
  }
};
pp$1.regexp_eatClassAtom = function(state) {
  var start = state.pos;
  if (state.eat(
    92
    /* \ */
  )) {
    if (this.regexp_eatClassEscape(state)) {
      return true;
    }
    if (state.switchU) {
      var ch$1 = state.current();
      if (ch$1 === 99 || isOctalDigit(ch$1)) {
        state.raise("Invalid class escape");
      }
      state.raise("Invalid escape");
    }
    state.pos = start;
  }
  var ch = state.current();
  if (ch !== 93) {
    state.lastIntValue = ch;
    state.advance();
    return true;
  }
  return false;
};
pp$1.regexp_eatClassEscape = function(state) {
  var start = state.pos;
  if (state.eat(
    98
    /* b */
  )) {
    state.lastIntValue = 8;
    return true;
  }
  if (state.switchU && state.eat(
    45
    /* - */
  )) {
    state.lastIntValue = 45;
    return true;
  }
  if (!state.switchU && state.eat(
    99
    /* c */
  )) {
    if (this.regexp_eatClassControlLetter(state)) {
      return true;
    }
    state.pos = start;
  }
  return this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state);
};
pp$1.regexp_classSetExpression = function(state) {
  var result = CharSetOk, subResult;
  if (this.regexp_eatClassSetRange(state)) ;
  else if (subResult = this.regexp_eatClassSetOperand(state)) {
    if (subResult === CharSetString) {
      result = CharSetString;
    }
    var start = state.pos;
    while (state.eatChars(
      [38, 38]
      /* && */
    )) {
      if (state.current() !== 38 && (subResult = this.regexp_eatClassSetOperand(state))) {
        if (subResult !== CharSetString) {
          result = CharSetOk;
        }
        continue;
      }
      state.raise("Invalid character in character class");
    }
    if (start !== state.pos) {
      return result;
    }
    while (state.eatChars(
      [45, 45]
      /* -- */
    )) {
      if (this.regexp_eatClassSetOperand(state)) {
        continue;
      }
      state.raise("Invalid character in character class");
    }
    if (start !== state.pos) {
      return result;
    }
  } else {
    state.raise("Invalid character in character class");
  }
  for (; ; ) {
    if (this.regexp_eatClassSetRange(state)) {
      continue;
    }
    subResult = this.regexp_eatClassSetOperand(state);
    if (!subResult) {
      return result;
    }
    if (subResult === CharSetString) {
      result = CharSetString;
    }
  }
};
pp$1.regexp_eatClassSetRange = function(state) {
  var start = state.pos;
  if (this.regexp_eatClassSetCharacter(state)) {
    var left = state.lastIntValue;
    if (state.eat(
      45
      /* - */
    ) && this.regexp_eatClassSetCharacter(state)) {
      var right = state.lastIntValue;
      if (left !== -1 && right !== -1 && left > right) {
        state.raise("Range out of order in character class");
      }
      return true;
    }
    state.pos = start;
  }
  return false;
};
pp$1.regexp_eatClassSetOperand = function(state) {
  if (this.regexp_eatClassSetCharacter(state)) {
    return CharSetOk;
  }
  return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state);
};
pp$1.regexp_eatNestedClass = function(state) {
  var start = state.pos;
  if (state.eat(
    91
    /* [ */
  )) {
    var negate = state.eat(
      94
      /* ^ */
    );
    var result = this.regexp_classContents(state);
    if (state.eat(
      93
      /* ] */
    )) {
      if (negate && result === CharSetString) {
        state.raise("Negated character class may contain strings");
      }
      return result;
    }
    state.pos = start;
  }
  if (state.eat(
    92
    /* \ */
  )) {
    var result$1 = this.regexp_eatCharacterClassEscape(state);
    if (result$1) {
      return result$1;
    }
    state.pos = start;
  }
  return null;
};
pp$1.regexp_eatClassStringDisjunction = function(state) {
  var start = state.pos;
  if (state.eatChars(
    [92, 113]
    /* \q */
  )) {
    if (state.eat(
      123
      /* { */
    )) {
      var result = this.regexp_classStringDisjunctionContents(state);
      if (state.eat(
        125
        /* } */
      )) {
        return result;
      }
    } else {
      state.raise("Invalid escape");
    }
    state.pos = start;
  }
  return null;
};
pp$1.regexp_classStringDisjunctionContents = function(state) {
  var result = this.regexp_classString(state);
  while (state.eat(
    124
    /* | */
  )) {
    if (this.regexp_classString(state) === CharSetString) {
      result = CharSetString;
    }
  }
  return result;
};
pp$1.regexp_classString = function(state) {
  var count = 0;
  while (this.regexp_eatClassSetCharacter(state)) {
    count++;
  }
  return count === 1 ? CharSetOk : CharSetString;
};
pp$1.regexp_eatClassSetCharacter = function(state) {
  var start = state.pos;
  if (state.eat(
    92
    /* \ */
  )) {
    if (this.regexp_eatCharacterEscape(state) || this.regexp_eatClassSetReservedPunctuator(state)) {
      return true;
    }
    if (state.eat(
      98
      /* b */
    )) {
      state.lastIntValue = 8;
      return true;
    }
    state.pos = start;
    return false;
  }
  var ch = state.current();
  if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) {
    return false;
  }
  if (isClassSetSyntaxCharacter(ch)) {
    return false;
  }
  state.advance();
  state.lastIntValue = ch;
  return true;
};
function isClassSetReservedDoublePunctuatorCharacter(ch) {
  return ch === 33 || ch >= 35 && ch <= 38 || ch >= 42 && ch <= 44 || ch === 46 || ch >= 58 && ch <= 64 || ch === 94 || ch === 96 || ch === 126;
}
function isClassSetSyntaxCharacter(ch) {
  return ch === 40 || ch === 41 || ch === 45 || ch === 47 || ch >= 91 && ch <= 93 || ch >= 123 && ch <= 125;
}
pp$1.regexp_eatClassSetReservedPunctuator = function(state) {
  var ch = state.current();
  if (isClassSetReservedPunctuator(ch)) {
    state.lastIntValue = ch;
    state.advance();
    return true;
  }
  return false;
};
function isClassSetReservedPunctuator(ch) {
  return ch === 33 || ch === 35 || ch === 37 || ch === 38 || ch === 44 || ch === 45 || ch >= 58 && ch <= 62 || ch === 64 || ch === 96 || ch === 126;
}
pp$1.regexp_eatClassControlLetter = function(state) {
  var ch = state.current();
  if (isDecimalDigit(ch) || ch === 95) {
    state.lastIntValue = ch % 32;
    state.advance();
    return true;
  }
  return false;
};
pp$1.regexp_eatHexEscapeSequence = function(state) {
  var start = state.pos;
  if (state.eat(
    120
    /* x */
  )) {
    if (this.regexp_eatFixedHexDigits(state, 2)) {
      return true;
    }
    if (state.switchU) {
      state.raise("Invalid escape");
    }
    state.pos = start;
  }
  return false;
};
pp$1.regexp_eatDecimalDigits = function(state) {
  var start = state.pos;
  var ch = 0;
  state.lastIntValue = 0;
  while (isDecimalDigit(ch = state.current())) {
    state.lastIntValue = 10 * state.lastIntValue + (ch - 48);
    state.advance();
  }
  return state.pos !== start;
};
function isDecimalDigit(ch) {
  return ch >= 48 && ch <= 57;
}
pp$1.regexp_eatHexDigits = function(state) {
  var start = state.pos;
  var ch = 0;
  state.lastIntValue = 0;
  while (isHexDigit(ch = state.current())) {
    state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
    state.advance();
  }
  return state.pos !== start;
};
function isHexDigit(ch) {
  return ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102;
}
function hexToInt(ch) {
  if (ch >= 65 && ch <= 70) {
    return 10 + (ch - 65);
  }
  if (ch >= 97 && ch <= 102) {
    return 10 + (ch - 97);
  }
  return ch - 48;
}
pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
  if (this.regexp_eatOctalDigit(state)) {
    var n1 = state.lastIntValue;
    if (this.regexp_eatOctalDigit(state)) {
      var n2 = state.lastIntValue;
      if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
        state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
      } else {
        state.lastIntValue = n1 * 8 + n2;
      }
    } else {
      state.lastIntValue = n1;
    }
    return true;
  }
  return false;
};
pp$1.regexp_eatOctalDigit = function(state) {
  var ch = state.current();
  if (isOctalDigit(ch)) {
    state.lastIntValue = ch - 48;
    state.advance();
    return true;
  }
  state.lastIntValue = 0;
  return false;
};
function isOctalDigit(ch) {
  return ch >= 48 && ch <= 55;
}
pp$1.regexp_eatFixedHexDigits = function(state, length) {
  var start = state.pos;
  state.lastIntValue = 0;
  for (var i = 0; i < length; ++i) {
    var ch = state.current();
    if (!isHexDigit(ch)) {
      state.pos = start;
      return false;
    }
    state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
    state.advance();
  }
  return true;
};
var Token = function Token2(p) {
  this.type = p.type;
  this.value = p.value;
  this.start = p.start;
  this.end = p.end;
  if (p.options.locations) {
    this.loc = new SourceLocation(p, p.startLoc, p.endLoc);
  }
  if (p.options.ranges) {
    this.range = [p.start, p.end];
  }
};
var pp = Parser.prototype;
pp.next = function(ignoreEscapeSequenceInKeyword) {
  if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) {
    this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword);
  }
  if (this.options.onToken) {
    this.options.onToken(new Token(this));
  }
  this.lastTokEnd = this.end;
  this.lastTokStart = this.start;
  this.lastTokEndLoc = this.endLoc;
  this.lastTokStartLoc = this.startLoc;
  this.nextToken();
};
pp.getToken = function() {
  this.next();
  return new Token(this);
};
if (typeof Symbol !== "undefined") {
  pp[Symbol.iterator] = function() {
    var this$1$1 = this;
    return {
      next: function() {
        var token = this$1$1.getToken();
        return {
          done: token.type === types$1.eof,
          value: token
        };
      }
    };
  };
}
pp.nextToken = function() {
  var curContext = this.curContext();
  if (!curContext || !curContext.preserveSpace) {
    this.skipSpace();
  }
  this.start = this.pos;
  if (this.options.locations) {
    this.startLoc = this.curPosition();
  }
  if (this.pos >= this.input.length) {
    return this.finishToken(types$1.eof);
  }
  if (curContext.override) {
    return curContext.override(this);
  } else {
    this.readToken(this.fullCharCodeAtPos());
  }
};
pp.readToken = function(code) {
  if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92) {
    return this.readWord();
  }
  return this.getTokenFromCode(code);
};
pp.fullCharCodeAtPos = function() {
  var code = this.input.charCodeAt(this.pos);
  if (code <= 55295 || code >= 56320) {
    return code;
  }
  var next = this.input.charCodeAt(this.pos + 1);
  return next <= 56319 || next >= 57344 ? code : (code << 10) + next - 56613888;
};
pp.skipBlockComment = function() {
  var startLoc = this.options.onComment && this.curPosition();
  var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  if (end === -1) {
    this.raise(this.pos - 2, "Unterminated comment");
  }
  this.pos = end + 2;
  if (this.options.locations) {
    for (var nextBreak = void 0, pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1; ) {
      ++this.curLine;
      pos = this.lineStart = nextBreak;
    }
  }
  if (this.options.onComment) {
    this.options.onComment(
      true,
      this.input.slice(start + 2, end),
      start,
      this.pos,
      startLoc,
      this.curPosition()
    );
  }
};
pp.skipLineComment = function(startSkip) {
  var start = this.pos;
  var startLoc = this.options.onComment && this.curPosition();
  var ch = this.input.charCodeAt(this.pos += startSkip);
  while (this.pos < this.input.length && !isNewLine(ch)) {
    ch = this.input.charCodeAt(++this.pos);
  }
  if (this.options.onComment) {
    this.options.onComment(
      false,
      this.input.slice(start + startSkip, this.pos),
      start,
      this.pos,
      startLoc,
      this.curPosition()
    );
  }
};
pp.skipSpace = function() {
  loop: while (this.pos < this.input.length) {
    var ch = this.input.charCodeAt(this.pos);
    switch (ch) {
      case 32:
      case 160:
        ++this.pos;
        break;
      case 13:
        if (this.input.charCodeAt(this.pos + 1) === 10) {
          ++this.pos;
        }
      case 10:
      case 8232:
      case 8233:
        ++this.pos;
        if (this.options.locations) {
          ++this.curLine;
          this.lineStart = this.pos;
        }
        break;
      case 47:
        switch (this.input.charCodeAt(this.pos + 1)) {
          case 42:
            this.skipBlockComment();
            break;
          case 47:
            this.skipLineComment(2);
            break;
          default:
            break loop;
        }
        break;
      default:
        if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
          ++this.pos;
        } else {
          break loop;
        }
    }
  }
};
pp.finishToken = function(type, val) {
  this.end = this.pos;
  if (this.options.locations) {
    this.endLoc = this.curPosition();
  }
  var prevType = this.type;
  this.type = type;
  this.value = val;
  this.updateContext(prevType);
};
pp.readToken_dot = function() {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next >= 48 && next <= 57) {
    return this.readNumber(true);
  }
  var next2 = this.input.charCodeAt(this.pos + 2);
  if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) {
    this.pos += 3;
    return this.finishToken(types$1.ellipsis);
  } else {
    ++this.pos;
    return this.finishToken(types$1.dot);
  }
};
pp.readToken_slash = function() {
  var next = this.input.charCodeAt(this.pos + 1);
  if (this.exprAllowed) {
    ++this.pos;
    return this.readRegexp();
  }
  if (next === 61) {
    return this.finishOp(types$1.assign, 2);
  }
  return this.finishOp(types$1.slash, 1);
};
pp.readToken_mult_modulo_exp = function(code) {
  var next = this.input.charCodeAt(this.pos + 1);
  var size = 1;
  var tokentype = code === 42 ? types$1.star : types$1.modulo;
  if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
    ++size;
    tokentype = types$1.starstar;
    next = this.input.charCodeAt(this.pos + 2);
  }
  if (next === 61) {
    return this.finishOp(types$1.assign, size + 1);
  }
  return this.finishOp(tokentype, size);
};
pp.readToken_pipe_amp = function(code) {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === code) {
    if (this.options.ecmaVersion >= 12) {
      var next2 = this.input.charCodeAt(this.pos + 2);
      if (next2 === 61) {
        return this.finishOp(types$1.assign, 3);
      }
    }
    return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2);
  }
  if (next === 61) {
    return this.finishOp(types$1.assign, 2);
  }
  return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1);
};
pp.readToken_caret = function() {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === 61) {
    return this.finishOp(types$1.assign, 2);
  }
  return this.finishOp(types$1.bitwiseXOR, 1);
};
pp.readToken_plus_min = function(code) {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === code) {
    if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
      this.skipLineComment(3);
      this.skipSpace();
      return this.nextToken();
    }
    return this.finishOp(types$1.incDec, 2);
  }
  if (next === 61) {
    return this.finishOp(types$1.assign, 2);
  }
  return this.finishOp(types$1.plusMin, 1);
};
pp.readToken_lt_gt = function(code) {
  var next = this.input.charCodeAt(this.pos + 1);
  var size = 1;
  if (next === code) {
    size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
    if (this.input.charCodeAt(this.pos + size) === 61) {
      return this.finishOp(types$1.assign, size + 1);
    }
    return this.finishOp(types$1.bitShift, size);
  }
  if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) {
    this.skipLineComment(4);
    this.skipSpace();
    return this.nextToken();
  }
  if (next === 61) {
    size = 2;
  }
  return this.finishOp(types$1.relational, size);
};
pp.readToken_eq_excl = function(code) {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === 61) {
    return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2);
  }
  if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) {
    this.pos += 2;
    return this.finishToken(types$1.arrow);
  }
  return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1);
};
pp.readToken_question = function() {
  var ecmaVersion = this.options.ecmaVersion;
  if (ecmaVersion >= 11) {
    var next = this.input.charCodeAt(this.pos + 1);
    if (next === 46) {
      var next2 = this.input.charCodeAt(this.pos + 2);
      if (next2 < 48 || next2 > 57) {
        return this.finishOp(types$1.questionDot, 2);
      }
    }
    if (next === 63) {
      if (ecmaVersion >= 12) {
        var next2$1 = this.input.charCodeAt(this.pos + 2);
        if (next2$1 === 61) {
          return this.finishOp(types$1.assign, 3);
        }
      }
      return this.finishOp(types$1.coalesce, 2);
    }
  }
  return this.finishOp(types$1.question, 1);
};
pp.readToken_numberSign = function() {
  var ecmaVersion = this.options.ecmaVersion;
  var code = 35;
  if (ecmaVersion >= 13) {
    ++this.pos;
    code = this.fullCharCodeAtPos();
    if (isIdentifierStart(code, true) || code === 92) {
      return this.finishToken(types$1.privateId, this.readWord1());
    }
  }
  this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
};
pp.getTokenFromCode = function(code) {
  switch (code) {
    // The interpretation of a dot depends on whether it is followed
    // by a digit or another two dots.
    case 46:
      return this.readToken_dot();
    // Punctuation tokens.
    case 40:
      ++this.pos;
      return this.finishToken(types$1.parenL);
    case 41:
      ++this.pos;
      return this.finishToken(types$1.parenR);
    case 59:
      ++this.pos;
      return this.finishToken(types$1.semi);
    case 44:
      ++this.pos;
      return this.finishToken(types$1.comma);
    case 91:
      ++this.pos;
      return this.finishToken(types$1.bracketL);
    case 93:
      ++this.pos;
      return this.finishToken(types$1.bracketR);
    case 123:
      ++this.pos;
      return this.finishToken(types$1.braceL);
    case 125:
      ++this.pos;
      return this.finishToken(types$1.braceR);
    case 58:
      ++this.pos;
      return this.finishToken(types$1.colon);
    case 96:
      if (this.options.ecmaVersion < 6) {
        break;
      }
      ++this.pos;
      return this.finishToken(types$1.backQuote);
    case 48:
      var next = this.input.charCodeAt(this.pos + 1);
      if (next === 120 || next === 88) {
        return this.readRadixNumber(16);
      }
      if (this.options.ecmaVersion >= 6) {
        if (next === 111 || next === 79) {
          return this.readRadixNumber(8);
        }
        if (next === 98 || next === 66) {
          return this.readRadixNumber(2);
        }
      }
    // Anything else beginning with a digit is an integer, octal
    // number, or float.
    case 49:
    case 50:
    case 51:
    case 52:
    case 53:
    case 54:
    case 55:
    case 56:
    case 57:
      return this.readNumber(false);
    // Quotes produce strings.
    case 34:
    case 39:
      return this.readString(code);
    // Operators are parsed inline in tiny state machines. '=' (61) is
    // often referred to. `finishOp` simply skips the amount of
    // characters it is given as second argument, and returns a token
    // of the type given by its first argument.
    case 47:
      return this.readToken_slash();
    case 37:
    case 42:
      return this.readToken_mult_modulo_exp(code);
    case 124:
    case 38:
      return this.readToken_pipe_amp(code);
    case 94:
      return this.readToken_caret();
    case 43:
    case 45:
      return this.readToken_plus_min(code);
    case 60:
    case 62:
      return this.readToken_lt_gt(code);
    case 61:
    case 33:
      return this.readToken_eq_excl(code);
    case 63:
      return this.readToken_question();
    case 126:
      return this.finishOp(types$1.prefix, 1);
    case 35:
      return this.readToken_numberSign();
  }
  this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
};
pp.finishOp = function(type, size) {
  var str = this.input.slice(this.pos, this.pos + size);
  this.pos += size;
  return this.finishToken(type, str);
};
pp.readRegexp = function() {
  var escaped, inClass, start = this.pos;
  for (; ; ) {
    if (this.pos >= this.input.length) {
      this.raise(start, "Unterminated regular expression");
    }
    var ch = this.input.charAt(this.pos);
    if (lineBreak.test(ch)) {
      this.raise(start, "Unterminated regular expression");
    }
    if (!escaped) {
      if (ch === "[") {
        inClass = true;
      } else if (ch === "]" && inClass) {
        inClass = false;
      } else if (ch === "/" && !inClass) {
        break;
      }
      escaped = ch === "\\";
    } else {
      escaped = false;
    }
    ++this.pos;
  }
  var pattern = this.input.slice(start, this.pos);
  ++this.pos;
  var flagsStart = this.pos;
  var flags = this.readWord1();
  if (this.containsEsc) {
    this.unexpected(flagsStart);
  }
  var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  state.reset(start, pattern, flags);
  this.validateRegExpFlags(state);
  this.validateRegExpPattern(state);
  var value = null;
  try {
    value = new RegExp(pattern, flags);
  } catch (e) {
  }
  return this.finishToken(types$1.regexp, { pattern, flags, value });
};
pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  var allowSeparators = this.options.ecmaVersion >= 12 && len === void 0;
  var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  var start = this.pos, total = 0, lastCode = 0;
  for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
    var code = this.input.charCodeAt(this.pos), val = void 0;
    if (allowSeparators && code === 95) {
      if (isLegacyOctalNumericLiteral) {
        this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals");
      }
      if (lastCode === 95) {
        this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore");
      }
      if (i === 0) {
        this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits");
      }
      lastCode = code;
      continue;
    }
    if (code >= 97) {
      val = code - 97 + 10;
    } else if (code >= 65) {
      val = code - 65 + 10;
    } else if (code >= 48 && code <= 57) {
      val = code - 48;
    } else {
      val = Infinity;
    }
    if (val >= radix) {
      break;
    }
    lastCode = code;
    total = total * radix + val;
  }
  if (allowSeparators && lastCode === 95) {
    this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits");
  }
  if (this.pos === start || len != null && this.pos - start !== len) {
    return null;
  }
  return total;
};
function stringToNumber(str, isLegacyOctalNumericLiteral) {
  if (isLegacyOctalNumericLiteral) {
    return parseInt(str, 8);
  }
  return parseFloat(str.replace(/_/g, ""));
}
function stringToBigInt(str) {
  if (typeof BigInt !== "function") {
    return null;
  }
  return BigInt(str.replace(/_/g, ""));
}
pp.readRadixNumber = function(radix) {
  var start = this.pos;
  this.pos += 2;
  var val = this.readInt(radix);
  if (val == null) {
    this.raise(this.start + 2, "Expected number in radix " + radix);
  }
  if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
    val = stringToBigInt(this.input.slice(start, this.pos));
    ++this.pos;
  } else if (isIdentifierStart(this.fullCharCodeAtPos())) {
    this.raise(this.pos, "Identifier directly after number");
  }
  return this.finishToken(types$1.num, val);
};
pp.readNumber = function(startsWithDot) {
  var start = this.pos;
  if (!startsWithDot && this.readInt(10, void 0, true) === null) {
    this.raise(start, "Invalid number");
  }
  var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  if (octal && this.strict) {
    this.raise(start, "Invalid number");
  }
  var next = this.input.charCodeAt(this.pos);
  if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
    var val$1 = stringToBigInt(this.input.slice(start, this.pos));
    ++this.pos;
    if (isIdentifierStart(this.fullCharCodeAtPos())) {
      this.raise(this.pos, "Identifier directly after number");
    }
    return this.finishToken(types$1.num, val$1);
  }
  if (octal && /[89]/.test(this.input.slice(start, this.pos))) {
    octal = false;
  }
  if (next === 46 && !octal) {
    ++this.pos;
    this.readInt(10);
    next = this.input.charCodeAt(this.pos);
  }
  if ((next === 69 || next === 101) && !octal) {
    next = this.input.charCodeAt(++this.pos);
    if (next === 43 || next === 45) {
      ++this.pos;
    }
    if (this.readInt(10) === null) {
      this.raise(start, "Invalid number");
    }
  }
  if (isIdentifierStart(this.fullCharCodeAtPos())) {
    this.raise(this.pos, "Identifier directly after number");
  }
  var val = stringToNumber(this.input.slice(start, this.pos), octal);
  return this.finishToken(types$1.num, val);
};
pp.readCodePoint = function() {
  var ch = this.input.charCodeAt(this.pos), code;
  if (ch === 123) {
    if (this.options.ecmaVersion < 6) {
      this.unexpected();
    }
    var codePos = ++this.pos;
    code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
    ++this.pos;
    if (code > 1114111) {
      this.invalidStringToken(codePos, "Code point out of bounds");
    }
  } else {
    code = this.readHexChar(4);
  }
  return code;
};
pp.readString = function(quote) {
  var out = "", chunkStart = ++this.pos;
  for (; ; ) {
    if (this.pos >= this.input.length) {
      this.raise(this.start, "Unterminated string constant");
    }
    var ch = this.input.charCodeAt(this.pos);
    if (ch === quote) {
      break;
    }
    if (ch === 92) {
      out += this.input.slice(chunkStart, this.pos);
      out += this.readEscapedChar(false);
      chunkStart = this.pos;
    } else if (ch === 8232 || ch === 8233) {
      if (this.options.ecmaVersion < 10) {
        this.raise(this.start, "Unterminated string constant");
      }
      ++this.pos;
      if (this.options.locations) {
        this.curLine++;
        this.lineStart = this.pos;
      }
    } else {
      if (isNewLine(ch)) {
        this.raise(this.start, "Unterminated string constant");
      }
      ++this.pos;
    }
  }
  out += this.input.slice(chunkStart, this.pos++);
  return this.finishToken(types$1.string, out);
};
var INVALID_TEMPLATE_ESCAPE_ERROR = {};
pp.tryReadTemplateToken = function() {
  this.inTemplateElement = true;
  try {
    this.readTmplToken();
  } catch (err) {
    if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
      this.readInvalidTemplateToken();
    } else {
      throw err;
    }
  }
  this.inTemplateElement = false;
};
pp.invalidStringToken = function(position, message) {
  if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
    throw INVALID_TEMPLATE_ESCAPE_ERROR;
  } else {
    this.raise(position, message);
  }
};
pp.readTmplToken = function() {
  var out = "", chunkStart = this.pos;
  for (; ; ) {
    if (this.pos >= this.input.length) {
      this.raise(this.start, "Unterminated template");
    }
    var ch = this.input.charCodeAt(this.pos);
    if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) {
      if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
        if (ch === 36) {
          this.pos += 2;
          return this.finishToken(types$1.dollarBraceL);
        } else {
          ++this.pos;
          return this.finishToken(types$1.backQuote);
        }
      }
      out += this.input.slice(chunkStart, this.pos);
      return this.finishToken(types$1.template, out);
    }
    if (ch === 92) {
      out += this.input.slice(chunkStart, this.pos);
      out += this.readEscapedChar(true);
      chunkStart = this.pos;
    } else if (isNewLine(ch)) {
      out += this.input.slice(chunkStart, this.pos);
      ++this.pos;
      switch (ch) {
        case 13:
          if (this.input.charCodeAt(this.pos) === 10) {
            ++this.pos;
          }
        case 10:
          out += "\n";
          break;
        default:
          out += String.fromCharCode(ch);
          break;
      }
      if (this.options.locations) {
        ++this.curLine;
        this.lineStart = this.pos;
      }
      chunkStart = this.pos;
    } else {
      ++this.pos;
    }
  }
};
pp.readInvalidTemplateToken = function() {
  for (; this.pos < this.input.length; this.pos++) {
    switch (this.input[this.pos]) {
      case "\\":
        ++this.pos;
        break;
      case "$":
        if (this.input[this.pos + 1] !== "{") {
          break;
        }
      // fall through
      case "`":
        return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos));
      case "\r":
        if (this.input[this.pos + 1] === "\n") {
          ++this.pos;
        }
      // fall through
      case "\n":
      case "\u2028":
      case "\u2029":
        ++this.curLine;
        this.lineStart = this.pos + 1;
        break;
    }
  }
  this.raise(this.start, "Unterminated template");
};
pp.readEscapedChar = function(inTemplate) {
  var ch = this.input.charCodeAt(++this.pos);
  ++this.pos;
  switch (ch) {
    case 110:
      return "\n";
    // 'n' -> '\n'
    case 114:
      return "\r";
    // 'r' -> '\r'
    case 120:
      return String.fromCharCode(this.readHexChar(2));
    // 'x'
    case 117:
      return codePointToString(this.readCodePoint());
    // 'u'
    case 116:
      return "	";
    // 't' -> '\t'
    case 98:
      return "\b";
    // 'b' -> '\b'
    case 118:
      return "\v";
    // 'v' -> '\u000b'
    case 102:
      return "\f";
    // 'f' -> '\f'
    case 13:
      if (this.input.charCodeAt(this.pos) === 10) {
        ++this.pos;
      }
    // '\r\n'
    case 10:
      if (this.options.locations) {
        this.lineStart = this.pos;
        ++this.curLine;
      }
      return "";
    case 56:
    case 57:
      if (this.strict) {
        this.invalidStringToken(
          this.pos - 1,
          "Invalid escape sequence"
        );
      }
      if (inTemplate) {
        var codePos = this.pos - 1;
        this.invalidStringToken(
          codePos,
          "Invalid escape sequence in template string"
        );
      }
    default:
      if (ch >= 48 && ch <= 55) {
        var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
        var octal = parseInt(octalStr, 8);
        if (octal > 255) {
          octalStr = octalStr.slice(0, -1);
          octal = parseInt(octalStr, 8);
        }
        this.pos += octalStr.length - 1;
        ch = this.input.charCodeAt(this.pos);
        if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
          this.invalidStringToken(
            this.pos - 1 - octalStr.length,
            inTemplate ? "Octal literal in template string" : "Octal literal in strict mode"
          );
        }
        return String.fromCharCode(octal);
      }
      if (isNewLine(ch)) {
        if (this.options.locations) {
          this.lineStart = this.pos;
          ++this.curLine;
        }
        return "";
      }
      return String.fromCharCode(ch);
  }
};
pp.readHexChar = function(len) {
  var codePos = this.pos;
  var n = this.readInt(16, len);
  if (n === null) {
    this.invalidStringToken(codePos, "Bad character escape sequence");
  }
  return n;
};
pp.readWord1 = function() {
  this.containsEsc = false;
  var word = "", first = true, chunkStart = this.pos;
  var astral = this.options.ecmaVersion >= 6;
  while (this.pos < this.input.length) {
    var ch = this.fullCharCodeAtPos();
    if (isIdentifierChar(ch, astral)) {
      this.pos += ch <= 65535 ? 1 : 2;
    } else if (ch === 92) {
      this.containsEsc = true;
      word += this.input.slice(chunkStart, this.pos);
      var escStart = this.pos;
      if (this.input.charCodeAt(++this.pos) !== 117) {
        this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX");
      }
      ++this.pos;
      var esc = this.readCodePoint();
      if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) {
        this.invalidStringToken(escStart, "Invalid Unicode escape");
      }
      word += codePointToString(esc);
      chunkStart = this.pos;
    } else {
      break;
    }
    first = false;
  }
  return word + this.input.slice(chunkStart, this.pos);
};
pp.readWord = function() {
  var word = this.readWord1();
  var type = types$1.name;
  if (this.keywords.test(word)) {
    type = keywords[word];
  }
  return this.finishToken(type, word);
};
var version = "8.14.0";
Parser.acorn = {
  Parser,
  version,
  defaultOptions,
  Position,
  SourceLocation,
  getLineInfo,
  Node,
  TokenType,
  tokTypes: types$1,
  keywordTypes: keywords,
  TokContext,
  tokContexts: types3,
  isIdentifierChar,
  isIdentifierStart,
  Token,
  isNewLine,
  lineBreak,
  lineBreakG,
  nonASCIIwhitespace
};

// ../../node_modules/.pnpm/acorn-import-phases@1.0.4_acorn@8.14.0/node_modules/acorn-import-phases/src/index.js
var import_plugin = __toESM(require_plugin(), 1);
function src_default2(options = {}) {
  return (Parser3) => (0, import_plugin.plugin)(options, Parser3, Parser3.acorn ? Parser3.acorn.tokTypes : types$1);
}

// ../../node_modules/.pnpm/acorn-walk@8.3.2/node_modules/acorn-walk/dist/walk.mjs
function simple(node, visitors, baseVisitor, state, override) {
  if (!baseVisitor) {
    baseVisitor = base;
  }
  (function c(node2, st, override2) {
    var type = override2 || node2.type;
    baseVisitor[type](node2, st, c);
    if (visitors[type]) {
      visitors[type](node2, st);
    }
  })(node, state, override);
}
function skipThrough(node, st, c) {
  c(node, st);
}
function ignore2(_node, _st, _c) {
}
var base = {};
base.Program = base.BlockStatement = base.StaticBlock = function(node, st, c) {
  for (var i = 0, list = node.body; i < list.length; i += 1) {
    var stmt = list[i];
    c(stmt, st, "Statement");
  }
};
base.Statement = skipThrough;
base.EmptyStatement = ignore2;
base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression = function(node, st, c) {
  return c(node.expression, st, "Expression");
};
base.IfStatement = function(node, st, c) {
  c(node.test, st, "Expression");
  c(node.consequent, st, "Statement");
  if (node.alternate) {
    c(node.alternate, st, "Statement");
  }
};
base.LabeledStatement = function(node, st, c) {
  return c(node.body, st, "Statement");
};
base.BreakStatement = base.ContinueStatement = ignore2;
base.WithStatement = function(node, st, c) {
  c(node.object, st, "Expression");
  c(node.body, st, "Statement");
};
base.SwitchStatement = function(node, st, c) {
  c(node.discriminant, st, "Expression");
  for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
    var cs = list$1[i$1];
    if (cs.test) {
      c(cs.test, st, "Expression");
    }
    for (var i = 0, list = cs.consequent; i < list.length; i += 1) {
      var cons = list[i];
      c(cons, st, "Statement");
    }
  }
};
base.SwitchCase = function(node, st, c) {
  if (node.test) {
    c(node.test, st, "Expression");
  }
  for (var i = 0, list = node.consequent; i < list.length; i += 1) {
    var cons = list[i];
    c(cons, st, "Statement");
  }
};
base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function(node, st, c) {
  if (node.argument) {
    c(node.argument, st, "Expression");
  }
};
base.ThrowStatement = base.SpreadElement = function(node, st, c) {
  return c(node.argument, st, "Expression");
};
base.TryStatement = function(node, st, c) {
  c(node.block, st, "Statement");
  if (node.handler) {
    c(node.handler, st);
  }
  if (node.finalizer) {
    c(node.finalizer, st, "Statement");
  }
};
base.CatchClause = function(node, st, c) {
  if (node.param) {
    c(node.param, st, "Pattern");
  }
  c(node.body, st, "Statement");
};
base.WhileStatement = base.DoWhileStatement = function(node, st, c) {
  c(node.test, st, "Expression");
  c(node.body, st, "Statement");
};
base.ForStatement = function(node, st, c) {
  if (node.init) {
    c(node.init, st, "ForInit");
  }
  if (node.test) {
    c(node.test, st, "Expression");
  }
  if (node.update) {
    c(node.update, st, "Expression");
  }
  c(node.body, st, "Statement");
};
base.ForInStatement = base.ForOfStatement = function(node, st, c) {
  c(node.left, st, "ForInit");
  c(node.right, st, "Expression");
  c(node.body, st, "Statement");
};
base.ForInit = function(node, st, c) {
  if (node.type === "VariableDeclaration") {
    c(node, st);
  } else {
    c(node, st, "Expression");
  }
};
base.DebuggerStatement = ignore2;
base.FunctionDeclaration = function(node, st, c) {
  return c(node, st, "Function");
};
base.VariableDeclaration = function(node, st, c) {
  for (var i = 0, list = node.declarations; i < list.length; i += 1) {
    var decl = list[i];
    c(decl, st);
  }
};
base.VariableDeclarator = function(node, st, c) {
  c(node.id, st, "Pattern");
  if (node.init) {
    c(node.init, st, "Expression");
  }
};
base.Function = function(node, st, c) {
  if (node.id) {
    c(node.id, st, "Pattern");
  }
  for (var i = 0, list = node.params; i < list.length; i += 1) {
    var param = list[i];
    c(param, st, "Pattern");
  }
  c(node.body, st, node.expression ? "Expression" : "Statement");
};
base.Pattern = function(node, st, c) {
  if (node.type === "Identifier") {
    c(node, st, "VariablePattern");
  } else if (node.type === "MemberExpression") {
    c(node, st, "MemberPattern");
  } else {
    c(node, st);
  }
};
base.VariablePattern = ignore2;
base.MemberPattern = skipThrough;
base.RestElement = function(node, st, c) {
  return c(node.argument, st, "Pattern");
};
base.ArrayPattern = function(node, st, c) {
  for (var i = 0, list = node.elements; i < list.length; i += 1) {
    var elt = list[i];
    if (elt) {
      c(elt, st, "Pattern");
    }
  }
};
base.ObjectPattern = function(node, st, c) {
  for (var i = 0, list = node.properties; i < list.length; i += 1) {
    var prop = list[i];
    if (prop.type === "Property") {
      if (prop.computed) {
        c(prop.key, st, "Expression");
      }
      c(prop.value, st, "Pattern");
    } else if (prop.type === "RestElement") {
      c(prop.argument, st, "Pattern");
    }
  }
};
base.Expression = skipThrough;
base.ThisExpression = base.Super = base.MetaProperty = ignore2;
base.ArrayExpression = function(node, st, c) {
  for (var i = 0, list = node.elements; i < list.length; i += 1) {
    var elt = list[i];
    if (elt) {
      c(elt, st, "Expression");
    }
  }
};
base.ObjectExpression = function(node, st, c) {
  for (var i = 0, list = node.properties; i < list.length; i += 1) {
    var prop = list[i];
    c(prop, st);
  }
};
base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
base.SequenceExpression = function(node, st, c) {
  for (var i = 0, list = node.expressions; i < list.length; i += 1) {
    var expr = list[i];
    c(expr, st, "Expression");
  }
};
base.TemplateLiteral = function(node, st, c) {
  for (var i = 0, list = node.quasis; i < list.length; i += 1) {
    var quasi = list[i];
    c(quasi, st);
  }
  for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1) {
    var expr = list$1[i$1];
    c(expr, st, "Expression");
  }
};
base.TemplateElement = ignore2;
base.UnaryExpression = base.UpdateExpression = function(node, st, c) {
  c(node.argument, st, "Expression");
};
base.BinaryExpression = base.LogicalExpression = function(node, st, c) {
  c(node.left, st, "Expression");
  c(node.right, st, "Expression");
};
base.AssignmentExpression = base.AssignmentPattern = function(node, st, c) {
  c(node.left, st, "Pattern");
  c(node.right, st, "Expression");
};
base.ConditionalExpression = function(node, st, c) {
  c(node.test, st, "Expression");
  c(node.consequent, st, "Expression");
  c(node.alternate, st, "Expression");
};
base.NewExpression = base.CallExpression = function(node, st, c) {
  c(node.callee, st, "Expression");
  if (node.arguments) {
    for (var i = 0, list = node.arguments; i < list.length; i += 1) {
      var arg = list[i];
      c(arg, st, "Expression");
    }
  }
};
base.MemberExpression = function(node, st, c) {
  c(node.object, st, "Expression");
  if (node.computed) {
    c(node.property, st, "Expression");
  }
};
base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function(node, st, c) {
  if (node.declaration) {
    c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression");
  }
  if (node.source) {
    c(node.source, st, "Expression");
  }
};
base.ExportAllDeclaration = function(node, st, c) {
  if (node.exported) {
    c(node.exported, st);
  }
  c(node.source, st, "Expression");
};
base.ImportDeclaration = function(node, st, c) {
  for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
    var spec = list[i];
    c(spec, st);
  }
  c(node.source, st, "Expression");
};
base.ImportExpression = function(node, st, c) {
  c(node.source, st, "Expression");
};
base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore2;
base.TaggedTemplateExpression = function(node, st, c) {
  c(node.tag, st, "Expression");
  c(node.quasi, st, "Expression");
};
base.ClassDeclaration = base.ClassExpression = function(node, st, c) {
  return c(node, st, "Class");
};
base.Class = function(node, st, c) {
  if (node.id) {
    c(node.id, st, "Pattern");
  }
  if (node.superClass) {
    c(node.superClass, st, "Expression");
  }
  c(node.body, st);
};
base.ClassBody = function(node, st, c) {
  for (var i = 0, list = node.body; i < list.length; i += 1) {
    var elt = list[i];
    c(elt, st);
  }
};
base.MethodDefinition = base.PropertyDefinition = base.Property = function(node, st, c) {
  if (node.computed) {
    c(node.key, st, "Expression");
  }
  if (node.value) {
    c(node.value, st, "Expression");
  }
};

// src/plugins/core/node-compat.ts
function getNodeCompat(compatibilityDate = "2000-01-01", compatibilityFlags) {
  const {
    hasNodejsAlsFlag,
    hasNodejsCompatFlag,
    hasNodejsCompatV2Flag,
    hasNoNodejsCompatV2Flag,
    hasExperimentalNodejsCompatV2Flag
  } = parseNodeCompatibilityFlags(compatibilityFlags);
  const nodeCompatSwitchOverDate = "2024-09-23";
  let mode = null;
  if (hasNodejsCompatV2Flag || hasNodejsCompatFlag && compatibilityDate >= nodeCompatSwitchOverDate && !hasNoNodejsCompatV2Flag) {
    mode = "v2";
  } else if (hasNodejsCompatFlag) {
    mode = "v1";
  } else if (hasNodejsAlsFlag) {
    mode = "als";
  }
  return {
    mode,
    hasNodejsAlsFlag,
    hasNodejsCompatFlag,
    hasNodejsCompatV2Flag,
    hasNoNodejsCompatV2Flag,
    hasExperimentalNodejsCompatV2Flag
  };
}
function parseNodeCompatibilityFlags(compatibilityFlags) {
  return {
    hasNodejsAlsFlag: compatibilityFlags.includes("nodejs_als"),
    hasNodejsCompatFlag: compatibilityFlags.includes("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/modules.ts
var ExtendedParser = Parser.extend(src_default2());
var parse7 = ExtendedParser.parse.bind(ExtendedParser);
var SUGGEST_BUNDLE = "If you're trying to import an npm package, you'll need to bundle your Worker first.";
var SUGGEST_NODE = "If you're trying to import a Node.js built-in module, or an npm package that uses Node.js built-ins, you'll either need to:\n- Bundle your Worker, configuring your bundler to polyfill Node.js built-ins\n- Configure your bundler to load Workers-compatible builds by changing the main fields/conditions\n- Enable the `nodejs_compat` compatibility flag\n- Find an alternative package that doesn't require Node.js built-ins";
var builtinModulesWithPrefix = import_node_module.builtinModules.concat(
  import_node_module.builtinModules.map((module2) => `node:${module2}`)
);
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]);
}
var ModuleRuleTypeSchema = external_exports.enum([
  "ESModule",
  "CommonJS",
  "Text",
  "Data",
  "CompiledWasm",
  "PythonModule",
  "PythonRequirement"
]);
var ModuleRuleSchema = external_exports.object({
  type: ModuleRuleTypeSchema,
  include: external_exports.string().array(),
  fallthrough: external_exports.boolean().optional()
});
var ModuleDefinitionSchema = external_exports.object({
  type: ModuleRuleTypeSchema,
  path: PathSchema,
  contents: external_exports.string().or(external_exports.instanceof(Uint8Array)).optional()
});
var SourceOptionsSchema = external_exports.union([
  external_exports.object({
    // Manually defined modules
    // (used by Wrangler which has its own module collection code)
    modules: external_exports.array(ModuleDefinitionSchema),
    // `modules` "name"s will be their paths relative to this value.
    // This ensures file paths in stack traces are correct.
    modulesRoot: PathSchema.optional()
  }),
  external_exports.object({
    script: external_exports.string(),
    // Optional script path for resolving modules, and stack traces file names
    scriptPath: PathSchema.optional(),
    // Automatically collect modules by parsing `script` if `true`, or treat as
    // service-worker if `false`
    modules: external_exports.boolean().optional(),
    // How to interpret automatically collected modules
    modulesRules: external_exports.array(ModuleRuleSchema).optional(),
    // `modules` "name"s will be their paths relative to this value.
    // This ensures file paths in stack traces are correct.
    modulesRoot: PathSchema.optional()
  }),
  external_exports.object({
    scriptPath: PathSchema,
    // Automatically collect modules by parsing `scriptPath` if `true`, or treat
    // as service-worker if `false`
    modules: external_exports.boolean().optional(),
    // How to interpret automatically collected modules
    modulesRules: external_exports.array(ModuleRuleSchema).optional(),
    // `modules` "name"s will be their paths relative to this value.
    // This ensures file paths in stack traces are correct.
    modulesRoot: PathSchema.optional()
  })
]);
var DEFAULT_MODULE_RULES = [
  { type: "ESModule", include: ["**/*.mjs"] },
  { type: "CommonJS", include: ["**/*.js", "**/*.cjs"] }
];
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 moduleName(modulesRoot, modulePath) {
  const name = import_node_path10.default.relative(modulesRoot, modulePath);
  return import_node_path10.default.sep === "\\" ? name.replaceAll("\\", "/") : name;
}
function withSourceURL(script, scriptPath) {
  if (script.lastIndexOf("//# sourceURL=") !== -1) return script;
  let scriptURL = scriptPath;
  if (maybeGetStringScriptPathIndex(scriptPath) === void 0) {
    scriptURL = (0, import_node_url3.pathToFileURL)(scriptPath);
  }
  const sourceURL = `
//# sourceURL=${scriptURL}
`;
  return script + sourceURL;
}
function getResolveErrorPrefix(referencingPath) {
  const relative4 = import_node_path10.default.relative("", referencingPath);
  return `Unable to resolve "${relative4}" dependency`;
}
var ModuleLocator = class {
  constructor(modulesRoot, additionalModuleNames, rules = [], compatibilityDate, compatibilityFlags) {
    this.modulesRoot = modulesRoot;
    this.additionalModuleNames = additionalModuleNames;
    rules = rules.concat(DEFAULT_MODULE_RULES);
    this.#compiledRules = compileModuleRules(rules);
    this.#nodejsCompatMode = getNodeCompat(
      compatibilityDate,
      compatibilityFlags ?? []
    ).mode;
  }
  #compiledRules;
  #nodejsCompatMode;
  #visitedPaths = /* @__PURE__ */ new Set();
  modules = [];
  visitEntrypoint(code, modulePath) {
    if (this.#visitedPaths.has(modulePath)) return;
    this.#visitedPaths.add(modulePath);
    this.#visitJavaScriptModule(code, modulePath, "ESModule");
  }
  #visitJavaScriptModule(code, modulePath, type) {
    const name = moduleName(this.modulesRoot, modulePath);
    const module2 = createJavaScriptModule(code, name, modulePath, type);
    this.modules.push(module2);
    const isESM = type === "ESModule";
    let root;
    try {
      root = parse7(code, {
        ecmaVersion: "latest",
        sourceType: isESM ? "module" : "script",
        locations: true
      });
    } catch (e) {
      let loc = "";
      if (e.loc?.line !== void 0) {
        loc += `:${e.loc.line}`;
        if (e.loc.column !== void 0) loc += `:${e.loc.column}`;
      }
      throw new MiniflareCoreError(
        "ERR_MODULE_PARSE",
        `Unable to parse "${name}": ${e.message ?? e}
    at ${modulePath}${loc}`
      );
    }
    const visitors = {
      ImportDeclaration: (node) => {
        this.#visitModule(modulePath, name, type, node.source);
      },
      ExportNamedDeclaration: (node) => {
        if (node.source != null) {
          this.#visitModule(modulePath, name, type, node.source);
        }
      },
      ExportAllDeclaration: (node) => {
        this.#visitModule(modulePath, name, type, node.source);
      },
      ImportExpression: (node) => {
        this.#visitModule(modulePath, name, type, node.source);
      },
      CallExpression: isESM ? void 0 : (node) => {
        const argument = node.arguments[0];
        if (node.callee.type === "Identifier" && node.callee.name === "require" && argument !== void 0) {
          this.#visitModule(modulePath, name, type, argument);
        }
      }
    };
    simple(root, visitors);
  }
  #visitModule(referencingPath, referencingName, referencingType, specExpression) {
    if (specExpression.type !== "Literal" || typeof specExpression.value !== "string") {
      const modules = this.modules.map((mod) => {
        const def = convertWorkerModule(mod);
        return `      { type: "${def.type}", path: "${def.path}" }`;
      });
      const modulesConfig = `  new Miniflare({
    ...,
    modules: [
${modules.join(",\n")},
      ...
    ]
  })`;
      const prefix = getResolveErrorPrefix(referencingPath);
      let message = `${prefix}: dynamic module specifiers are unsupported.
You must manually define your modules when constructing Miniflare:
${dim2(modulesConfig)}`;
      if (specExpression.loc != null) {
        const { line, column } = specExpression.loc.start;
        message += `
    at ${referencingPath}:${line}:${column}`;
      }
      throw new MiniflareCoreError("ERR_MODULE_DYNAMIC_SPEC", message);
    }
    const spec = specExpression.value;
    if (
      // `cloudflare:` and `workerd:` imports don't need to be included explicitly
      spec.startsWith("cloudflare:") || spec.startsWith("workerd:") || // Node.js compat v1 requires imports to be prefixed with `node:`
      this.#nodejsCompatMode === "v1" && spec.startsWith("node:") || // Node.js compat modules and v2 can also handle non-prefixed imports
      this.#nodejsCompatMode === "v2" && builtinModulesWithPrefix.includes(spec) || // Async Local Storage mode (node_als) only deals with `node:async_hooks` imports
      this.#nodejsCompatMode === "als" && spec === "node:async_hooks" || // Any "additional" external modules can be ignored
      this.additionalModuleNames.includes(spec)
    ) {
      return;
    }
    if (maybeGetStringScriptPathIndex(referencingName) !== void 0) {
      const prefix = getResolveErrorPrefix(referencingPath);
      throw new MiniflareCoreError(
        "ERR_MODULE_STRING_SCRIPT",
        `${prefix}: imports are unsupported in string \`script\` without defined \`scriptPath\``
      );
    }
    const identifier = import_node_path10.default.resolve(import_node_path10.default.dirname(referencingPath), spec);
    const name = moduleName(this.modulesRoot, identifier);
    if (this.#visitedPaths.has(identifier)) return;
    this.#visitedPaths.add(identifier);
    const rule = this.#compiledRules.find(
      (rule2) => testRegExps(rule2.include, identifier)
    );
    if (rule === void 0) {
      const prefix = getResolveErrorPrefix(referencingPath);
      const isBuiltin = builtinModulesWithPrefix.includes(spec);
      const suggestion = isBuiltin ? SUGGEST_NODE : SUGGEST_BUNDLE;
      throw new MiniflareCoreError(
        "ERR_MODULE_RULE",
        `${prefix} "${spec}": no matching module rules.
${suggestion}`
      );
    }
    const data2 = (0, import_node_fs7.readFileSync)(identifier);
    switch (rule.type) {
      case "ESModule":
      case "CommonJS":
        const code = data2.toString("utf8");
        this.#visitJavaScriptModule(code, identifier, rule.type);
        break;
      case "Text":
        this.modules.push({ name, text: data2.toString("utf8") });
        break;
      case "Data":
        this.modules.push({ name, data: data2 });
        break;
      case "CompiledWasm":
        this.modules.push({ name, wasm: data2 });
        break;
      case "PythonModule":
        this.modules.push({ name, pythonModule: data2.toString("utf-8") });
        break;
      case "PythonRequirement":
        this.modules.push({ name, pythonRequirement: data2.toString("utf-8") });
        break;
      default:
        const exhaustive = rule.type;
        import_node_assert12.default.fail(`Unreachable: ${exhaustive} modules are unsupported`);
    }
  }
};
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_assert12.default.fail(`Unreachable: ${exhaustive} JavaScript modules are unsupported`);
}
var encoder = new import_node_util2.TextEncoder();
var decoder = new import_node_util2.TextDecoder();
function contentsToString(contents38) {
  return typeof contents38 === "string" ? contents38 : decoder.decode(contents38);
}
function contentsToArray(contents38) {
  return typeof contents38 === "string" ? encoder.encode(contents38) : contents38;
}
function convertModuleDefinition(modulesRoot, def) {
  const name = moduleName(modulesRoot, def.path);
  const contents38 = def.contents ?? (0, import_node_fs7.readFileSync)(def.path);
  switch (def.type) {
    case "ESModule":
    case "CommonJS":
      return createJavaScriptModule(
        contentsToString(contents38),
        name,
        import_node_path10.default.resolve(modulesRoot, def.path),
        def.type
      );
    case "Text":
      return { name, text: contentsToString(contents38) };
    case "Data":
      return { name, data: contentsToArray(contents38) };
    case "CompiledWasm":
      return { name, wasm: contentsToArray(contents38) };
    case "PythonModule":
      return { name, pythonModule: contentsToString(contents38) };
    case "PythonRequirement":
      return { name, pythonRequirement: contentsToString(contents38) };
    default:
      const exhaustive = def.type;
      import_node_assert12.default.fail(`Unreachable: ${exhaustive} modules are unsupported`);
  }
}
function convertWorkerModule(mod) {
  const path62 = mod.name;
  (0, import_node_assert12.default)(path62 !== void 0);
  const m2 = mod;
  if ("esModule" in m2) return { path: path62, type: "ESModule" };
  else if ("commonJsModule" in m2) return { path: path62, type: "CommonJS" };
  else if ("text" in m2) return { path: path62, type: "Text" };
  else if ("data" in m2) return { path: path62, type: "Data" };
  else if ("wasm" in m2) return { path: path62, type: "CompiledWasm" };
  else if ("pythonModule" in m2) return { path: path62, type: "PythonModule" };
  else if ("pythonRequirement" in m2) return { path: path62, type: "PythonRequirement" };
  (0, import_node_assert12.default)(
    !("json" in m2 || "fallbackService" in m2),
    "Unreachable: json or fallbackService modules aren't generated"
  );
  const exhaustive = m2;
  import_node_assert12.default.fail(
    `Unreachable: [${Object.keys(exhaustive).join(
      ", "
    )}] modules are unsupported`
  );
}

// src/plugins/core/proxy/client.ts
var import_node_assert15 = __toESM(require("node:assert"));
var import_node_crypto3 = __toESM(require("node:crypto"));
var import_web4 = require("node:stream/web");
var import_node_util3 = __toESM(require("node:util"));
var import_undici6 = require("undici");

// src/plugins/core/proxy/fetch-sync.ts
var import_node_assert14 = __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_fs8 = __toESM(require("node:fs"));
var import_node_path11 = __toESM(require("node:path"));
var import_node_url4 = require("node:url");

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

// 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 object = 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) {
      object = functionName.substring(0, methodStart);
      method = functionName.substring(methodStart + 1);
      const objectEnd = object.indexOf(".Module");
      if (objectEnd > 0) {
        functionName = functionName.substring(objectEnd + 1);
        object = object.substring(0, objectEnd);
      }
    }
  }
  if (method) {
    typeName = object;
    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;
  }
  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;
  }
  // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  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 resolvedSupportPath = require.resolve("@cspotcode/source-map-support");
  const originalSymbolFor = Symbol.for;
  const originalSupport = require.cache[resolvedSupportPath];
  try {
    Symbol.for = (key) => {
      import_node_assert13.default.strictEqual(key, "source-map-support/sharedData");
      return Symbol(key);
    };
    delete require.cache[resolvedSupportPath];
    return require(resolvedSupportPath);
  } finally {
    Symbol.for = originalSymbolFor;
    require.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_assert13.default)(prepareStackTrace !== void 0);
  Error.prepareStackTrace = originalPrepareStackTrace;
  sourceMapper = (retrieveSourceMap, error) => {
    support.install({
      ...sourceMapInstallBaseOptions,
      retrieveFile(_file) {
        return "";
      },
      retrieveSourceMap
    });
    const callSites = parseStack(error.stack ?? "");
    return prepareStackTrace(error, callSites);
  };
  return sourceMapper;
}

// src/plugins/core/errors/index.ts
function maybeGetDiskFile(filePath) {
  try {
    const contents38 = import_node_fs8.default.readFileSync(filePath, "utf8");
    return { path: filePath, contents: contents38 };
  } catch (e) {
    if (e.code !== "ENOENT") throw e;
  }
}
function maybeGetFile2(workerSrcOpts, fileSpecifier) {
  const maybeUrl = maybeParseURL(fileSpecifier);
  if (maybeUrl !== void 0 && maybeUrl.protocol === "file:") {
    const filePath = (0, import_node_url4.fileURLToPath)(maybeUrl);
    for (const srcOpts of workerSrcOpts) {
      if (Array.isArray(srcOpts.modules)) {
        const modulesRoot = srcOpts.modulesRoot ?? "";
        for (const module2 of srcOpts.modules) {
          if (module2.contents !== void 0 && import_node_path11.default.resolve(modulesRoot, module2.path) === filePath) {
            const contents38 = contentsToString(module2.contents);
            return { path: filePath, contents: contents38 };
          }
        }
      } else if ("script" in srcOpts && "scriptPath" in srcOpts && srcOpts.script !== void 0 && srcOpts.scriptPath !== void 0) {
        const modulesRoot = srcOpts.modules && srcOpts.modulesRoot || "";
        if (import_node_path11.default.resolve(modulesRoot, srcOpts.scriptPath) === filePath) {
          return { path: filePath, contents: srcOpts.script };
        }
      }
    }
    return maybeGetDiskFile(filePath);
  }
  const workerIndex = maybeGetStringScriptPathIndex(fileSpecifier);
  if (workerIndex !== void 0) {
    const srcOpts = workerSrcOpts[workerIndex];
    if ("script" in srcOpts && srcOpts.script !== void 0) {
      return { contents: srcOpts.script };
    }
  }
}
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, error, 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_path11.default.dirname(sourceFile.path);
    const sourceMapPath = import_node_path11.default.resolve(root, sourceMapMatch[1]);
    const sourceMapFile = maybeGetDiskFile(sourceMapPath);
    if (sourceMapFile === 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 };
  }
  return getSourceMapper()(retrieveSourceMap, error);
}
var JsonErrorSchema = external_exports.lazy(
  () => external_exports.object({
    message: external_exports.string().optional(),
    name: external_exports.string().optional(),
    stack: external_exports.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 error = new ctor(jsonError.message, { cause });
  if (jsonError.name !== void 0) error.name = jsonError.name;
  error.stack = jsonError.stack;
  error.stack = processStackTrace(
    getSourceMappedStack(workerSrcOpts, error, onSourceMap),
    (line, location) => !location.includes(".wrangler/tmp") && !location.includes("wrangler/templates/middleware") ? line : null
  );
  return error;
}
async function handlePrettyErrorRequest(log2, workerSrcOpts, request4) {
  const caught = JsonErrorSchema.parse(await request4.json());
  const sourcesContentMap = /* @__PURE__ */ new Map();
  const error = 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_path11.default.resolve(
            import_node_path11.default.dirname(sourceMapPath),
            sourceMap.sourceRoot ?? "",
            source
          );
          sourcesContentMap.set(fullSourcePath, sourceContent);
        }
      }
    }
  );
  log2.error(error);
  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 Response2(error.stack, { status: 500 });
  }
  const { Youch } = require("youch");
  const youch = new Youch();
  youch.defineSourceLoader(async (stackFrame) => {
    if (!stackFrame.fileName) {
      return;
    }
    if (stackFrame.type === "native" || stackFrame.fileName.startsWith("cloudflare:") || stackFrame.fileName.startsWith("node:")) {
      stackFrame.type = "native";
      return;
    }
    if (!import_node_fs8.default.existsSync(stackFrame.fileName)) {
      stackFrame.fileType = void 0;
    }
    const workerIndex = maybeGetStringScriptPathIndex(stackFrame.fileName);
    if (workerIndex !== void 0) {
      const srcOpts = workerSrcOpts[workerIndex];
      if ("script" in srcOpts && srcOpts.script !== void 0) {
        return { contents: srcOpts.script };
      }
    }
    const sourcesContent = sourcesContentMap.get(stackFrame.fileName);
    if (sourcesContent) {
      return { contents: sourcesContent };
    }
    try {
      const contents38 = import_node_fs8.default.readFileSync(stackFrame.fileName, {
        encoding: "utf8"
      });
      return { contents: contents38 };
    } catch {
      return;
    }
  });
  youch.useTransformer((error2) => {
    error2.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("");
  });
  const html = await youch.toHTML(error, {
    request: {
      url: `${request4.cf?.prettyErrorOriginalUrl ?? request4.url}`,
      method: request4.method,
      headers: getHeaders(request4)
    }
  });
  return new Response2(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(url38, init2) {
    this.#ensureWorker();
    Atomics.store(
      this.#notifyHandle,
      /* index */
      0,
      /* value */
      0
    );
    const id = this.#nextId++;
    this.#channel.port1.postMessage({
      id,
      method: init2.method,
      url: url38.toString(),
      headers: init2.headers,
      body: init2.body
    });
    Atomics.wait(
      this.#notifyHandle,
      /* index */
      0,
      /* value */
      0
    );
    const message = (0, import_node_worker_threads.receiveMessageOnPort)(
      this.#channel.port1
    )?.message;
    (0, import_node_assert14.default)(message?.id === id);
    if ("response" in message) {
      const { status: status2, headers: rawHeaders, body } = message.response;
      const headers = new import_undici4.Headers(rawHeaders);
      const stack = headers.get(CoreHeaders.ERROR_STACK);
      if (status2 === 500 && stack !== null && body !== null) {
        (0, import_node_assert14.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_buffer4 = require("node:buffer");
var import_consumers = require("node:stream/consumers");
var import_web3 = require("node:stream/web");
var import_undici5 = 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_buffer4.Blob,
  File,
  Headers: import_undici5.Headers,
  Request,
  Response: Response2,
  isReadableStream(value) {
    return value instanceof import_web3.ReadableStream;
  },
  bufferReadableStream(stream) {
    return (0, import_consumers.arrayBuffer)(stream);
  },
  unbufferReadableStream(buffer) {
    return new import_node_buffer4.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_crypto3.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(url38, dispatchFetch) {
    this.url = url38;
    this.dispatchFetch = dispatchFetch;
    this.#finalizationRegistry = new FinalizationRegistry(this.#finalizeProxy);
  }
  // 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_util3.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() {
    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 = stringify2(this.target, reducers);
  }
  #version;
  #stringifiedTarget;
  #knownValues = /* @__PURE__ */ new Map();
  #knownDescriptors = /* @__PURE__ */ new Map();
  #knownOwnKeys;
  revivers = {
    ...revivers,
    Native: (value) => {
      (0, import_node_assert15.default)(Array.isArray(value));
      const [address, name, isFunction] = value;
      (0, import_node_assert15.default)(typeof address === "number");
      (0, import_node_assert15.default)(typeof name === "string");
      (0, import_node_assert15.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]: stringify2(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: (transform) => {
          return transformer(target2, stream, [
            ...operations,
            { type: "transform", arguments: [transform] }
          ]);
        },
        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_util3.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_assert15.default)(res.status === 200);
      return result;
    }
  }
  async #parseAsyncResponse(resPromise) {
    const res = await resPromise;
    (0, import_node_assert15.default)(!isClientError(res.status));
    const typeHeader = res.headers.get(CoreHeaders.OP_RESULT_TYPE);
    if (typeHeader === "Promise, ReadableStream") return res.body;
    (0, import_node_assert15.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_assert15.default)(!Number.isNaN(stringifiedSize));
      (0, import_node_assert15.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_assert15.default)(!isClientError(syncRes.status));
    (0, import_node_assert15.default)(syncRes.body !== null);
    (0, import_node_assert15.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_assert15.default)(arg instanceof import_undici6.Headers);
        (0, import_node_assert15.default)(result instanceof import_undici6.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/services.ts
var kCurrentWorker = /* @__PURE__ */ Symbol.for("miniflare.kCurrentWorker");
var HttpOptionsHeaderSchema = external_exports.object({
  name: external_exports.string(),
  // name should be required
  value: external_exports.ostring()
  // If omitted, the header will be removed
});
var HttpOptionsSchema = external_exports.object({
  style: external_exports.nativeEnum(HttpOptions_Style).optional(),
  forwardedProtoHeader: external_exports.ostring(),
  cfBlobHeader: external_exports.ostring(),
  injectRequestHeaders: HttpOptionsHeaderSchema.array().optional(),
  injectResponseHeaders: HttpOptionsHeaderSchema.array().optional()
}).transform((options) => ({
  ...options,
  capnpConnectHost: HOST_CAPNP_CONNECT
}));
var TlsOptionsKeypairSchema = external_exports.object({
  privateKey: external_exports.ostring(),
  certificateChain: external_exports.ostring()
});
var TlsOptionsSchema = external_exports.object({
  keypair: TlsOptionsKeypairSchema.optional(),
  requireClientCerts: external_exports.oboolean(),
  trustBrowserCas: external_exports.oboolean(),
  trustedCertificates: external_exports.string().array().optional(),
  minVersion: external_exports.nativeEnum(TlsOptions_Version).optional(),
  cipherList: external_exports.ostring()
});
var NetworkSchema = external_exports.object({
  allow: external_exports.string().array().optional(),
  deny: external_exports.string().array().optional(),
  tlsOptions: TlsOptionsSchema.optional()
});
var ExternalServerSchema = external_exports.intersection(
  external_exports.object({ address: external_exports.string() }),
  // address should be required
  external_exports.union([
    external_exports.object({ http: external_exports.optional(HttpOptionsSchema) }),
    external_exports.object({
      https: external_exports.optional(
        external_exports.object({
          options: HttpOptionsSchema.optional(),
          tlsOptions: TlsOptionsSchema.optional(),
          certificateHost: external_exports.ostring()
        })
      )
    })
  ])
);
var DiskDirectorySchema = external_exports.object({
  path: external_exports.string(),
  // path should be required
  writable: external_exports.oboolean()
});
var CustomNodeServiceSchema = external_exports.custom((v2) => typeof v2 === "function");
var CustomFetchServiceSchema = external_exports.custom((v2) => typeof v2 === "function");
var ServiceDesignatorSchema = external_exports.union([
  external_exports.string(),
  external_exports.literal(kCurrentWorker),
  external_exports.object({
    name: external_exports.union([external_exports.string(), external_exports.literal(kCurrentWorker)]),
    entrypoint: external_exports.ostring(),
    props: external_exports.record(external_exports.unknown()).optional(),
    remoteProxyConnectionString: external_exports.custom().optional()
  }),
  external_exports.object({ network: NetworkSchema }),
  external_exports.object({ external: ExternalServerSchema }),
  external_exports.object({ disk: DiskDirectorySchema }),
  external_exports.object({ node: CustomNodeServiceSchema }),
  CustomFetchServiceSchema
]);

// 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_fs9.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_util4.TextEncoder();
function createFetchMock() {
  return new import_undici7.MockAgent();
}
var WrappedBindingSchema = external_exports.object({
  scriptName: external_exports.string(),
  entrypoint: external_exports.string().optional(),
  bindings: external_exports.record(JsonSchema).optional()
});
var UnusableStringSchema = external_exports.string().transform(() => void 0);
var UnsafeDirectSocketSchema = external_exports.object({
  host: external_exports.ostring(),
  port: external_exports.onumber(),
  serviceName: external_exports.ostring(),
  entrypoint: external_exports.ostring(),
  proxy: external_exports.oboolean()
});
var ExternalPluginSpecifier = external_exports.object({
  package: external_exports.string(),
  name: external_exports.string()
});
var CoreOptionsSchemaInput = external_exports.intersection(
  SourceOptionsSchema,
  external_exports.object({
    name: external_exports.string().optional(),
    rootPath: UnusableStringSchema.optional(),
    compatibilityDate: external_exports.string().optional(),
    compatibilityFlags: external_exports.string().array().optional(),
    unsafeInspectorProxy: external_exports.boolean().optional(),
    routes: external_exports.string().array().optional(),
    bindings: external_exports.record(JsonSchema).optional(),
    wasmBindings: external_exports.record(external_exports.union([PathSchema, external_exports.instanceof(Uint8Array)])).optional(),
    textBlobBindings: external_exports.record(PathSchema).optional(),
    dataBlobBindings: external_exports.record(external_exports.union([PathSchema, external_exports.instanceof(Uint8Array)])).optional(),
    serviceBindings: external_exports.record(ServiceDesignatorSchema).optional(),
    wrappedBindings: external_exports.record(external_exports.union([external_exports.string(), WrappedBindingSchema])).optional(),
    outboundService: ServiceDesignatorSchema.optional(),
    fetchMock: external_exports.instanceof(import_undici7.MockAgent).optional(),
    // TODO(soon): remove this in favour of per-object `unsafeUniqueKey: kEphemeralUniqueKey`
    unsafeEphemeralDurableObjects: external_exports.boolean().optional(),
    unsafeDirectSockets: UnsafeDirectSocketSchema.array().optional(),
    unsafeEvalBinding: external_exports.string().optional(),
    unsafeUseModuleFallbackService: external_exports.boolean().optional(),
    /** Used to set the vitest pool worker SELF binding to point to the Router Worker if there are assets.
     (If there are assets but we're not using vitest, the miniflare entry worker can point directly to
     Router Worker)
     */
    hasAssetsAndIsVitest: external_exports.boolean().optional(),
    tails: external_exports.array(ServiceDesignatorSchema).optional(),
    streamingTails: external_exports.array(ServiceDesignatorSchema).optional(),
    // Strip the CF-Connecting-IP header from outbound fetches
    stripCfConnectingIp: external_exports.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_exports.string().optional(),
    /** Configuration used to connect to the container engine */
    containerEngine: external_exports.union([
      external_exports.object({
        localDocker: external_exports.object({
          socketPath: external_exports.string(),
          containerEgressInterceptorImage: external_exports.string().optional()
        })
      }),
      external_exports.string()
    ]).optional(),
    unsafeBindings: external_exports.array(
      external_exports.object({
        name: external_exports.string(),
        type: external_exports.string(),
        plugin: ExternalPluginSpecifier,
        options: external_exports.record(JsonSchema)
      })
    ).optional()
  })
);
var CoreOptionsSchema = CoreOptionsSchemaInput.transform((value) => {
  const fetchMock = value.fetchMock;
  if (fetchMock !== void 0) {
    if (value.outboundService !== void 0) {
      throw new MiniflareCoreError(
        "ERR_MULTIPLE_OUTBOUNDS",
        "Only one of `outboundService` or `fetchMock` may be specified per worker"
      );
    }
    value.fetchMock = void 0;
    value.outboundService = (req) => fetch4(req, { dispatcher: fetchMock });
  }
  return value;
});
var WorkerdStructuredLogSchema = external_exports.object({
  timestamp: external_exports.number(),
  level: external_exports.string(),
  message: external_exports.string()
});
var CoreSharedOptionsSchema = external_exports.object({
  rootPath: UnusableStringSchema.optional(),
  host: external_exports.string().optional(),
  port: external_exports.number().optional(),
  https: external_exports.boolean().optional(),
  httpsKey: external_exports.string().optional(),
  httpsKeyPath: external_exports.string().optional(),
  httpsCert: external_exports.string().optional(),
  httpsCertPath: external_exports.string().optional(),
  inspectorPort: external_exports.number().optional(),
  inspectorHost: external_exports.string().optional(),
  verbose: external_exports.boolean().optional(),
  log: external_exports.instanceof(Log).optional(),
  handleRuntimeStdio: external_exports.function(external_exports.tuple([external_exports.instanceof(import_node_stream2.Readable), external_exports.instanceof(import_node_stream2.Readable)])).optional(),
  handleStructuredLogs: external_exports.function(external_exports.tuple([WorkerdStructuredLogSchema])).returns(external_exports.void()).optional(),
  upstream: external_exports.string().optional(),
  // TODO: add back validation of cf object
  cf: external_exports.union([external_exports.boolean(), external_exports.string(), external_exports.record(external_exports.any())]).optional(),
  liveReload: external_exports.boolean().optional(),
  // Enable auto service / durable objects discovery with the dev registry
  unsafeDevRegistryPath: external_exports.string().optional(),
  // Enable External Durable Objects Proxy / Internal DOs registration
  unsafeDevRegistryDurableObjectProxy: external_exports.boolean().default(false),
  // Called when external workers this instance depends on are updated in the dev registry
  unsafeHandleDevRegistryUpdate: external_exports.function(external_exports.tuple([external_exports.custom()])).optional(),
  // This is a shared secret between a proxy server and miniflare that can be
  // passed in a header to prove that the request came from the proxy and not
  // some malicious attacker.
  unsafeProxySharedSecret: external_exports.string().optional(),
  unsafeModuleFallbackService: CustomFetchServiceSchema.optional(),
  // Keep blobs when deleting/overwriting keys, required for stacked storage
  unsafeStickyBlobs: external_exports.boolean().optional(),
  // Enable directly triggering user Worker handlers with paths like `/cdn-cgi/handler/scheduled`
  unsafeTriggerHandlers: external_exports.boolean().optional(),
  // Enable the local explorer at /cdn-cgi/explorer
  unsafeLocalExplorer: external_exports.boolean().optional(),
  // Enable logging requests
  logRequests: external_exports.boolean().default(true),
  // Path to the root directory for persisting data
  // Used as the default for all plugins with the plugin name as the subdirectory name
  defaultPersistRoot: external_exports.string().optional(),
  // Strip the MF-DISABLE_PRETTY_ERROR header from user request
  stripDisablePrettyError: external_exports.boolean().default(true),
  // Whether to get structured logs from workerd or not (defaults to `true` is a
  // `handleStructuredLogs` is set, to `false` otherwise)
  // This option is useful in combination with a custom handleRuntimeStdio.
  structuredWorkerdLogs: external_exports.boolean().optional(),
  // Enable telemetry for the local explorer.
  telemetry: external_exports.object({
    enabled: external_exports.boolean().default(false),
    deviceId: external_exports.string().optional()
  }).default({ enabled: false })
}).refine(
  ({ structuredWorkerdLogs, handleStructuredLogs }) => {
    if (structuredWorkerdLogs === false && handleStructuredLogs) {
      return false;
    }
    return true;
  },
  {
    message: "A `handleStructuredLogs` has been provided but `structuredWorkerdLogs` is set to `false`"
  }
);
var CORE_PLUGIN_NAME2 = "core";
var LIVE_RELOAD_SCRIPT_TEMPLATE = (port) => `<script defer type="application/javascript">
(function () {
  // Miniflare Live Reload
  var url = new URL("/cdn-cgi/mf/reload", location.origin);
  url.protocol = url.protocol.replace("http", "ws");
  url.port = ${port};
  function reload() { location.reload(); }
  function connect(reconnected) {
    var ws = new WebSocket(url);
    if (reconnected) ws.onopen = reload;
    ws.onclose = function(e) {
      e.code === 1012 ? reload() : e.code === 1000 || e.code === 1001 || setTimeout(connect, 1000, true);
    }
  }
  connect();
})();
</script>`;
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, hasAssetsAndIsVitest = false) {
  let serviceName;
  let entrypoint;
  let props;
  if (typeof service === "function") {
    serviceName = getCustomFetchServiceName(workerIndex, kind, name);
  } else if (typeof service === "object") {
    if ("node" in service) {
      serviceName = getCustomNodeServiceName(workerIndex, kind, name);
    } else if ("remoteProxyConnectionString" in service) {
      (0, import_node_assert16.default)("name" in service && typeof service.name === "string");
      serviceName = `${CORE_PLUGIN_NAME2}:remote-proxy-service:${workerIndex}:${name}`;
    } else if ("name" in service) {
      if (service.name === kCurrentWorker) {
        serviceName = getUserServiceName(refererName);
      } else {
        serviceName = getUserServiceName(service.name);
      }
      entrypoint = service.entrypoint;
      if (service.props) {
        props = { json: JSON.stringify(service.props) };
      }
    } else {
      serviceName = getBuiltinServiceName(workerIndex, kind, name);
    }
  } else if (service === kCurrentWorker) {
    serviceName = hasAssetsAndIsVitest ? `${RPC_PROXY_SERVICE_NAME}:${refererName}` : getUserServiceName(refererName);
  } else {
    serviceName = getUserServiceName(service);
  }
  return { name: serviceName, entrypoint, props };
}
function maybeGetCustomServiceService(workerIndex, kind, name, service) {
  if (typeof service === "function") {
    return {
      name: getCustomFetchServiceName(workerIndex, kind, name),
      worker: {
        serviceWorkerScript: SCRIPT_CUSTOM_FETCH_SERVICE,
        compatibilityDate: "2022-09-01",
        bindings: [
          {
            name: CoreBindings.TEXT_CUSTOM_SERVICE,
            text: `${workerIndex}/${kind}${name}`
          },
          WORKER_BINDING_SERVICE_LOOPBACK
        ]
      }
    };
  } else if (typeof service === "object" && "node" in service) {
    return {
      name: getCustomNodeServiceName(workerIndex, kind, name),
      worker: {
        serviceWorkerScript: SCRIPT_CUSTOM_NODE_SERVICE,
        compatibilityDate: "2022-09-01",
        bindings: [
          {
            name: CoreBindings.TEXT_CUSTOM_SERVICE,
            text: `${workerIndex}/${kind}${name}`
          },
          WORKER_BINDING_SERVICE_LOOPBACK
        ]
      }
    };
  } else if (typeof service === "object" && !("name" in service)) {
    return {
      name: getBuiltinServiceName(workerIndex, kind, name),
      ...service
    };
  } else if (typeof service === "object" && service.remoteProxyConnectionString !== void 0) {
    (0, import_node_assert16.default)(
      service.remoteProxyConnectionString && service.name && typeof service.name === "string"
    );
    return {
      name: `${CORE_PLUGIN_NAME2}:remote-proxy-service:${workerIndex}:${name}`,
      worker: remoteProxyClientWorker(
        service.remoteProxyConnectionString,
        name
      )
    };
  }
}
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 buildBindings(bindings) {
  return Object.entries(bindings).map(([name, value]) => {
    if (typeof value === "string") {
      return {
        name,
        text: value
      };
    } else {
      return {
        name,
        json: JSON.stringify(value)
      };
    }
  });
}
var WRAPPED_MODULE_PREFIX = "miniflare-internal:wrapped:";
function workerNameToWrappedModule(workerName) {
  return WRAPPED_MODULE_PREFIX + workerName;
}
function maybeWrappedModuleToWorkerName(name) {
  if (name.startsWith(WRAPPED_MODULE_PREFIX)) {
    return name.substring(WRAPPED_MODULE_PREFIX.length);
  }
}
function getStripCfConnectingIpName(workerIndex) {
  return `strip-cf-connecting-ip:${workerIndex}`;
}
function getGlobalOutbound(workerIndex, options) {
  return options.outboundService === void 0 ? void 0 : getCustomServiceDesignator(
    /* referrer */
    options.name,
    workerIndex,
    "$" /* KNOWN */,
    CUSTOM_SERVICE_KNOWN_OUTBOUND,
    options.outboundService,
    options.hasAssetsAndIsVitest
  );
}
var CORE_PLUGIN = {
  options: CoreOptionsSchema,
  sharedOptions: CoreSharedOptionsSchema,
  getBindings(options, workerIndex) {
    const bindings = [];
    if (options.bindings !== void 0) {
      bindings.push(...buildBindings(options.bindings));
    }
    if (options.wasmBindings !== void 0) {
      bindings.push(
        ...Object.entries(options.wasmBindings).map(
          ([name, value]) => typeof value === "string" ? import_promises6.default.readFile(value).then((wasmModule) => ({ name, wasmModule })) : { name, wasmModule: value }
        )
      );
    }
    if (options.textBlobBindings !== void 0) {
      bindings.push(
        ...Object.entries(options.textBlobBindings).map(
          ([name, path62]) => import_promises6.default.readFile(path62, "utf8").then((text) => ({ name, text }))
        )
      );
    }
    if (options.dataBlobBindings !== void 0) {
      bindings.push(
        ...Object.entries(options.dataBlobBindings).map(
          ([name, value]) => typeof value === "string" ? import_promises6.default.readFile(value).then((data2) => ({ name, data: data2 })) : { name, data: value }
        )
      );
    }
    if (options.serviceBindings !== void 0) {
      bindings.push(
        ...Object.entries(options.serviceBindings).map(([name, service]) => {
          return {
            name,
            service: getCustomServiceDesignator(
              /* referrer */
              options.name,
              workerIndex,
              "#" /* UNKNOWN */,
              name,
              service,
              options.hasAssetsAndIsVitest
            )
          };
        })
      );
    }
    if (options.wrappedBindings !== void 0) {
      bindings.push(
        ...Object.entries(options.wrappedBindings).map(([name, designator]) => {
          const isObject = typeof designator === "object";
          const scriptName = isObject ? designator.scriptName : designator;
          const entrypoint = isObject ? designator.entrypoint : void 0;
          const bindings2 = isObject ? designator.bindings : void 0;
          const moduleName2 = workerNameToWrappedModule(scriptName);
          const innerBindings = bindings2 === void 0 ? [] : buildBindings(bindings2);
          return {
            name,
            wrapped: { moduleName: moduleName2, entrypoint, innerBindings }
          };
        })
      );
    }
    if (options.unsafeEvalBinding !== void 0) {
      bindings.push({
        name: options.unsafeEvalBinding,
        unsafeEval: kVoid
      });
    }
    return Promise.all(bindings);
  },
  async getNodeBindings(options) {
    const bindingEntries3 = [];
    if (options.bindings !== void 0) {
      bindingEntries3.push(
        ...Object.entries(options.bindings).map(([name, value]) => [
          name,
          JSON.parse(JSON.stringify(value))
        ])
      );
    }
    if (options.wasmBindings !== void 0) {
      bindingEntries3.push(
        ...Object.entries(options.wasmBindings).map(
          ([name, value]) => typeof value === "string" ? import_promises6.default.readFile(value).then((buffer) => [name, new WebAssembly.Module(buffer)]) : [name, new WebAssembly.Module(value)]
        )
      );
    }
    if (options.textBlobBindings !== void 0) {
      bindingEntries3.push(
        ...Object.entries(options.textBlobBindings).map(
          ([name, path62]) => import_promises6.default.readFile(path62, "utf8").then((text) => [name, text])
        )
      );
    }
    if (options.dataBlobBindings !== void 0) {
      bindingEntries3.push(
        ...Object.entries(options.dataBlobBindings).map(
          ([name, value]) => typeof value === "string" ? import_promises6.default.readFile(value).then((buffer) => [name, viewToBuffer(buffer)]) : [name, viewToBuffer(value)]
        )
      );
    }
    if (options.serviceBindings !== void 0) {
      bindingEntries3.push(
        ...Object.keys(options.serviceBindings).map((name) => [
          name,
          new ProxyNodeBinding()
        ])
      );
    }
    if (options.wrappedBindings !== void 0) {
      bindingEntries3.push(
        ...Object.keys(options.wrappedBindings).map((name) => [
          name,
          new ProxyNodeBinding()
        ])
      );
    }
    return Object.fromEntries(await Promise.all(bindingEntries3));
  },
  async getServices({
    log: _log,
    options,
    sharedOptions,
    workerBindings,
    workerIndex,
    wrappedBindingNames,
    durableObjectClassNames,
    additionalModules,
    loopbackPort
  }) {
    const additionalModuleNames = additionalModules.map(({ name: name2 }) => name2);
    const workerScript = getWorkerScript(
      options,
      workerIndex,
      additionalModuleNames
    );
    if ("modules" in workerScript) {
      const subDirs = new Set(
        workerScript.modules.map(({ name: name2 }) => import_node_path12.default.posix.dirname(name2))
      );
      subDirs.delete(".");
      for (const module2 of additionalModules) {
        workerScript.modules.push(module2);
        for (const subDir of subDirs) {
          const relativePath = import_node_path12.default.posix.relative(subDir, module2.name);
          const relativePathString = JSON.stringify(relativePath);
          workerScript.modules.push({
            name: import_node_path12.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 name = options.name ?? "";
    const serviceName = getUserServiceName(options.name);
    const classNames = durableObjectClassNames.get(serviceName);
    const classNamesEntries = Array.from(classNames ?? []);
    const sqliteClasses = classNamesEntries.filter(
      ([, { enableSql }]) => enableSql
    );
    if (sharedOptions.unsafeLocalExplorer && // 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(
      options.compatibilityDate ?? FALLBACK_COMPATIBILITY_DATE
    );
    const isWrappedBinding = wrappedBindingNames.has(name);
    const services = [];
    const extensions = [];
    if (isWrappedBinding) {
      let invalidWrapped2 = function(reason) {
        const message = `Cannot use ${stringName} for wrapped binding because ${reason}`;
        throw new MiniflareCoreError("ERR_INVALID_WRAPPED", message);
      };
      var invalidWrapped = invalidWrapped2;
      const stringName = JSON.stringify(name);
      if (workerIndex === 0) {
        invalidWrapped2(
          `it's the entrypoint.
Ensure ${stringName} isn't the first entry in the \`workers\` array.`
        );
      }
      if (!("modules" in workerScript)) {
        invalidWrapped2(
          `it's a service worker.
Ensure ${stringName} sets \`modules\` to \`true\` or an array of modules`
        );
      }
      if (workerScript.modules.length !== 1) {
        invalidWrapped2(
          `it isn't a single module.
Ensure ${stringName} doesn't include unbundled \`import\`s.`
        );
      }
      const firstModule = workerScript.modules[0];
      if (!("esModule" in firstModule)) {
        invalidWrapped2("it isn't a single ES module");
      }
      if (options.compatibilityDate !== void 0) {
        invalidWrapped2(
          "it defines a compatibility date.\nWrapped bindings use the compatibility date of the worker with the binding."
        );
      }
      if (options.compatibilityFlags?.length) {
        invalidWrapped2(
          "it defines compatibility flags.\nWrapped bindings use the compatibility flags of the worker with the binding."
        );
      }
      if (options.outboundService !== void 0) {
        invalidWrapped2(
          "it defines an outbound service.\nWrapped bindings use the outbound service of the worker with the binding."
        );
      }
      extensions.push({
        modules: [
          {
            name: workerNameToWrappedModule(name),
            esModule: firstModule.esModule,
            internal: true
          }
        ]
      });
    } else {
      services.push({
        name: serviceName,
        worker: {
          ...workerScript,
          compatibilityDate,
          compatibilityFlags: options.compatibilityFlags,
          bindings: workerBindings,
          durableObjectNamespaces: classNamesEntries.map(
            ([
              className,
              {
                enableSql,
                unsafeUniqueKey,
                unsafePreventEviction: preventEviction,
                container
              }
            ]) => unsafeUniqueKey === kUnsafeEphemeralUniqueKey ? {
              className,
              enableSql,
              ephemeralLocal: kVoid,
              preventEviction,
              container
            } : {
              className,
              enableSql,
              // This `uniqueKey` will (among other things) be used as part of the
              // path when persisting to the file-system. `-` is invalid in
              // JavaScript class names, but safe on filesystems (incl. Windows).
              uniqueKey: unsafeUniqueKey ?? `${options.name ?? ""}-${className}`,
              preventEviction,
              container
            }
          ),
          durableObjectStorage: classNamesEntries.length === 0 ? void 0 : options.unsafeEphemeralDurableObjects ? { inMemory: kVoid } : { localDisk: DURABLE_OBJECTS_STORAGE_SERVICE_NAME },
          globalOutbound: options.stripCfConnectingIp ? { name: getStripCfConnectingIpName(workerIndex) } : getGlobalOutbound(workerIndex, options),
          cacheApiOutbound: { name: getCacheServiceName(workerIndex) },
          moduleFallback: options.unsafeUseModuleFallbackService && sharedOptions.unsafeModuleFallbackService !== void 0 ? `localhost:${loopbackPort}` : void 0,
          tails: options.tails?.map((service) => {
            return getCustomServiceDesignator(
              /* referrer */
              options.name,
              workerIndex,
              "#" /* UNKNOWN */,
              name,
              service,
              options.hasAssetsAndIsVitest
            );
          }),
          streamingTails: options.streamingTails?.map(
            (service) => {
              return getCustomServiceDesignator(
                /* referrer */
                options.name,
                workerIndex,
                "#" /* UNKNOWN */,
                name,
                service,
                options.hasAssetsAndIsVitest
              );
            }
          ),
          containerEngine: getContainerEngine(options.containerEngine)
        }
      });
    }
    if (options.serviceBindings !== void 0) {
      for (const [name2, service] of Object.entries(options.serviceBindings)) {
        const maybeService = maybeGetCustomServiceService(
          workerIndex,
          "#" /* UNKNOWN */,
          name2,
          service
        );
        if (maybeService !== void 0) services.push(maybeService);
      }
    }
    for (const service of options.tails ?? []) {
      const maybeService = maybeGetCustomServiceService(
        workerIndex,
        "#" /* UNKNOWN */,
        name,
        service
      );
      if (maybeService !== void 0) services.push(maybeService);
    }
    for (const service of options.streamingTails ?? []) {
      const maybeService = maybeGetCustomServiceService(
        workerIndex,
        "#" /* UNKNOWN */,
        name,
        service
      );
      if (maybeService !== void 0) services.push(maybeService);
    }
    if (options.outboundService !== void 0) {
      const maybeService = maybeGetCustomServiceService(
        workerIndex,
        "$" /* KNOWN */,
        CUSTOM_SERVICE_KNOWN_OUTBOUND,
        options.outboundService
      );
      if (maybeService !== void 0) services.push(maybeService);
    }
    if (options.stripCfConnectingIp) {
      const workerName = options.name ?? "worker";
      const cfWorkerValue = options.zone ?? `${workerName}.example.com`;
      services.push({
        name: getStripCfConnectingIpName(workerIndex),
        worker: {
          modules: [
            {
              name: "index.js",
              esModule: strip_cf_connecting_ip_worker_default()
            }
          ],
          compatibilityDate: "2025-01-01",
          compatibilityFlags: ["connect_pass_through", "experimental"],
          bindings: [
            {
              name: "CF_WORKER_ZONE",
              text: cfWorkerValue
            }
          ],
          globalOutbound: getGlobalOutbound(workerIndex, options)
        }
      });
    }
    return { services, extensions };
  }
};
function getGlobalServices({
  sharedOptions,
  allWorkerRoutes,
  fallbackWorkerName,
  loopbackPort,
  log: log2,
  proxyBindings,
  durableObjectClassNames,
  workflowOptions,
  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) }
    }
  ];
  if (sharedOptions.unsafeLocalExplorer) {
    serviceEntryBindings.push({
      name: CoreBindings.SERVICE_LOCAL_EXPLORER,
      service: {
        name: SERVICE_LOCAL_EXPLORER
      }
    });
  }
  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)
    });
  }
  if (sharedOptions.liveReload) {
    const liveReloadScript = LIVE_RELOAD_SCRIPT_TEMPLATE(loopbackPort);
    serviceEntryBindings.push({
      name: CoreBindings.DATA_LIVE_RELOAD_SCRIPT,
      data: encoder2.encode(liveReloadScript)
    });
  }
  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: "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 (sharedOptions.unsafeLocalExplorer) {
    const localExplorerUiPath = import_node_path12.default.join(__dirname, "../local-explorer-ui");
    if (!(0, import_node_fs9.existsSync)(localExplorerUiPath)) {
      throw new MiniflareCoreError(
        "ERR_MISSING_EXPLORER_UI",
        `Local Explorer UI assets not found at expected path: ${localExplorerUiPath}`
      );
    }
    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
      })
    );
  }
  return services;
}
function getWorkerScript(options, workerIndex, additionalModuleNames) {
  const modulesRoot = import_node_path12.default.resolve(
    ("modulesRoot" in options ? options.modulesRoot : void 0) ?? ""
  );
  if (Array.isArray(options.modules)) {
    return {
      modules: options.modules.map(
        (module2) => convertModuleDefinition(modulesRoot, module2)
      )
    };
  }
  let code;
  if ("script" in options && options.script !== void 0) {
    code = options.script;
  } else if ("scriptPath" in options && options.scriptPath !== void 0) {
    code = (0, import_node_fs9.readFileSync)(options.scriptPath, "utf8");
  } else {
    import_node_assert16.default.fail("Unreachable: Workers must have code");
  }
  const scriptPath = options.scriptPath ?? buildStringScriptPath(workerIndex);
  if (options.modules) {
    const locator = new ModuleLocator(
      modulesRoot,
      additionalModuleNames,
      options.modulesRules,
      options.compatibilityDate,
      options.compatibilityFlags
    );
    locator.visitEntrypoint(code, scriptPath);
    return { modules: locator.modules };
  } else {
    code = withSourceURL(code, scriptPath);
    return { serviceWorkerScript: code };
  }
}
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/schema.ts
var AssetsOptionsSchema = external_exports.object({
  assets: external_exports.object({
    // User Worker name or vitest runner - this is only ever set inside miniflare
    // The assets plugin needs access to the worker name to create the router worker - user worker binding
    workerName: external_exports.string().optional(),
    directory: PathSchema,
    binding: external_exports.string().optional(),
    routerConfig: RouterConfigSchema.optional(),
    assetConfig: AssetConfigSchema.omit({
      compatibility_date: true,
      compatibility_flags: true
    }).optional()
  }).optional(),
  compatibilityDate: external_exports.string().optional(),
  compatibilityFlags: external_exports.string().array().optional()
});

// src/plugins/assets/index.ts
var ASSETS_PLUGIN = {
  options: AssetsOptionsSchema,
  async getBindings(options) {
    if (!options.assets?.binding) {
      return [];
    }
    return [
      {
        // binding between User Worker and Asset Worker
        name: options.assets.binding,
        service: {
          name: `${ASSETS_SERVICE_NAME}:${options.assets.workerName}`
        }
      }
    ];
  },
  async getNodeBindings(options) {
    if (!options.assets?.binding) {
      return {};
    }
    return {
      [options.assets.binding]: new ProxyNodeBinding()
    };
  },
  async getServices({ options, log: log2 }) {
    if (!options.assets) {
      return [];
    }
    const storageServiceName = `${ASSETS_PLUGIN_NAME}:storage`;
    const storageService = {
      name: storageServiceName,
      disk: {
        path: options.assets.directory,
        writable: true,
        allowDotfiles: true
      }
    };
    const { encodedAssetManifest, assetsReverseMap } = await buildAssetManifest(
      options.assets.directory
    );
    const redirectsFile = (0, import_node_path13.join)(options.assets.directory, REDIRECTS_FILENAME);
    const headersFile = (0, import_node_path13.join)(options.assets.directory, 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: (error) => log2.error(error)
    };
    let parsedRedirects;
    if (redirectsContents !== void 0) {
      const redirects = parseRedirects(redirectsContents, {
        htmlHandling: options.assets.assetConfig?.html_handling
      });
      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 assetConfig = {
      compatibility_date: options.compatibilityDate,
      compatibility_flags: options.compatibilityFlags,
      ...options.assets.assetConfig,
      redirects: parsedRedirects,
      headers: parsedHeaders,
      debug: true,
      has_static_routing: Boolean(options.assets.routerConfig?.static_routing)
    };
    const id = options.assets.workerName;
    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"],
        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"],
        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(options.assets.routerConfig ?? {})
          }
        ]
      }
    };
    const assetsProxyService = {
      name: `${RPC_PROXY_SERVICE_NAME}:${id}`,
      worker: {
        compatibilityDate: "2024-08-01",
        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 (dir) => {
  const { manifest, assetsReverseMap } = await walk(dir);
  const sortedAssetManifest = sortManifest(manifest);
  const encodedAssetManifest = encodeManifest(sortedAssetManifest);
  return { encodedAssetManifest, assetsReverseMap };
};
var walk = async (dir) => {
  const files = await import_promises7.default.readdir(dir, { recursive: true });
  const manifest = [];
  const assetsReverseMap = {};
  const { assetsIgnoreFunction } = await createAssetsIgnoreFunction(dir);
  let counter = 0;
  await Promise.all(
    files.map(async (file2) => {
      if (assetsIgnoreFunction(file2)) {
        return;
      }
      const filepath = import_node_path13.default.join(dir, file2);
      const relativeFilepath = import_node_path13.default.relative(dir, filepath);
      const filestat = await import_promises7.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 "${dir}" 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 "${dir}".
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, v2] of a.pathHash.entries()) {
    if (v2 < b.pathHash[i]) {
      return -1;
    }
    if (v2 > 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 (path62) => {
  const encoder3 = new TextEncoder();
  const data2 = encoder3.encode(path62);
  const hashBuffer = await import_node_crypto4.default.subtle.digest(
    "SHA-256",
    data2.buffer
  );
  return new Uint8Array(hashBuffer, 0, PATH_HASH_SIZE);
};

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

// ../../node_modules/.pnpm/@clack+core@0.3.2/node_modules/@clack/core/dist/index.mjs
var import_sisteransi = __toESM(require_src(), 1);
var m = {};
var G = { get exports() {
  return m;
}, set exports(t) {
  m = t;
} };
(function(t) {
  var u = {};
  t.exports = u, u.eastAsianWidth = function(e) {
    var s = e.charCodeAt(0), C = e.length == 2 ? e.charCodeAt(1) : 0, D = s;
    return 55296 <= s && s <= 56319 && 56320 <= C && C <= 57343 && (s &= 1023, C &= 1023, D = s << 10 | C, D += 65536), D == 12288 || 65281 <= D && D <= 65376 || 65504 <= D && D <= 65510 ? "F" : D == 8361 || 65377 <= D && D <= 65470 || 65474 <= D && D <= 65479 || 65482 <= D && D <= 65487 || 65490 <= D && D <= 65495 || 65498 <= D && D <= 65500 || 65512 <= D && D <= 65518 ? "H" : 4352 <= D && D <= 4447 || 4515 <= D && D <= 4519 || 4602 <= D && D <= 4607 || 9001 <= D && D <= 9002 || 11904 <= D && D <= 11929 || 11931 <= D && D <= 12019 || 12032 <= D && D <= 12245 || 12272 <= D && D <= 12283 || 12289 <= D && D <= 12350 || 12353 <= D && D <= 12438 || 12441 <= D && D <= 12543 || 12549 <= D && D <= 12589 || 12593 <= D && D <= 12686 || 12688 <= D && D <= 12730 || 12736 <= D && D <= 12771 || 12784 <= D && D <= 12830 || 12832 <= D && D <= 12871 || 12880 <= D && D <= 13054 || 13056 <= D && D <= 19903 || 19968 <= D && D <= 42124 || 42128 <= D && D <= 42182 || 43360 <= D && D <= 43388 || 44032 <= D && D <= 55203 || 55216 <= D && D <= 55238 || 55243 <= D && D <= 55291 || 63744 <= D && D <= 64255 || 65040 <= D && D <= 65049 || 65072 <= D && D <= 65106 || 65108 <= D && D <= 65126 || 65128 <= D && D <= 65131 || 110592 <= D && D <= 110593 || 127488 <= D && D <= 127490 || 127504 <= D && D <= 127546 || 127552 <= D && D <= 127560 || 127568 <= D && D <= 127569 || 131072 <= D && D <= 194367 || 177984 <= D && D <= 196605 || 196608 <= D && D <= 262141 ? "W" : 32 <= D && D <= 126 || 162 <= D && D <= 163 || 165 <= D && D <= 166 || D == 172 || D == 175 || 10214 <= D && D <= 10221 || 10629 <= D && D <= 10630 ? "Na" : D == 161 || D == 164 || 167 <= D && D <= 168 || D == 170 || 173 <= D && D <= 174 || 176 <= D && D <= 180 || 182 <= D && D <= 186 || 188 <= D && D <= 191 || D == 198 || D == 208 || 215 <= D && D <= 216 || 222 <= D && D <= 225 || D == 230 || 232 <= D && D <= 234 || 236 <= D && D <= 237 || D == 240 || 242 <= D && D <= 243 || 247 <= D && D <= 250 || D == 252 || D == 254 || D == 257 || D == 273 || D == 275 || D == 283 || 294 <= D && D <= 295 || D == 299 || 305 <= D && D <= 307 || D == 312 || 319 <= D && D <= 322 || D == 324 || 328 <= D && D <= 331 || D == 333 || 338 <= D && D <= 339 || 358 <= D && D <= 359 || D == 363 || D == 462 || D == 464 || D == 466 || D == 468 || D == 470 || D == 472 || D == 474 || D == 476 || D == 593 || D == 609 || D == 708 || D == 711 || 713 <= D && D <= 715 || D == 717 || D == 720 || 728 <= D && D <= 731 || D == 733 || D == 735 || 768 <= D && D <= 879 || 913 <= D && D <= 929 || 931 <= D && D <= 937 || 945 <= D && D <= 961 || 963 <= D && D <= 969 || D == 1025 || 1040 <= D && D <= 1103 || D == 1105 || D == 8208 || 8211 <= D && D <= 8214 || 8216 <= D && D <= 8217 || 8220 <= D && D <= 8221 || 8224 <= D && D <= 8226 || 8228 <= D && D <= 8231 || D == 8240 || 8242 <= D && D <= 8243 || D == 8245 || D == 8251 || D == 8254 || D == 8308 || D == 8319 || 8321 <= D && D <= 8324 || D == 8364 || D == 8451 || D == 8453 || D == 8457 || D == 8467 || D == 8470 || 8481 <= D && D <= 8482 || D == 8486 || D == 8491 || 8531 <= D && D <= 8532 || 8539 <= D && D <= 8542 || 8544 <= D && D <= 8555 || 8560 <= D && D <= 8569 || D == 8585 || 8592 <= D && D <= 8601 || 8632 <= D && D <= 8633 || D == 8658 || D == 8660 || D == 8679 || D == 8704 || 8706 <= D && D <= 8707 || 8711 <= D && D <= 8712 || D == 8715 || D == 8719 || D == 8721 || D == 8725 || D == 8730 || 8733 <= D && D <= 8736 || D == 8739 || D == 8741 || 8743 <= D && D <= 8748 || D == 8750 || 8756 <= D && D <= 8759 || 8764 <= D && D <= 8765 || D == 8776 || D == 8780 || D == 8786 || 8800 <= D && D <= 8801 || 8804 <= D && D <= 8807 || 8810 <= D && D <= 8811 || 8814 <= D && D <= 8815 || 8834 <= D && D <= 8835 || 8838 <= D && D <= 8839 || D == 8853 || D == 8857 || D == 8869 || D == 8895 || D == 8978 || 9312 <= D && D <= 9449 || 9451 <= D && D <= 9547 || 9552 <= D && D <= 9587 || 9600 <= D && D <= 9615 || 9618 <= D && D <= 9621 || 9632 <= D && D <= 9633 || 9635 <= D && D <= 9641 || 9650 <= D && D <= 9651 || 9654 <= D && D <= 9655 || 9660 <= D && D <= 9661 || 9664 <= D && D <= 9665 || 9670 <= D && D <= 9672 || D == 9675 || 9678 <= D && D <= 9681 || 9698 <= D && D <= 9701 || D == 9711 || 9733 <= D && D <= 9734 || D == 9737 || 9742 <= D && D <= 9743 || 9748 <= D && D <= 9749 || D == 9756 || D == 9758 || D == 9792 || D == 9794 || 9824 <= D && D <= 9825 || 9827 <= D && D <= 9829 || 9831 <= D && D <= 9834 || 9836 <= D && D <= 9837 || D == 9839 || 9886 <= D && D <= 9887 || 9918 <= D && D <= 9919 || 9924 <= D && D <= 9933 || 9935 <= D && D <= 9953 || D == 9955 || 9960 <= D && D <= 9983 || D == 10045 || D == 10071 || 10102 <= D && D <= 10111 || 11093 <= D && D <= 11097 || 12872 <= D && D <= 12879 || 57344 <= D && D <= 63743 || 65024 <= D && D <= 65039 || D == 65533 || 127232 <= D && D <= 127242 || 127248 <= D && D <= 127277 || 127280 <= D && D <= 127337 || 127344 <= D && D <= 127386 || 917760 <= D && D <= 917999 || 983040 <= D && D <= 1048573 || 1048576 <= D && D <= 1114109 ? "A" : "N";
  }, u.characterLength = function(e) {
    var s = this.eastAsianWidth(e);
    return s == "F" || s == "W" || s == "A" ? 2 : 1;
  };
  function F(e) {
    return e.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g) || [];
  }
  u.length = function(e) {
    for (var s = F(e), C = 0, D = 0; D < s.length; D++) C = C + this.characterLength(s[D]);
    return C;
  }, u.slice = function(e, s, C) {
    textLen = u.length(e), s = s || 0, C = C || 1, s < 0 && (s = textLen + s), C < 0 && (C = textLen + C);
    for (var D = "", i = 0, o = F(e), E = 0; E < o.length; E++) {
      var a = o[E], n = u.length(a);
      if (i >= s - (n == 2 ? 1 : 0)) if (i + n <= C) D += a;
      else break;
      i += n;
    }
    return D;
  };
})(G);
var v = 10;
var L = (t = 0) => (u) => `\x1B[${u + t}m`;
var M = (t = 0) => (u) => `\x1B[${38 + t};5;${u}m`;
var T = (t = 0) => (u, F, e) => `\x1B[${38 + t};2;${u};${F};${e}m`;
var r = { modifier: { reset: [0, 0], 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], blackBright: [90, 39], gray: [90, 39], grey: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgGray: [100, 49], bgGrey: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } };
Object.keys(r.modifier);
var Z = Object.keys(r.color);
var H = Object.keys(r.bgColor);
[...Z, ...H];
function U() {
  const t = /* @__PURE__ */ new Map();
  for (const [u, F] of Object.entries(r)) {
    for (const [e, s] of Object.entries(F)) r[e] = { open: `\x1B[${s[0]}m`, close: `\x1B[${s[1]}m` }, F[e] = r[e], t.set(s[0], s[1]);
    Object.defineProperty(r, u, { value: F, enumerable: false });
  }
  return Object.defineProperty(r, "codes", { value: t, enumerable: false }), r.color.close = "\x1B[39m", r.bgColor.close = "\x1B[49m", r.color.ansi = L(), r.color.ansi256 = M(), r.color.ansi16m = T(), r.bgColor.ansi = L(v), r.bgColor.ansi256 = M(v), r.bgColor.ansi16m = T(v), Object.defineProperties(r, { rgbToAnsi256: { value: (u, F, e) => u === F && F === e ? u < 8 ? 16 : u > 248 ? 231 : Math.round((u - 8) / 247 * 24) + 232 : 16 + 36 * Math.round(u / 255 * 5) + 6 * Math.round(F / 255 * 5) + Math.round(e / 255 * 5), enumerable: false }, hexToRgb: { value: (u) => {
    const F = /[a-f\d]{6}|[a-f\d]{3}/i.exec(u.toString(16));
    if (!F) return [0, 0, 0];
    let [e] = F;
    e.length === 3 && (e = [...e].map((C) => C + C).join(""));
    const s = Number.parseInt(e, 16);
    return [s >> 16 & 255, s >> 8 & 255, s & 255];
  }, enumerable: false }, hexToAnsi256: { value: (u) => r.rgbToAnsi256(...r.hexToRgb(u)), enumerable: false }, ansi256ToAnsi: { value: (u) => {
    if (u < 8) return 30 + u;
    if (u < 16) return 90 + (u - 8);
    let F, e, s;
    if (u >= 232) F = ((u - 232) * 10 + 8) / 255, e = F, s = F;
    else {
      u -= 16;
      const i = u % 36;
      F = Math.floor(u / 36) / 5, e = Math.floor(i / 6) / 5, s = i % 6 / 5;
    }
    const C = Math.max(F, e, s) * 2;
    if (C === 0) return 30;
    let D = 30 + (Math.round(s) << 2 | Math.round(e) << 1 | Math.round(F));
    return C === 2 && (D += 60), D;
  }, enumerable: false }, rgbToAnsi: { value: (u, F, e) => r.ansi256ToAnsi(r.rgbToAnsi256(u, F, e)), enumerable: false }, hexToAnsi: { value: (u) => r.ansi256ToAnsi(r.hexToAnsi256(u)), enumerable: false } }), r;
}
var q = U();
var Q = "]";
var w = `${Q}8;;`;

// ../../node_modules/.pnpm/log-update@5.0.1/node_modules/log-update/index.js
var import_node_process4 = __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 = (x2, y) => {
  if (typeof x2 !== "number") {
    throw new TypeError("The `x` argument is required");
  }
  if (typeof y !== "number") {
    return ESC + (x2 + 1) + "G";
  }
  return ESC + (y + 1) + ";" + (x2 + 1) + "H";
};
ansiEscapes.cursorMove = (x2, y) => {
  if (typeof x2 !== "number") {
    throw new TypeError("The `x` argument is required");
  }
  let returnValue = "";
  if (x2 < 0) {
    returnValue += ESC + -x2 + "D";
  } else if (x2 > 0) {
    returnValue += ESC + x2 + "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, url38) => {
  return [
    OSC,
    "8",
    SEP,
    SEP,
    url38,
    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_process3 = __toESM(require("node:process"), 1);

// ../../node_modules/.pnpm/restore-cursor@4.0.0/node_modules/restore-cursor/index.js
var import_node_process2 = __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_process2.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_process3.default.stderr) => {
  if (!writableStream.isTTY) {
    return;
  }
  isHidden = false;
  writableStream.write("\x1B[?25h");
};
cliCursor.hide = (writableStream = import_node_process3.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.0.1/node_modules/ansi-regex/index.js
function ansiRegex({ 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 regex = ansiRegex();
function stripAnsi2(string) {
  if (typeof string !== "string") {
    throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
  }
  return string.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(string, options = {}) {
  if (typeof string !== "string" || string.length === 0) {
    return 0;
  }
  options = {
    ambiguousIsNarrow: true,
    ...options
  };
  string = stripAnsi2(string);
  if (string.length === 0) {
    return 0;
  }
  string = string.replace((0, import_emoji_regex.default)(), "  ");
  const ambiguousCharacterWidth = options.ambiguousIsNarrow ? 1 : 2;
  let width = 0;
  for (const character of string) {
    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 = (offset2 = 0) => (code) => `\x1B[${code + offset2}m`;
var wrapAnsi2562 = (offset2 = 0) => (code) => `\x1B[${38 + offset2};5;${code}m`;
var wrapAnsi16m2 = (offset2 = 0) => (red3, green3, blue3) => `\x1B[${38 + offset2};2;${red3};${green3};${blue3}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: (red3, green3, blue3) => {
        if (red3 === green3 && green3 === blue3) {
          if (red3 < 8) {
            return 16;
          }
          if (red3 > 248) {
            return 231;
          }
          return Math.round((red3 - 8) / 247 * 24) + 232;
        }
        return 16 + 36 * Math.round(red3 / 255 * 5) + 6 * Math.round(green3 / 255 * 5) + Math.round(blue3 / 255 * 5);
      },
      enumerable: false
    },
    hexToRgb: {
      value: (hex) => {
        const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches) {
          return [0, 0, 0];
        }
        let [colorString] = matches;
        if (colorString.length === 3) {
          colorString = [...colorString].map((character) => character + character).join("");
        }
        const integer = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer >> 16 & 255,
          integer >> 8 & 255,
          integer & 255
          /* eslint-enable no-bitwise */
        ];
      },
      enumerable: false
    },
    hexToAnsi256: {
      value: (hex) => styles3.rgbToAnsi256(...styles3.hexToRgb(hex)),
      enumerable: false
    },
    ansi256ToAnsi: {
      value: (code) => {
        if (code < 8) {
          return 30 + code;
        }
        if (code < 16) {
          return 90 + (code - 8);
        }
        let red3;
        let green3;
        let blue3;
        if (code >= 232) {
          red3 = ((code - 232) * 10 + 8) / 255;
          green3 = red3;
          blue3 = red3;
        } else {
          code -= 16;
          const remainder = code % 36;
          red3 = Math.floor(code / 36) / 5;
          green3 = Math.floor(remainder / 6) / 5;
          blue3 = remainder % 6 / 5;
        }
        const value = Math.max(red3, green3, blue3) * 2;
        if (value === 0) {
          return 30;
        }
        let result = 30 + (Math.round(blue3) << 2 | Math.round(green3) << 1 | Math.round(red3));
        if (value === 2) {
          result += 60;
        }
        return result;
      },
      enumerable: false
    },
    rgbToAnsi: {
      value: (red3, green3, blue3) => styles3.ansi256ToAnsi(styles3.rgbToAnsi256(red3, green3, blue3)),
      enumerable: false
    },
    hexToAnsi: {
      value: (hex) => styles3.ansi256ToAnsi(styles3.hexToAnsi256(hex)),
      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_BELL = "\x07";
var ANSI_CSI = "[";
var ANSI_OSC = "]";
var ANSI_SGR_TERMINATOR = "m";
var ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
var wrapAnsiCode = (code) => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
var wrapAnsiHyperlink = (uri) => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`;
var wordLengths = (string) => string.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_LINK);
    }
    if (isInsideEscape) {
      if (isInsideLinkEscape) {
        if (character === ANSI_ESCAPE_BELL) {
          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 = (string) => {
  const words = string.split(" ");
  let last = words.length;
  while (last > 0) {
    if (stringWidth(words[last - 1]) > 0) {
      break;
    }
    last--;
  }
  if (last === words.length) {
    return string;
  }
  return words.slice(0, last).join(" ") + words.slice(last).join("");
};
var exec = (string, columns, options = {}) => {
  if (options.trim !== false && string.trim() === "") {
    return "";
  }
  let returnValue = "";
  let escapeCode;
  let escapeUrl;
  const lengths = wordLengths(string);
  let rows = [""];
  for (const [index, word] of string.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_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).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 wrapAnsi(string, columns, options) {
  return String(string).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 wrapAnsi2 = (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(wrapAnsi2(isEscapes ? item : ansiCodeOrigin));
      } else {
        ansiCodes.splice(indexEscape, 1);
      }
    } else if (isEscapes) {
      output.push(wrapAnsi2(0));
      break;
    } else {
      output.push(wrapAnsi2(ansiCodeOrigin));
    }
  }
  if (isEscapes) {
    output = output.filter((element, index) => output.indexOf(element) === index);
    if (endAnsiCode !== void 0) {
      const fistEscapeCode = wrapAnsi2(ansi_styles_default2.codes.get(Number.parseInt(endAnsiCode, 10)));
      output = output.reduce((current2, next) => next === fistEscapeCode ? [next, ...current2] : [...current2, next], []);
    }
  }
  return output.join("");
};
function sliceAnsi(string, begin, end) {
  const characters = [...string];
  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(string.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/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,
    stripAnsi2(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 = wrapAnsi(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_process4.default.stdout);
var logUpdateStderr = createLogUpdate(import_node_process4.default.stderr);

// ../cli/interactive.ts
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 (isInteractive()) {
        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 (isInteractive()) {
        logUpdate2.clear();
        if (msg) {
          logUpdate2(`${leftT} ${startMsg}
${grayBar} ${msg}`);
          logUpdate2.done();
          newline();
        }
        clearLoop();
      } else {
        if (msg !== void 0) {
          logRaw(`${grayBar} ${msg}`);
        }
        newline();
      }
    }
  };
};
function isInteractive() {
  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_process2 = __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_path15 = __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_path14 = __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_fs10 = require("node:fs");
var http = __toESM(require("node:http"), 1);
var https = __toESM(require("node:https"), 1);
var import_node_url5 = require("node:url");
var import_proxy_agent = __toESM(require_dist11(), 1);
function httpRequest(url38, method, response, keepAlive = true) {
  const options = {
    protocol: url38.protocol,
    hostname: url38.hostname,
    port: url38.port,
    path: url38.pathname + url38.search,
    method,
    headers: keepAlive ? { Connection: "keep-alive" } : void 0,
    auth: (0, import_node_url5.urlToHttpOptions)(url38).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_url5.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(url38, destinationPath, progressCallback) {
  return new Promise((resolve6, reject) => {
    let downloadedBytes = 0;
    let totalBytes = 0;
    function onData(chunk) {
      downloadedBytes += chunk.length;
      progressCallback(downloadedBytes, totalBytes);
    }
    const request4 = httpRequest(url38, "GET", (response) => {
      if (response.statusCode !== 200) {
        const error = new Error(`Download failed: server returned code ${response.statusCode}. URL: ${url38}`);
        response.resume();
        reject(error);
        return;
      }
      const file2 = (0, import_node_fs10.createWriteStream)(destinationPath);
      file2.on("finish", () => {
        return resolve6();
      });
      file2.on("error", (error) => {
        return reject(error);
      });
      response.pipe(file2);
      totalBytes = parseInt(response.headers["content-length"], 10);
      if (progressCallback) {
        response.on("data", onData);
      }
    });
    request4.on("error", (error) => {
      return reject(error);
    });
  });
}
async function getJSON(url38) {
  const text = await getText2(url38);
  try {
    return JSON.parse(text);
  } catch {
    throw new Error("Could not parse JSON from " + url38.toString());
  }
}
function getText2(url38) {
  return new Promise((resolve6, reject) => {
    const request4 = httpRequest(url38, "GET", (response) => {
      let data2 = "";
      if (response.statusCode && response.statusCode >= 400) {
        return reject(new Error(`Got status code ${response.statusCode}`));
      }
      response.on("data", (chunk) => {
        data2 += chunk;
      });
      response.on("end", () => {
        try {
          return resolve6(String(data2));
        } 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(platform) {
  switch (platform) {
    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(platform, buildId, baseUrl = "https://storage.googleapis.com/chrome-for-testing-public") {
  return `${baseUrl}/${resolveDownloadPath(platform, buildId).join("/")}`;
}
function resolveDownloadPath(platform, buildId) {
  return [buildId, folder(platform), `chrome-${folder(platform)}.zip`];
}
function relativeExecutablePath(platform, _buildId) {
  switch (platform) {
    case BrowserPlatform.MAC:
    case BrowserPlatform.MAC_ARM:
      return import_node_path14.default.join("chrome-" + folder(platform), "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing");
    case BrowserPlatform.LINUX_ARM:
    case BrowserPlatform.LINUX:
      return import_node_path14.default.join("chrome-linux64", "chrome");
    case BrowserPlatform.WIN32:
    case BrowserPlatform.WIN64:
      return import_node_path14.default.join("chrome-" + folder(platform), "chrome.exe");
  }
}
async function getLastKnownGoodReleaseForChannel(channel) {
  const data2 = await getJSON(new URL("https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions.json"));
  for (const channel2 of Object.keys(data2.channels)) {
    data2.channels[channel2.toLowerCase()] = data2.channels[channel2];
    delete data2.channels[channel2];
  }
  return data2.channels[channel];
}
async function getLastKnownGoodReleaseForMilestone(milestone) {
  const data2 = await getJSON(new URL("https://googlechromelabs.github.io/chrome-for-testing/latest-versions-per-milestone.json"));
  return data2.milestones[milestone];
}
async function getLastKnownGoodReleaseForBuild(buildPrefix) {
  const data2 = await getJSON(new URL("https://googlechromelabs.github.io/chrome-for-testing/latest-patch-versions-per-build.json"));
  return data2.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(platform) {
  switch (platform) {
    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(platform, buildId, baseUrl = "https://storage.googleapis.com/chrome-for-testing-public") {
  return `${baseUrl}/${resolveDownloadPath2(platform, buildId).join("/")}`;
}
function resolveDownloadPath2(platform, buildId) {
  return [
    buildId,
    folder2(platform),
    `chrome-headless-shell-${folder2(platform)}.zip`
  ];
}
function relativeExecutablePath2(platform, _buildId) {
  switch (platform) {
    case BrowserPlatform.MAC:
    case BrowserPlatform.MAC_ARM:
      return import_node_path15.default.join("chrome-headless-shell-" + folder2(platform), "chrome-headless-shell");
    case BrowserPlatform.LINUX_ARM:
    case BrowserPlatform.LINUX:
      return import_node_path15.default.join("chrome-headless-shell-linux64", "chrome-headless-shell");
    case BrowserPlatform.WIN32:
    case BrowserPlatform.WIN64:
      return import_node_path15.default.join("chrome-headless-shell-" + folder2(platform), "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_path16 = __toESM(require("node:path"), 1);
function folder3(platform) {
  switch (platform) {
    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(platform, buildId, baseUrl = "https://storage.googleapis.com/chrome-for-testing-public") {
  return `${baseUrl}/${resolveDownloadPath3(platform, buildId).join("/")}`;
}
function resolveDownloadPath3(platform, buildId) {
  return [buildId, folder3(platform), `chromedriver-${folder3(platform)}.zip`];
}
function relativeExecutablePath3(platform, _buildId) {
  switch (platform) {
    case BrowserPlatform.MAC:
    case BrowserPlatform.MAC_ARM:
      return import_node_path16.default.join("chromedriver-" + folder3(platform), "chromedriver");
    case BrowserPlatform.LINUX_ARM:
    case BrowserPlatform.LINUX:
      return import_node_path16.default.join("chromedriver-linux64", "chromedriver");
    case BrowserPlatform.WIN32:
    case BrowserPlatform.WIN64:
      return import_node_path16.default.join("chromedriver-" + folder3(platform), "chromedriver.exe");
  }
}

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/browser-data/chromium.js
var import_node_path17 = __toESM(require("node:path"), 1);
function archive(platform, buildId) {
  switch (platform) {
    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(platform) {
  switch (platform) {
    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(platform, buildId, baseUrl = "https://storage.googleapis.com/chromium-browser-snapshots") {
  return `${baseUrl}/${resolveDownloadPath4(platform, buildId).join("/")}`;
}
function resolveDownloadPath4(platform, buildId) {
  return [folder4(platform), buildId, `${archive(platform, buildId)}.zip`];
}
function relativeExecutablePath4(platform, _buildId) {
  switch (platform) {
    case BrowserPlatform.MAC:
    case BrowserPlatform.MAC_ARM:
      return import_node_path17.default.join("chrome-mac", "Chromium.app", "Contents", "MacOS", "Chromium");
    case BrowserPlatform.LINUX_ARM:
    case BrowserPlatform.LINUX:
      return import_node_path17.default.join("chrome-linux", "chrome");
    case BrowserPlatform.WIN32:
    case BrowserPlatform.WIN64:
      return import_node_path17.default.join("chrome-win", "chrome.exe");
  }
}
async function resolveBuildId2(platform) {
  return await getText2(new URL(`https://storage.googleapis.com/chromium-browser-snapshots/${folder4(platform)}/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_path18 = __toESM(require("node:path"), 1);
function getFormat(buildId) {
  const majorVersion = Number(buildId.split(".").shift());
  return majorVersion >= 135 ? "xz" : "bz2";
}
function archiveNightly(platform, buildId) {
  switch (platform) {
    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.${platform}.zip`;
  }
}
function archive2(platform, buildId) {
  switch (platform) {
    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(platform) {
  switch (platform) {
    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 platform;
  }
}
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(platform, 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(platform, buildId).join("/")}`;
}
function resolveDownloadPath5(platform, buildId) {
  const [channel, resolvedBuildId] = parseBuildId(buildId);
  switch (channel) {
    case FirefoxChannel.NIGHTLY:
      return [archiveNightly(platform, resolvedBuildId)];
    case FirefoxChannel.DEVEDITION:
    case FirefoxChannel.BETA:
    case FirefoxChannel.STABLE:
    case FirefoxChannel.ESR:
      return [
        resolvedBuildId,
        platformName(platform),
        "en-US",
        archive2(platform, resolvedBuildId)
      ];
  }
}
function relativeExecutablePath5(platform, buildId) {
  const [channel] = parseBuildId(buildId);
  switch (channel) {
    case FirefoxChannel.NIGHTLY:
      switch (platform) {
        case BrowserPlatform.MAC_ARM:
        case BrowserPlatform.MAC:
          return import_node_path18.default.join("Firefox Nightly.app", "Contents", "MacOS", "firefox");
        case BrowserPlatform.LINUX_ARM:
        case BrowserPlatform.LINUX:
          return import_node_path18.default.join("firefox", "firefox");
        case BrowserPlatform.WIN32:
        case BrowserPlatform.WIN64:
          return import_node_path18.default.join("firefox", "firefox.exe");
      }
    case FirefoxChannel.BETA:
    case FirefoxChannel.DEVEDITION:
    case FirefoxChannel.ESR:
    case FirefoxChannel.STABLE:
      switch (platform) {
        case BrowserPlatform.MAC_ARM:
        case BrowserPlatform.MAC:
          return import_node_path18.default.join("Firefox.app", "Contents", "MacOS", "firefox");
        case BrowserPlatform.LINUX_ARM:
        case BrowserPlatform.LINUX:
          return import_node_path18.default.join("firefox", "firefox");
        case BrowserPlatform.WIN32:
        case BrowserPlatform.WIN64:
          return import_node_path18.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 version3 = versions[channelToVersionKey[channel]];
  if (!version3) {
    throw new Error(`Channel ${channel} is not found.`);
  }
  return channel + "_" + version3;
}
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, platform, 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(platform);
        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, platform, tag) {
  const browserTag = tag;
  if (Object.values(BrowserTag).includes(browserTag)) {
    return await resolveBuildIdForBrowserTag(browser, platform, 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_fs11 = __toESM(require("node:fs"), 1);
var import_node_os7 = __toESM(require("node:os"), 1);
var import_node_path19 = __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_os6 = __toESM(require("node:os"), 1);
function detectBrowserPlatform() {
  const platform = import_node_os6.default.platform();
  const arch = import_node_os6.default.arch();
  switch (platform) {
    case "darwin":
      return arch === "arm64" ? BrowserPlatform.MAC_ARM : BrowserPlatform.MAC;
    case "linux":
      return arch === "arm64" ? BrowserPlatform.LINUX_ARM : BrowserPlatform.LINUX;
    case "win32":
      return arch === "x64" || // Windows 11 for ARM supports x64 emulation
      arch === "arm64" && isWindows11(import_node_os6.default.release()) ? BrowserPlatform.WIN64 : BrowserPlatform.WIN32;
    default:
      return void 0;
  }
}
function isWindows11(version3) {
  const parts = version3.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, platform) {
    this.#cache = cache;
    this.browser = browser;
    this.buildId = buildId;
    this.platform = platform;
    this.executablePath = cache.computeExecutablePath({
      browser,
      buildId,
      platform
    });
  }
  /**
   * 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_path19.default.join(this.#rootDir, browser);
  }
  metadataFile(browser) {
    return import_node_path19.default.join(this.browserRoot(browser), ".metadata");
  }
  readMetadata(browser) {
    const metatadaPath = this.metadataFile(browser);
    if (!import_node_fs11.default.existsSync(metatadaPath)) {
      return { aliases: {} };
    }
    const data2 = JSON.parse(import_node_fs11.default.readFileSync(metatadaPath, "utf8"));
    if (typeof data2 !== "object") {
      throw new Error(".metadata is not an object");
    }
    return data2;
  }
  writeMetadata(browser, metadata) {
    const metatadaPath = this.metadataFile(browser);
    import_node_fs11.default.mkdirSync(import_node_path19.default.dirname(metatadaPath), { recursive: true });
    import_node_fs11.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, platform, buildId) {
    return import_node_path19.default.join(this.browserRoot(browser), `${platform}-${buildId}`);
  }
  clear() {
    import_node_fs11.default.rmSync(this.#rootDir, {
      force: true,
      recursive: true,
      maxRetries: 10,
      retryDelay: 500
    });
  }
  uninstall(browser, platform, 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_fs11.default.rmSync(this.installationDir(browser, platform, buildId), {
      force: true,
      recursive: true,
      maxRetries: 10,
      retryDelay: 500
    });
  }
  getInstalledBrowsers() {
    if (!import_node_fs11.default.existsSync(this.#rootDir)) {
      return [];
    }
    const types4 = import_node_fs11.default.readdirSync(this.#rootDir);
    const browsers = types4.filter((t) => {
      return Object.values(Browser).includes(t);
    });
    return browsers.flatMap((browser) => {
      const files = import_node_fs11.default.readdirSync(this.browserRoot(browser));
      return files.map((file2) => {
        const result = parseFolderPath(import_node_path19.default.join(this.browserRoot(browser), file2));
        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_os7.default.platform()} (${import_node_os7.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_path19.default.join(installationDir, executablePathByBrowser[options.browser](options.platform, options.buildId));
  }
};
function parseFolderPath(folderPath) {
  const name = import_node_path19.default.basename(folderPath);
  const splits = name.split("-");
  if (splits.length !== 2) {
    return;
  }
  const [platform, buildId] = splits;
  if (!buildId || !platform) {
    return;
  }
  return { platform, 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_process2.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((resolve6, 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;
        }
        resolve6();
      });
    });
  }
  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_process2.default.execSync(`taskkill /pid ${this.#browserProcess.pid} /T /F`);
          } catch (error) {
            debugLaunch(`Killing ${this.#browserProcess.pid} using taskkill failed`, error);
            this.#browserProcess.kill();
          }
        } else {
          const processGroupId = -this.#browserProcess.pid;
          try {
            process.kill(processGroupId, "SIGKILL");
          } catch (error) {
            debugLaunch(`Killing ${this.#browserProcess.pid} using process.kill failed`, error);
            this.#browserProcess.kill("SIGKILL");
          }
        }
      } catch (error) {
        throw new Error(`${PROCESS_ERROR_EXPLANATION}
Error cause: ${isErrorLike(error) ? error.stack : error}`);
      }
    }
    this.#clearListeners();
  }
  waitForLineOutput(regex2, 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((resolve6, 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(error) {
        cleanup();
        reject(new Error([
          `Failed to launch the browser process!${error ? " " + error.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(regex2);
        if (!match) {
          return;
        }
        cleanup();
        resolve6(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 (error) {
    if (isErrnoException(error)) {
      if (error.code && error.code === "ESRCH") {
        return false;
      }
    }
    throw error;
  }
}
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_assert17 = __toESM(require("node:assert"), 1);
var import_node_child_process4 = require("node:child_process");
var import_node_fs13 = require("node:fs");
var import_promises9 = require("node:fs/promises");
var import_node_os8 = __toESM(require("node:os"), 1);
var import_node_path20 = __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_process3 = require("node:child_process");
var import_node_fs12 = require("node:fs");
var import_promises8 = require("node:fs/promises");
var path34 = __toESM(require("node:path"), 1);
var import_node_stream3 = 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 (!path34.isAbsolute(folderPath)) {
    folderPath = path34.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_promises8.mkdir)(folderPath);
    await installDMG(archivePath, folderPath);
  } else if (archivePath.endsWith(".exe")) {
    const result = (0, import_node_child_process3.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_stream3.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", (data2) => {
    return stream.push(data2);
  }).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 (error) => {
        if ("code" in error && error.code === "ENOENT") {
          error = new Error(`\`${utilityName}\` utility is required to unpack this archive`, {
            cause: error
          });
        }
        reject(error);
      };
    }
    const unpack2 = (0, import_node_child_process3.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_fs12.createReadStream)(tarPath).pipe(createTransformStream(unpack2)).pipe(tar);
  });
}
async function installDMG(dmgPath, folderPath) {
  const { stdout: stdout2 } = (0, import_node_child_process3.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_promises8.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 = path34.join(mountPath, appName);
    (0, import_node_child_process3.spawnSync)("cp", ["-R", mountedPath, folderPath]);
  } finally {
    (0, import_node_child_process3.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 duration = end[0] * 1e3 + end[1] / 1e6 - (start[0] * 1e3 + start[1] / 1e6);
  debugInstall(`Duration for ${label}: ${duration}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_os8.default.platform()} (${import_node_os8.default.arch()})`);
  }
  const url38 = getDownloadUrl(options.browser, options.platform, options.buildId, options.baseUrl);
  try {
    return await installUrl(url38, options);
  } catch (err) {
    if (options.baseUrl && !options.forceFallbackForTesting) {
      throw err;
    }
    debugInstall(`Error downloading from ${url38}.`);
    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 version3 = await getJSON(new URL(`https://googlechromelabs.github.io/chrome-for-testing/${options.buildId}.json`));
        let platform = "";
        switch (options.platform) {
          case BrowserPlatform.LINUX:
            platform = "linux64";
            break;
          case BrowserPlatform.MAC_ARM:
            platform = "mac-arm64";
            break;
          case BrowserPlatform.MAC:
            platform = "mac-x64";
            break;
          case BrowserPlatform.WIN32:
            platform = "win32";
            break;
          case BrowserPlatform.WIN64:
            platform = "win64";
            break;
        }
        const backupUrl = version3.downloads[options.browser]?.find((link) => {
          return link["platform"] === platform;
        })?.url;
        if (backupUrl) {
          if (backupUrl === url38.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_path20.default.join(import_node_path20.default.dirname(installedBrowser.executablePath), "deb.deps");
  if (!(0, import_node_fs13.existsSync)(depsPath)) {
    debugInstall(`deb.deps file was not found at ${depsPath}`);
    return;
  }
  const data2 = (0, import_node_fs13.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_process4.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: ${data2}`);
  result = (0, import_node_child_process4.spawnSync)("apt-get", [
    "satisfy",
    "-y",
    data2,
    "--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 ${data2}`);
}
async function installUrl(url38, options) {
  options.platform ??= detectBrowserPlatform();
  if (!options.platform) {
    throw new Error(`Cannot download a binary for the provided platform: ${import_node_os8.default.platform()} (${import_node_os8.default.arch()})`);
  }
  let downloadProgressCallback = options.downloadProgressCallback;
  if (downloadProgressCallback === "default") {
    downloadProgressCallback = await makeProgressCallback(options.browser, options.buildIdAlias ?? options.buildId);
  }
  const fileName = decodeURIComponent(url38.toString()).split("/").pop();
  (0, import_node_assert17.default)(fileName, `A malformed download URL was found: ${url38}.`);
  const cache = new Cache(options.cacheDir);
  const browserRoot = cache.browserRoot(options.browser);
  const archivePath = import_node_path20.default.join(browserRoot, `${options.buildId}-${fileName}`);
  if (!(0, import_node_fs13.existsSync)(browserRoot)) {
    await (0, import_promises9.mkdir)(browserRoot, { recursive: true });
  }
  if (!options.unpack) {
    if ((0, import_node_fs13.existsSync)(archivePath)) {
      return archivePath;
    }
    debugInstall(`Downloading binary from ${url38}`);
    debugTime("download");
    await downloadFile(url38, archivePath, downloadProgressCallback);
    debugTimeEnd("download");
    return archivePath;
  }
  const outputPath = cache.installationDir(options.browser, options.platform, options.buildId);
  try {
    if ((0, import_node_fs13.existsSync)(outputPath)) {
      const installedBrowser2 = new InstalledBrowser(cache, options.browser, options.buildId, options.platform);
      if (!(0, import_node_fs13.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 ${url38}`);
    try {
      debugTime("download");
      await downloadFile(url38, 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_fs13.existsSync)(archivePath)) {
      await (0, import_promises9.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_path20.default.dirname(installedBrowser.executablePath);
      const setupExePath = import_node_path20.default.join(browserDir, "setup.exe");
      if (!(0, import_node_fs13.existsSync)(setupExePath)) {
        return;
      }
      (0, import_node_child_process4.spawnSync)(import_node_path20.default.join(browserDir, "setup.exe"), [`--configure-browser-in-directory=` + browserDir], {
        shell: true
      });
    } finally {
      debugTimeEnd("permissions");
    }
  }
}
function getDownloadUrl(browser, platform, buildId, baseUrl) {
  return new URL(downloadUrls[browser](platform, 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_fs17 = __toESM(require("fs"));
var import_path17 = __toESM(require("path"));
var import_url17 = __toESM(require("url"));
var contents17;
function binding_worker_default() {
  if (contents17 !== void 0) return contents17;
  const filePath = import_path17.default.join(__dirname, "workers", "browser-rendering/binding.worker.js");
  contents17 = import_fs17.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url17.default.pathToFileURL(filePath);
  return contents17;
}

// src/shared/wrangler.ts
var import_node_fs14 = __toESM(require("node:fs"));
var import_node_os9 = __toESM(require("node:os"));
var import_node_path21 = __toESM(require("node:path"));

// ../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/esm-wrapper/mod.esm.js
var mod_esm_exports2 = {};
__export(mod_esm_exports2, {
  default: () => mod_esm_default2
});
var import_mod_cjs2 = __toESM(require_mod_cjs6(), 1);
__reExport(mod_esm_exports2, __toESM(require_mod_cjs6(), 1));
var mod_esm_default2 = import_mod_cjs2.default;

// src/shared/wrangler.ts
function isDirectory2(configPath) {
  return import_node_fs14.default.statSync(configPath, { throwIfNoEntry: false })?.isDirectory() ?? false;
}
function getGlobalWranglerConfigPath2() {
  const configDir = mod_esm_default2(".wrangler").config();
  const legacyConfigDir = import_node_path21.default.join(import_node_os9.default.homedir(), ".wrangler");
  if (isDirectory2(legacyConfigDir)) {
    return legacyConfigDir;
  } else {
    return configDir;
  }
}
function getGlobalWranglerCachePath() {
  return mod_esm_default2(".wrangler").cache();
}

// src/plugins/browser-rendering/index.ts
var BrowserRenderingSchema = external_exports.object({
  binding: external_exports.string(),
  remoteProxyConnectionString: external_exports.custom().optional(),
  headful: external_exports.boolean().optional()
});
var BrowserRenderingOptionsSchema = external_exports.object({
  browserRendering: BrowserRenderingSchema.optional()
});
var BROWSER_RENDERING_PLUGIN_NAME = "browser-rendering";
var BROWSER_RENDERING_PLUGIN = {
  options: BrowserRenderingOptionsSchema,
  async getBindings(options) {
    if (!options.browserRendering) {
      return [];
    }
    return [
      {
        name: options.browserRendering.binding,
        service: {
          name: getUserBindingServiceName(
            BROWSER_RENDERING_PLUGIN_NAME,
            options.browserRendering.binding,
            options.browserRendering.remoteProxyConnectionString
          )
        }
      }
    ];
  },
  getNodeBindings(options) {
    if (!options.browserRendering) {
      return {};
    }
    return {
      [options.browserRendering.binding]: new ProxyNodeBinding()
    };
  },
  async getServices({ options }) {
    if (!options.browserRendering) {
      return [];
    }
    return [
      {
        name: getUserBindingServiceName(
          BROWSER_RENDERING_PLUGIN_NAME,
          options.browserRendering.binding,
          options.browserRendering.remoteProxyConnectionString
        ),
        worker: options.browserRendering.remoteProxyConnectionString ? remoteProxyClientWorker(
          options.browserRendering.remoteProxyConnectionString,
          options.browserRendering.binding
        ) : {
          compatibilityDate: "2025-05-01",
          compatibilityFlags: ["nodejs_compat"],
          modules: [
            {
              name: "index.worker.js",
              esModule: binding_worker_default()
            }
          ],
          bindings: [
            WORKER_BINDING_SERVICE_LOOPBACK,
            {
              name: "BrowserSession",
              durableObjectNamespace: {
                className: "BrowserSession"
              }
            }
          ],
          durableObjectNamespaces: [
            {
              className: "BrowserSession"
            }
          ],
          durableObjectStorage: { inMemory: kVoid }
        }
      }
    ];
  }
};
async function launchBrowser({
  browserVersion,
  headful,
  log: log2,
  tmpPath
}) {
  const platform = detectBrowserPlatform();
  if (!platform) {
    throw new Error("The current platform is not supported.");
  }
  const browser = Browser.CHROME;
  const sessionId = crypto.randomUUID();
  const s = spinner();
  let startedDownloading = false;
  const { executablePath } = await install({
    browser,
    platform,
    cacheDir: getGlobalWranglerCachePath(),
    buildId: await resolveBuildId4(browser, platform, browserVersion),
    downloadProgressCallback: (downloadedBytes, totalBytes) => {
      if (!startedDownloading) {
        s.start(`Downloading browser...`);
        startedDownloading = true;
      }
      const progress = Math.round(downloadedBytes / totalBytes * 100);
      s.update(`Downloading browser... ${progress}%`);
    }
  });
  if (startedDownloading) {
    s.stop(`${brandColor("downloaded")} ${dim2(`browser`)}`);
    log2.debug(`${browser} ${browserVersion} available at ${executablePath}`);
  }
  const tempUserData = import_node_path22.default.join(
    tmpPath,
    "browser-rendering",
    `profile-${sessionId}`
  );
  await import_node_fs15.default.promises.mkdir(tempUserData, { recursive: true });
  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",
    `--user-data-dir=${tempUserData}`
  ];
  const browserProcess = launch({
    executablePath,
    args: process.env.CI ? [...args, "--no-sandbox"] : args,
    handleSIGTERM: false,
    dumpio: false,
    pipe: false,
    onExit: async () => {
      try {
        await removeDir(tempUserData);
      } catch (e) {
        log2.debug(`Unable to remove Chrome user data directory: ${e}`);
      }
    }
  });
  const wsEndpoint = await browserProcess.waitForLineOutput(
    CDP_WEBSOCKET_ENDPOINT_REGEX
  );
  const startTime = Date.now();
  return { sessionId, browserProcess, startTime, wsEndpoint };
}

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

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

// src/plugins/d1/index.ts
var D1OptionsSchema = external_exports.object({
  d1Databases: external_exports.union([
    external_exports.record(
      external_exports.union([
        external_exports.string(),
        external_exports.object({
          id: external_exports.string(),
          remoteProxyConnectionString: external_exports.custom().optional()
        })
      ])
    ),
    external_exports.string().array()
  ]).optional()
});
var D1SharedOptionsSchema = external_exports.object({
  d1Persist: PersistenceSchema
});
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_DATABASE_OBJECT_CLASS_NAME = "D1DatabaseObject";
var D1_DATABASE_OBJECT = {
  serviceName: D1_DATABASE_SERVICE_PREFIX,
  className: D1_DATABASE_OBJECT_CLASS_NAME
};
var D1_PLUGIN = {
  options: D1OptionsSchema,
  sharedOptions: D1SharedOptionsSchema,
  getBindings(options) {
    const databases = namespaceEntries(options.d1Databases);
    return databases.map(
      ([name, { id, remoteProxyConnectionString }]) => {
        (0, import_node_assert18.default)(
          !(name.startsWith("__D1_BETA__") && remoteProxyConnectionString),
          "Alpha D1 Databases cannot run remotely"
        );
        const serviceName = getUserBindingServiceName(
          D1_DATABASE_SERVICE_PREFIX,
          id,
          remoteProxyConnectionString
        );
        const binding = name.startsWith("__D1_BETA__") ? (
          // Used before Wrangler 3.3
          {
            service: {
              name: serviceName
            }
          }
        ) : (
          // Used after Wrangler 3.3
          {
            wrapped: {
              moduleName: "cloudflare-internal:d1-api",
              innerBindings: [
                {
                  name: "fetcher",
                  service: {
                    name: serviceName
                  }
                }
              ]
            }
          }
        );
        return { name, ...binding };
      }
    );
  },
  getNodeBindings(options) {
    const databases = namespaceKeys(options.d1Databases);
    return Object.fromEntries(
      databases.map((name) => [name, new ProxyNodeBinding()])
    );
  },
  async getServices({
    options,
    sharedOptions,
    tmpPath,
    defaultPersistRoot,
    log: log2,
    unsafeStickyBlobs
  }) {
    const persist = sharedOptions.d1Persist;
    const databases = namespaceEntries(options.d1Databases);
    const services = databases.map(
      ([name, { id, remoteProxyConnectionString }]) => ({
        name: getUserBindingServiceName(
          D1_DATABASE_SERVICE_PREFIX,
          id,
          remoteProxyConnectionString
        ),
        worker: remoteProxyConnectionString ? remoteProxyClientWorker(remoteProxyConnectionString, name) : objectEntryWorker(D1_DATABASE_OBJECT, id)
      })
    );
    if (databases.length > 0) {
      const uniqueKey = `miniflare-${D1_DATABASE_OBJECT_CLASS_NAME}`;
      const persistPath = getPersistPath(
        D1_PLUGIN_NAME,
        tmpPath,
        defaultPersistRoot,
        persist
      );
      await import_promises10.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(unsafeStickyBlobs)
          ]
        }
      };
      services.push(storageService, objectService);
      for (const database of databases) {
        await migrateDatabase(log2, uniqueKey, persistPath, database[1].id);
      }
    }
    return services;
  },
  getPersistPath({ d1Persist }, tmpPath) {
    return getPersistPath(D1_PLUGIN_NAME, tmpPath, void 0, d1Persist);
  }
};

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

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

// src/plugins/dispatch-namespace/index.ts
var DispatchNamespaceOptionsSchema = external_exports.object({
  dispatchNamespaces: external_exports.record(
    external_exports.object({
      namespace: external_exports.string(),
      remoteProxyConnectionString: external_exports.custom().optional()
    })
  ).optional()
});
var DISPATCH_NAMESPACE_PLUGIN_NAME = "dispatch-namespace";
function getProxyServiceName(name, remoteProxyConnectionString) {
  return getUserBindingServiceName(
    `${DISPATCH_NAMESPACE_PLUGIN_NAME}-proxy`,
    name,
    remoteProxyConnectionString
  );
}
var DISPATCH_NAMESPACE_PLUGIN = {
  options: DispatchNamespaceOptionsSchema,
  async getBindings(options) {
    if (!options.dispatchNamespaces) {
      return [];
    }
    const bindings = Object.entries(
      options.dispatchNamespaces
    ).map(([name, config]) => {
      return {
        name,
        wrapped: {
          moduleName: `${DISPATCH_NAMESPACE_PLUGIN_NAME}:local-dispatch-namespace`,
          innerBindings: [
            {
              name: "proxyClient",
              service: {
                name: getProxyServiceName(
                  name,
                  config.remoteProxyConnectionString
                )
              }
            }
          ]
        }
      };
    });
    return bindings;
  },
  getNodeBindings(options) {
    if (!options.dispatchNamespaces) {
      return {};
    }
    return Object.fromEntries(
      Object.keys(options.dispatchNamespaces).map((name) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    if (!options.dispatchNamespaces) {
      return [];
    }
    return Object.entries(options.dispatchNamespaces).map(([name, config]) => ({
      name: getProxyServiceName(name, config.remoteProxyConnectionString),
      worker: remoteProxyClientWorker(
        config.remoteProxyConnectionString,
        name,
        dispatch_namespace_proxy_worker_default
      )
    }));
  },
  getExtensions({ options }) {
    if (!options.some((o) => o.dispatchNamespaces)) {
      return [];
    }
    return [
      {
        modules: [
          {
            name: `${DISPATCH_NAMESPACE_PLUGIN_NAME}:local-dispatch-namespace`,
            esModule: dispatch_namespace_worker_default(),
            internal: true
          }
        ]
      }
    ];
  }
};

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/email/email.worker.ts
var import_fs21 = __toESM(require("fs"));
var import_path21 = __toESM(require("path"));
var import_url21 = __toESM(require("url"));
var contents21;
function email_worker_default() {
  if (contents21 !== void 0) return contents21;
  const filePath = import_path21.default.join(__dirname, "workers", "email/email.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/email/send_email.worker.ts
var import_fs22 = __toESM(require("fs"));
var import_path22 = __toESM(require("path"));
var import_url22 = __toESM(require("url"));
var contents22;
function send_email_worker_default() {
  if (contents22 !== void 0) return contents22;
  const filePath = import_path22.default.join(__dirname, "workers", "email/send_email.worker.js");
  contents22 = import_fs22.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url22.default.pathToFileURL(filePath);
  return contents22;
}

// src/plugins/email/index.ts
var EmailBindingOptionsSchema = external_exports.object({
  name: external_exports.string(),
  remoteProxyConnectionString: external_exports.custom().optional(),
  allowed_sender_addresses: external_exports.array(external_exports.string()).optional()
}).and(
  external_exports.union([
    external_exports.object({
      destination_address: external_exports.string().optional(),
      allowed_destination_addresses: external_exports.never().optional()
    }),
    external_exports.object({
      allowed_destination_addresses: external_exports.array(external_exports.string()).optional(),
      destination_address: external_exports.never().optional()
    })
  ])
);
var EmailOptionsSchema = external_exports.object({
  email: external_exports.object({
    send_email: external_exports.array(EmailBindingOptionsSchema).optional()
  }).optional()
});
var EMAIL_PLUGIN_NAME = "email";
var SERVICE_SEND_EMAIL_WORKER_PREFIX = `SEND-EMAIL-WORKER`;
function buildJsonBindings(bindings) {
  return Object.entries(bindings).map(([name, value]) => ({
    name,
    json: JSON.stringify(value)
  }));
}
var EMAIL_PLUGIN = {
  options: EmailOptionsSchema,
  getBindings(options) {
    if (!options.email?.send_email) {
      return [];
    }
    const sendEmailBindings = options.email.send_email;
    return sendEmailBindings.map(({ name, remoteProxyConnectionString }) => ({
      name,
      service: {
        entrypoint: remoteProxyConnectionString ? void 0 : "SendEmailBinding",
        name: getUserBindingServiceName(SERVICE_SEND_EMAIL_WORKER_PREFIX, name)
      }
    }));
  },
  getNodeBindings(_options) {
    return {};
  },
  async getServices(args) {
    const services = [];
    for (const { name, remoteProxyConnectionString, ...config } of args.options.email?.send_email ?? []) {
      services.push({
        name: getUserBindingServiceName(SERVICE_SEND_EMAIL_WORKER_PREFIX, name),
        worker: remoteProxyConnectionString ? remoteProxyClientWorker(remoteProxyConnectionString, name) : {
          compatibilityDate: "2025-03-17",
          modules: [
            {
              name: "send_email.mjs",
              esModule: send_email_worker_default()
            }
          ],
          bindings: [
            ...buildJsonBindings(config),
            WORKER_BINDING_SERVICE_LOOPBACK
          ]
        }
      });
    }
    return services;
  },
  getExtensions() {
    return [
      {
        modules: [
          {
            name: "cloudflare-internal:email",
            esModule: email_worker_default(),
            internal: true
          }
        ]
      }
    ];
  }
};

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

// src/plugins/flagship/index.ts
var FlagshipSchema = external_exports.object({
  app_id: external_exports.string(),
  remoteProxyConnectionString: external_exports.custom().optional()
});
var FlagshipOptionsSchema = external_exports.object({
  flagship: external_exports.record(FlagshipSchema).optional()
});
var FLAGSHIP_PLUGIN_NAME = "flagship";
var FLAGSHIP_PLUGIN = {
  options: FlagshipOptionsSchema,
  async getBindings(options) {
    if (!options.flagship) {
      return [];
    }
    return Object.entries(options.flagship).map(
      ([name, config]) => ({
        name,
        service: {
          name: getUserBindingServiceName(
            FLAGSHIP_PLUGIN_NAME,
            name,
            config.remoteProxyConnectionString
          ),
          entrypoint: "FlagshipBinding"
        }
      })
    );
  },
  getNodeBindings(options) {
    if (!options.flagship) {
      return {};
    }
    return Object.fromEntries(
      Object.keys(options.flagship).map((name) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    if (!options.flagship) {
      return [];
    }
    return Object.entries(options.flagship).map(
      ([name, { remoteProxyConnectionString }]) => {
        return {
          name: getUserBindingServiceName(
            FLAGSHIP_PLUGIN_NAME,
            name,
            remoteProxyConnectionString
          ),
          worker: remoteProxyConnectionString ? remoteProxyClientWorker(remoteProxyConnectionString, name) : {
            compatibilityDate: "2025-03-17",
            modules: [
              {
                name: "binding.worker.js",
                esModule: binding_worker_default2()
              }
            ]
          }
        };
      }
    );
  }
};

// src/plugins/hello-world/index.ts
var import_promises11 = __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_fs24 = __toESM(require("fs"));
var import_path24 = __toESM(require("path"));
var import_url24 = __toESM(require("url"));
var contents24;
function binding_worker_default3() {
  if (contents24 !== void 0) return contents24;
  const filePath = import_path24.default.join(__dirname, "workers", "hello-world/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/hello-world/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", "hello-world/object.worker.js");
  contents25 = import_fs25.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url25.default.pathToFileURL(filePath);
  return contents25;
}

// src/plugins/hello-world/index.ts
var HELLO_WORLD_PLUGIN_NAME = "hello-world";
var HelloWorldOptionsSchema = external_exports.object({
  helloWorld: external_exports.record(
    external_exports.object({
      enable_timer: external_exports.boolean().optional()
    })
  ).optional()
});
var HelloWorldSharedOptionsSchema = external_exports.object({
  helloWorldPersist: PersistenceSchema
});
var HELLO_WORLD_PLUGIN = {
  options: HelloWorldOptionsSchema,
  sharedOptions: HelloWorldSharedOptionsSchema,
  async getBindings(options) {
    if (!options.helloWorld) {
      return [];
    }
    const bindings = Object.entries(options.helloWorld).map(
      ([name, config]) => {
        return {
          name,
          service: {
            name: `${HELLO_WORLD_PLUGIN_NAME}:${JSON.stringify(config.enable_timer ?? false)}`,
            entrypoint: "HelloWorldBinding"
          }
        };
      }
    );
    return bindings;
  },
  getNodeBindings(options) {
    if (!options.helloWorld) {
      return {};
    }
    return Object.fromEntries(
      Object.keys(options.helloWorld).map((name) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({
    options,
    sharedOptions,
    tmpPath,
    defaultPersistRoot,
    unsafeStickyBlobs
  }) {
    const configs = options.helloWorld ? Object.values(options.helloWorld) : [];
    if (configs.length === 0) {
      return [];
    }
    const persistPath = getPersistPath(
      HELLO_WORLD_PLUGIN_NAME,
      tmpPath,
      defaultPersistRoot,
      sharedOptions.helloWorldPersist
    );
    await import_promises11.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_default()
          }
        ],
        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(unsafeStickyBlobs)
        ]
      }
    };
    const services = configs.map((config) => ({
      name: `${HELLO_WORLD_PLUGIN_NAME}:${JSON.stringify(config.enable_timer ?? false)}`,
      worker: {
        compatibilityDate: "2025-01-01",
        modules: [
          {
            name: "binding.worker.js",
            esModule: binding_worker_default3()
          }
        ],
        bindings: [
          {
            name: "config",
            json: JSON.stringify(config)
          },
          {
            name: "store",
            durableObjectNamespace: {
              className: "HelloWorldObject",
              serviceName: objectService.name
            }
          }
        ]
      }
    }));
    return [...services, storageService, objectService];
  },
  getPersistPath(sharedOptions, tmpPath) {
    return getPersistPath(
      HELLO_WORLD_PLUGIN_NAME,
      tmpPath,
      void 0,
      sharedOptions.helloWorldPersist
    );
  }
};

// src/plugins/hyperdrive/index.ts
var import_node_assert19 = __toESM(require("node:assert"));
var HYPERDRIVE_PLUGIN_NAME = "hyperdrive";
function hasPostgresProtocol(url38) {
  return url38.protocol === "postgresql:" || url38.protocol === "postgres:";
}
function hasMysqlProtocol(url38) {
  return url38.protocol === "mysql:";
}
function getPort(url38) {
  if (url38.port !== "") return url38.port;
  if (hasPostgresProtocol(url38)) return "5432";
  if (hasMysqlProtocol(url38)) return "3306";
  import_node_assert19.default.fail(`Expected known protocol, got ${url38.protocol}`);
}
var HyperdriveSchema = external_exports.union([external_exports.string().url(), external_exports.instanceof(URL)]).transform((url38, ctx) => {
  if (typeof url38 === "string") url38 = new URL(url38);
  if (url38.protocol === "") {
    ctx.addIssue({
      code: external_exports.ZodIssueCode.custom,
      message: "You must specify the database protocol - e.g. 'postgresql'/'mysql'."
    });
  } else if (!hasPostgresProtocol(url38) && !hasMysqlProtocol(url38)) {
    ctx.addIssue({
      code: external_exports.ZodIssueCode.custom,
      message: "Only PostgreSQL-compatible or MySQL-compatible databases are currently supported."
    });
  }
  if (url38.host === "") {
    ctx.addIssue({
      code: external_exports.ZodIssueCode.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 (url38.pathname === "") {
    ctx.addIssue({
      code: external_exports.ZodIssueCode.custom,
      message: "You must provide a database name as the path component - e.g. /postgres"
    });
  }
  if (url38.username === "") {
    ctx.addIssue({
      code: external_exports.ZodIssueCode.custom,
      message: "You must provide a username - e.g. 'user:password@database.example.com:port/databasename'"
    });
  }
  if (url38.password === "") {
    ctx.addIssue({
      code: external_exports.ZodIssueCode.custom,
      message: "You must provide a password - e.g. 'user:password@database.example.com:port/databasename' "
    });
  }
  return url38;
});
var HyperdriveInputOptionsSchema = external_exports.object({
  hyperdrives: external_exports.record(external_exports.string(), HyperdriveSchema).optional()
});
var HYPERDRIVE_PLUGIN = {
  options: HyperdriveInputOptionsSchema,
  getBindings(options) {
    return Object.entries(options.hyperdrives ?? {}).map(
      ([name, url38]) => {
        const database = url38.pathname.replace("/", "");
        const scheme = url38.protocol.replace(":", "");
        return {
          name,
          hyperdrive: {
            designator: {
              name: `${HYPERDRIVE_PLUGIN_NAME}:${name}`
            },
            database: decodeURIComponent(database),
            user: decodeURIComponent(url38.username),
            password: decodeURIComponent(url38.password),
            scheme
          }
        };
      }
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      Object.entries(options.hyperdrives ?? {}).map(([name, url38]) => {
        const connectionOverrides = {
          connectionString: `${url38}`,
          port: Number.parseInt(url38.port),
          host: url38.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, url38] of Object.entries(options.hyperdrives ?? {})) {
      const scheme = url38.protocol.replace(":", "");
      const proxyPort = await hyperdriveProxyController.createProxyServer({
        name,
        targetHost: url38.hostname,
        targetPort: getPort(url38),
        scheme,
        sslmode: parseSslMode(url38, scheme)
      });
      services.push({
        name: `${HYPERDRIVE_PLUGIN_NAME}:${name}`,
        external: {
          address: `127.0.0.1:${proxyPort}`,
          tcp: {}
        }
      });
    }
    return services;
  }
};
function parseSslMode(url38, scheme) {
  const params = Object.fromEntries(
    Array.from(url38.searchParams.entries()).map(([k, v2]) => [
      k.toLowerCase(),
      v2.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 "required":
      case "true":
      case "1":
        return "require";
      case "preferred":
        return "prefer";
      case "disabled":
      case "false":
      case "0":
        return "disable";
    }
  }
  return "disable";
}

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

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/images/images.worker.ts
var import_fs26 = __toESM(require("fs"));
var import_path26 = __toESM(require("path"));
var import_url26 = __toESM(require("url"));
var contents26;
function images_worker_default() {
  if (contents26 !== void 0) return contents26;
  const filePath = import_path26.default.join(__dirname, "workers", "images/images.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/kv/namespace.worker.ts
var import_fs27 = __toESM(require("fs"));
var import_path27 = __toESM(require("path"));
var import_url27 = __toESM(require("url"));
var contents27;
function namespace_worker_default() {
  if (contents27 !== void 0) return contents27;
  const filePath = import_path27.default.join(__dirname, "workers", "kv/namespace.worker.js");
  contents27 = import_fs27.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url27.default.pathToFileURL(filePath);
  return contents27;
}

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

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

// src/plugins/kv/sites.ts
var import_node_assert20 = __toESM(require("node:assert"));
var import_promises12 = __toESM(require("node:fs/promises"));
var import_node_path23 = __toESM(require("node:path"));

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

// src/plugins/kv/sites.ts
async function* listKeysInDirectoryInner(rootPath2, currentPath) {
  const fileEntries = await import_promises12.default.readdir(currentPath, { withFileTypes: true });
  for (const fileEntry of fileEntries) {
    const filePath = import_node_path23.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_path23.default.resolve(rootPath2);
  return listKeysInDirectoryInner(rootPath2, rootPath2);
}
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) {
  const siteRegExps = {
    include: options.siteInclude && globsToRegExps(options.siteInclude),
    exclude: options.siteExclude && globsToRegExps(options.siteExclude)
  };
  sitesRegExpsCache.set(options, siteRegExps);
  const __STATIC_CONTENT_MANIFEST = await buildStaticContentManifest(
    options.sitePath,
    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) {
  const siteRegExps = sitesRegExpsCache.get(options);
  (0, import_node_assert20.default)(siteRegExps !== void 0);
  const __STATIC_CONTENT_MANIFEST = await buildStaticContentManifest(
    options.sitePath,
    siteRegExps
  );
  return {
    [SiteBindings.KV_NAMESPACE_SITE]: new ProxyNodeBinding(),
    [SiteBindings.JSON_SITE_MANIFEST]: __STATIC_CONTENT_MANIFEST
  };
}
function getSitesServices(options) {
  const siteRegExps = sitesRegExpsCache.get(options);
  (0, import_node_assert20.default)(siteRegExps !== void 0);
  const serialisedSiteRegExps = serialiseSiteRegExps(siteRegExps);
  const persist = import_node_path23.default.resolve(options.sitePath);
  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 KVOptionsSchema = external_exports.object({
  kvNamespaces: external_exports.union([
    external_exports.record(
      external_exports.union([
        external_exports.string(),
        external_exports.object({
          id: external_exports.string(),
          remoteProxyConnectionString: external_exports.custom().optional()
        })
      ])
    ),
    external_exports.string().array()
  ]).optional(),
  // Workers Sites
  sitePath: PathSchema.optional(),
  siteInclude: external_exports.string().array().optional(),
  siteExclude: external_exports.string().array().optional()
});
var KVSharedOptionsSchema = external_exports.object({
  kvPersist: PersistenceSchema
});
var SERVICE_NAMESPACE_PREFIX = `${KV_PLUGIN_NAME}:ns`;
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.sitePath !== void 0;
}
var KV_PLUGIN = {
  options: KVOptionsSchema,
  sharedOptions: KVSharedOptionsSchema,
  async getBindings(options) {
    const namespaces = namespaceEntries(options.kvNamespaces);
    const bindings = namespaces.map(([name, namespace]) => ({
      name,
      kvNamespace: {
        name: getUserBindingServiceName(
          SERVICE_NAMESPACE_PREFIX,
          namespace.id,
          namespace.remoteProxyConnectionString
        )
      }
    }));
    if (isWorkersSitesEnabled(options)) {
      bindings.push(...await getSitesBindings(options));
    }
    return bindings;
  },
  async getNodeBindings(options) {
    const namespaces = namespaceKeys(options.kvNamespaces);
    const bindings = Object.fromEntries(
      namespaces.map((name) => [name, new ProxyNodeBinding()])
    );
    if (isWorkersSitesEnabled(options)) {
      Object.assign(bindings, await getSitesNodeBindings(options));
    }
    return bindings;
  },
  async getServices({
    options,
    sharedOptions,
    tmpPath,
    defaultPersistRoot,
    log: log2,
    unsafeStickyBlobs
  }) {
    const persist = sharedOptions.kvPersist;
    const namespaces = namespaceEntries(options.kvNamespaces);
    const services = namespaces.map(
      ([name, { id, remoteProxyConnectionString }]) => ({
        name: getUserBindingServiceName(
          SERVICE_NAMESPACE_PREFIX,
          id,
          remoteProxyConnectionString
        ),
        worker: remoteProxyConnectionString ? remoteProxyClientWorker(remoteProxyConnectionString, name) : objectEntryWorker(KV_NAMESPACE_OBJECT, id)
      })
    );
    if (services.length > 0) {
      const uniqueKey = `miniflare-${KV_NAMESPACE_OBJECT_CLASS_NAME}`;
      const persistPath = getPersistPath(
        KV_PLUGIN_NAME,
        tmpPath,
        defaultPersistRoot,
        persist
      );
      await import_promises13.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(unsafeStickyBlobs)
          ]
        }
      };
      services.push(storageService, objectService);
      for (const namespace of namespaces) {
        await migrateDatabase(log2, uniqueKey, persistPath, namespace[1].id);
      }
    }
    if (isWorkersSitesEnabled(options)) {
      services.push(...getSitesServices(options));
    }
    return services;
  },
  getPersistPath({ kvPersist }, tmpPath) {
    return getPersistPath(KV_PLUGIN_NAME, tmpPath, void 0, kvPersist);
  }
};

// src/plugins/images/index.ts
var ImagesSchema = external_exports.object({
  binding: external_exports.string(),
  remoteProxyConnectionString: external_exports.custom().optional()
});
var ImagesOptionsSchema = external_exports.object({
  images: ImagesSchema.optional()
});
var ImagesSharedOptionsSchema = external_exports.object({
  imagesPersist: PersistenceSchema
});
var IMAGES_PLUGIN_NAME = "images";
var IMAGES_PLUGIN = {
  options: ImagesOptionsSchema,
  sharedOptions: ImagesSharedOptionsSchema,
  async getBindings(options) {
    if (!options.images) {
      return [];
    }
    return [
      {
        name: options.images.binding,
        wrapped: {
          moduleName: "cloudflare-internal:images-api",
          innerBindings: [
            {
              name: "fetcher",
              service: {
                name: getUserBindingServiceName(
                  IMAGES_PLUGIN_NAME,
                  options.images.binding,
                  options.images.remoteProxyConnectionString
                )
              }
            }
          ]
        }
      }
    ];
  },
  getNodeBindings(options) {
    if (!options.images) {
      return {};
    }
    return {
      [options.images.binding]: new ProxyNodeBinding()
    };
  },
  async getServices({
    options,
    sharedOptions,
    tmpPath,
    defaultPersistRoot,
    unsafeStickyBlobs
  }) {
    if (!options.images) {
      return [];
    }
    const serviceName = getUserBindingServiceName(
      IMAGES_PLUGIN_NAME,
      options.images.binding,
      options.images.remoteProxyConnectionString
    );
    if (options.images.remoteProxyConnectionString) {
      return [
        {
          name: serviceName,
          worker: remoteProxyClientWorker(
            options.images.remoteProxyConnectionString,
            options.images.binding
          )
        }
      ];
    }
    const persistPath = getPersistPath(
      IMAGES_PLUGIN_NAME,
      tmpPath,
      defaultPersistRoot,
      sharedOptions.imagesPersist
    );
    await import_promises14.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(unsafeStickyBlobs)
        ]
      }
    };
    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
        ]
      }
    };
    return [storageService, objectService, kvNamespaceService, imagesService];
  },
  getPersistPath({ imagesPersist }, tmpPath) {
    return getPersistPath(
      IMAGES_PLUGIN_NAME,
      tmpPath,
      void 0,
      imagesPersist
    );
  }
};

// src/plugins/media/index.ts
var MEDIA_PLUGIN_NAME = "media";
var MediaSchema = external_exports.object({
  binding: external_exports.string(),
  remoteProxyConnectionString: external_exports.custom().optional()
});
var MediaOptionsSchema = external_exports.object({
  media: MediaSchema.optional()
});
var MEDIA_PLUGIN = {
  options: MediaOptionsSchema,
  async getBindings(options) {
    if (!options.media) {
      return [];
    }
    return [
      {
        name: options.media.binding,
        service: {
          name: getUserBindingServiceName(
            MEDIA_PLUGIN_NAME,
            options.media.binding,
            options.media.remoteProxyConnectionString
          )
        }
      }
    ];
  },
  getNodeBindings(options) {
    if (!options.media) {
      return {};
    }
    return {
      [options.media.binding]: new ProxyNodeBinding()
    };
  },
  async getServices({ options }) {
    if (!options.media) {
      return [];
    }
    return [
      {
        name: getUserBindingServiceName(
          MEDIA_PLUGIN_NAME,
          options.media.binding,
          options.media.remoteProxyConnectionString
        ),
        worker: remoteProxyClientWorker(
          options.media.remoteProxyConnectionString,
          options.media.binding
        )
      }
    ];
  }
};

// src/plugins/mtls/index.ts
var MtlsSchema = external_exports.object({
  certificate_id: external_exports.string(),
  remoteProxyConnectionString: external_exports.custom().optional()
});
var MtlsOptionsSchema = external_exports.object({
  mtlsCertificates: external_exports.record(MtlsSchema).optional()
});
var MTLS_PLUGIN_NAME = "mtls";
var MTLS_PLUGIN = {
  options: MtlsOptionsSchema,
  async getBindings(options) {
    if (!options.mtlsCertificates) {
      return [];
    }
    return Object.entries(options.mtlsCertificates).map(
      ([name, { certificate_id, remoteProxyConnectionString }]) => {
        return {
          name,
          service: {
            name: getUserBindingServiceName(
              MTLS_PLUGIN_NAME,
              certificate_id,
              remoteProxyConnectionString
            )
          }
        };
      }
    );
  },
  getNodeBindings(options) {
    if (!options.mtlsCertificates) {
      return {};
    }
    return Object.fromEntries(
      Object.keys(options.mtlsCertificates).map((name) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    if (!options.mtlsCertificates) {
      return [];
    }
    return Object.entries(options.mtlsCertificates).map(
      ([name, { certificate_id, remoteProxyConnectionString }]) => {
        return {
          name: getUserBindingServiceName(
            MTLS_PLUGIN_NAME,
            certificate_id,
            remoteProxyConnectionString
          ),
          worker: remoteProxyClientWorker(remoteProxyConnectionString, name)
        };
      }
    );
  }
};

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

// src/plugins/pipelines/index.ts
var PipelineOptionsSchema = external_exports.object({
  pipelines: external_exports.union([
    external_exports.record(
      external_exports.union([
        external_exports.string(),
        external_exports.object({
          pipeline: external_exports.string(),
          remoteProxyConnectionString: external_exports.custom().optional()
        })
      ])
    ),
    external_exports.string().array()
  ]).optional()
});
var PIPELINES_PLUGIN_NAME = "pipelines";
var SERVICE_PIPELINE_PREFIX = `${PIPELINES_PLUGIN_NAME}:pipeline`;
var PIPELINE_PLUGIN = {
  options: PipelineOptionsSchema,
  getBindings(options) {
    const pipelines = bindingEntries(options.pipelines);
    return pipelines.map(([name, { id }]) => ({
      name,
      service: { name: `${SERVICE_PIPELINE_PREFIX}:${id}` }
    }));
  },
  getNodeBindings(options) {
    const buckets = namespaceKeys(options.pipelines);
    return Object.fromEntries(
      buckets.map((name) => [name, new ProxyNodeBinding()])
    );
  },
  async getServices({ options }) {
    const pipelines = bindingEntries(options.pipelines);
    const services = [];
    for (const [bindingName, pipeline] of pipelines) {
      services.push({
        name: `${SERVICE_PIPELINE_PREFIX}:${pipeline.id}`,
        worker: pipeline.remoteProxyConnectionString ? remoteProxyClientWorker(
          pipeline.remoteProxyConnectionString,
          bindingName
        ) : {
          compatibilityDate: "2024-12-30",
          modules: [
            {
              name: "pipeline.worker.js",
              esModule: pipeline_worker_default()
            }
          ]
        }
      });
    }
    return services;
  }
};
function bindingEntries(namespaces) {
  if (Array.isArray(namespaces)) {
    return namespaces.map((bindingName) => [bindingName, { id: bindingName }]);
  } else if (namespaces !== void 0) {
    return Object.entries(namespaces).map(([name, opts]) => [
      name,
      typeof opts === "string" ? { id: opts } : {
        id: opts.pipeline,
        remoteProxyConnectionString: opts.remoteProxyConnectionString
      }
    ]);
  } else {
    return [];
  }
}

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

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

// src/plugins/queues/index.ts
var QueuesOptionsSchema = external_exports.object({
  queueProducers: external_exports.union([
    external_exports.record(
      QueueProducerOptionsSchema.merge(
        external_exports.object({
          remoteProxyConnectionString: external_exports.custom().optional()
        })
      )
    ),
    external_exports.string().array(),
    external_exports.record(external_exports.string())
  ]).optional(),
  queueConsumers: external_exports.union([external_exports.record(QueueConsumerOptionsSchema), external_exports.string().array()]).optional()
});
var QUEUES_PLUGIN_NAME = "queues";
var SERVICE_QUEUE_PREFIX = `${QUEUES_PLUGIN_NAME}:queue`;
var QUEUE_BROKER_OBJECT_CLASS_NAME = "QueueBrokerObject";
var QUEUE_BROKER_OBJECT = {
  serviceName: SERVICE_QUEUE_PREFIX,
  className: QUEUE_BROKER_OBJECT_CLASS_NAME
};
var QUEUES_PLUGIN = {
  options: QueuesOptionsSchema,
  getBindings(options) {
    const queues = bindingEntries2(options.queueProducers);
    return queues.map(([name, id]) => ({
      name,
      queue: { name: `${SERVICE_QUEUE_PREFIX}:${id}` }
    }));
  },
  getNodeBindings(options) {
    const queues = bindingKeys(options.queueProducers);
    return Object.fromEntries(
      queues.map((name) => [name, new ProxyNodeBinding()])
    );
  },
  async getServices({
    options,
    workerNames,
    queueProducers: allQueueProducers,
    queueConsumers: allQueueConsumers,
    unsafeStickyBlobs
  }) {
    const queues = bindingEntries2(options.queueProducers);
    if (queues.length === 0) return [];
    const services = queues.map(([_2, id]) => ({
      name: `${SERVICE_QUEUE_PREFIX}:${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(unsafeStickyBlobs),
          {
            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) }
          }))
        ]
      }
    };
    services.push(objectService);
    return services;
  }
};
function bindingEntries2(namespaces) {
  if (Array.isArray(namespaces)) {
    return namespaces.map((bindingName) => [bindingName, bindingName]);
  } else if (namespaces !== void 0) {
    return Object.entries(namespaces).map(([name, opts]) => [
      name,
      typeof opts === "string" ? opts : opts.queueName
    ]);
  } else {
    return [];
  }
}
function bindingKeys(namespaces) {
  if (Array.isArray(namespaces)) {
    return namespaces;
  } else if (namespaces !== void 0) {
    return Object.keys(namespaces);
  } else {
    return [];
  }
}

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

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

// src/plugins/r2/index.ts
var R2OptionsSchema = external_exports.object({
  r2Buckets: external_exports.union([
    external_exports.record(
      external_exports.union([
        external_exports.string(),
        external_exports.object({
          id: external_exports.string(),
          remoteProxyConnectionString: external_exports.custom().optional()
        })
      ])
    ),
    external_exports.string().array()
  ]).optional()
});
var R2SharedOptionsSchema = external_exports.object({
  r2Persist: PersistenceSchema
});
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_BUCKET_OBJECT_CLASS_NAME = "R2BucketObject";
var R2_BUCKET_OBJECT = {
  serviceName: R2_BUCKET_SERVICE_PREFIX,
  className: R2_BUCKET_OBJECT_CLASS_NAME
};
var R2_PLUGIN = {
  options: R2OptionsSchema,
  sharedOptions: R2SharedOptionsSchema,
  getBindings(options) {
    const buckets = namespaceEntries(options.r2Buckets);
    return buckets.map(([name, bucket]) => ({
      name,
      r2Bucket: {
        name: getUserBindingServiceName(
          R2_BUCKET_SERVICE_PREFIX,
          bucket.id,
          bucket.remoteProxyConnectionString
        )
      }
    }));
  },
  getNodeBindings(options) {
    const buckets = namespaceKeys(options.r2Buckets);
    return Object.fromEntries(
      buckets.map((name) => [name, new ProxyNodeBinding()])
    );
  },
  async getServices({
    options,
    sharedOptions,
    tmpPath,
    defaultPersistRoot,
    log: log2,
    unsafeStickyBlobs
  }) {
    const persist = sharedOptions.r2Persist;
    const buckets = namespaceEntries(options.r2Buckets);
    const services = buckets.map(
      ([name, { id, remoteProxyConnectionString }]) => ({
        name: getUserBindingServiceName(
          R2_BUCKET_SERVICE_PREFIX,
          id,
          remoteProxyConnectionString
        ),
        worker: remoteProxyConnectionString ? remoteProxyClientWorker(remoteProxyConnectionString, name) : objectEntryWorker(R2_BUCKET_OBJECT, id)
      })
    );
    if (buckets.length > 0) {
      const uniqueKey = `miniflare-${R2_BUCKET_OBJECT_CLASS_NAME}`;
      const persistPath = getPersistPath(
        R2_PLUGIN_NAME,
        tmpPath,
        defaultPersistRoot,
        persist
      );
      await import_promises15.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(unsafeStickyBlobs)
          ]
        }
      };
      services.push(storageService, objectService);
      for (const bucket of buckets) {
        await migrateDatabase(log2, uniqueKey, persistPath, bucket[1].id);
      }
    }
    return services;
  },
  getPersistPath({ r2Persist }, tmpPath) {
    return getPersistPath(R2_PLUGIN_NAME, tmpPath, void 0, r2Persist);
  }
};

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

// src/plugins/ratelimit/index.ts
var PeriodType = /* @__PURE__ */ ((PeriodType2) => {
  PeriodType2[PeriodType2["TENSECONDS"] = 10] = "TENSECONDS";
  PeriodType2[PeriodType2["MINUTE"] = 60] = "MINUTE";
  return PeriodType2;
})(PeriodType || {});
var RatelimitConfigSchema = external_exports.object({
  simple: external_exports.object({
    limit: external_exports.number().gt(0),
    // may relax this to be any number in the future
    period: external_exports.nativeEnum(PeriodType).optional()
  })
});
var RatelimitOptionsSchema = external_exports.object({
  ratelimits: external_exports.record(RatelimitConfigSchema).optional()
});
var RATELIMIT_PLUGIN_NAME = "ratelimit";
var SERVICE_RATELIMIT_PREFIX = `${RATELIMIT_PLUGIN_NAME}`;
var SERVICE_RATELIMIT_MODULE = `cloudflare-internal:${SERVICE_RATELIMIT_PREFIX}:module`;
function buildJsonBindings2(bindings) {
  return Object.entries(bindings).map(([name, value]) => ({
    name,
    json: JSON.stringify(value)
  }));
}
var RATELIMIT_PLUGIN = {
  options: RatelimitOptionsSchema,
  getBindings(options) {
    if (!options.ratelimits) {
      return [];
    }
    const bindings = Object.entries(options.ratelimits).map(
      ([name, config]) => ({
        name,
        wrapped: {
          moduleName: SERVICE_RATELIMIT_MODULE,
          innerBindings: buildJsonBindings2({
            namespaceId: name,
            limit: config.simple.limit,
            period: config.simple.period
          })
        }
      })
    );
    return bindings;
  },
  getNodeBindings(options) {
    if (!options.ratelimits) {
      return {};
    }
    return Object.fromEntries(
      Object.keys(options.ratelimits).map((name) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices() {
    return [];
  },
  getExtensions({ options }) {
    if (!options.some((o) => o.ratelimits)) {
      return [];
    }
    return [
      {
        modules: [
          {
            name: SERVICE_RATELIMIT_MODULE,
            esModule: ratelimit_worker_default(),
            internal: true
          }
        ]
      }
    ];
  }
};

// src/plugins/secret-store/index.ts
var import_promises16 = __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_fs33 = __toESM(require("fs"));
var import_path33 = __toESM(require("path"));
var import_url33 = __toESM(require("url"));
var contents33;
function secret_worker_default() {
  if (contents33 !== void 0) return contents33;
  const filePath = import_path33.default.join(__dirname, "workers", "secrets-store/secret.worker.js");
  contents33 = import_fs33.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url33.default.pathToFileURL(filePath);
  return contents33;
}

// src/plugins/secret-store/index.ts
var SecretsStoreSecretsSchema = external_exports.record(
  external_exports.object({
    store_id: external_exports.string(),
    secret_name: external_exports.string()
  })
);
var SecretsStoreSecretsOptionsSchema = external_exports.object({
  secretsStoreSecrets: SecretsStoreSecretsSchema.optional()
});
var SecretsStoreSecretsSharedOptionsSchema = external_exports.object({
  secretsStorePersist: PersistenceSchema
});
var SECRET_STORE_PLUGIN_NAME = "secrets-store";
var SECRET_STORE_PLUGIN = {
  options: SecretsStoreSecretsOptionsSchema,
  sharedOptions: SecretsStoreSecretsSharedOptionsSchema,
  async getBindings(options) {
    if (!options.secretsStoreSecrets) {
      return [];
    }
    const bindings = Object.entries(
      options.secretsStoreSecrets
    ).map(([name, config]) => {
      return {
        name,
        service: {
          name: getUserBindingServiceName(
            SECRET_STORE_PLUGIN_NAME,
            `${config.store_id}:${config.secret_name}`
          ),
          entrypoint: "SecretsStoreSecret"
        }
      };
    });
    return bindings;
  },
  getNodeBindings(options) {
    if (!options.secretsStoreSecrets) {
      return {};
    }
    return Object.fromEntries(
      Object.keys(options.secretsStoreSecrets).map((name) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({
    options,
    sharedOptions,
    tmpPath,
    defaultPersistRoot,
    unsafeStickyBlobs
  }) {
    const configs = options.secretsStoreSecrets ? Object.values(options.secretsStoreSecrets) : [];
    if (configs.length === 0) {
      return [];
    }
    const persistPath = getPersistPath(
      SECRET_STORE_PLUGIN_NAME,
      tmpPath,
      defaultPersistRoot,
      sharedOptions.secretsStorePersist
    );
    await import_promises16.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(unsafeStickyBlobs)
        ]
      }
    };
    const services = configs.flatMap((config) => {
      const kvNamespaceService = {
        name: `${SECRET_STORE_PLUGIN_NAME}:ns:${config.store_id}`,
        worker: objectEntryWorker(
          {
            serviceName: objectService.name,
            className: KV_NAMESPACE_OBJECT_CLASS_NAME
          },
          config.store_id
        )
      };
      const secretStoreSecretService = {
        name: getUserBindingServiceName(
          SECRET_STORE_PLUGIN_NAME,
          `${config.store_id}:${config.secret_name}`
        ),
        worker: {
          compatibilityDate: "2025-01-01",
          modules: [
            {
              name: "secret.worker.js",
              esModule: secret_worker_default()
            }
          ],
          bindings: [
            {
              name: "store",
              kvNamespace: {
                name: kvNamespaceService.name
              }
            },
            {
              name: "secret_name",
              json: JSON.stringify(config.secret_name)
            }
          ]
        }
      };
      return [kvNamespaceService, secretStoreSecretService];
    });
    return [...services, storageService, objectService];
  },
  getPersistPath({ secretsStorePersist }, tmpPath) {
    return getPersistPath(
      SECRET_STORE_PLUGIN_NAME,
      tmpPath,
      void 0,
      secretsStorePersist
    );
  }
};

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

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

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

// src/plugins/stream/index.ts
var StreamSchema = external_exports.object({
  binding: external_exports.string(),
  remoteProxyConnectionString: external_exports.custom().optional()
});
var StreamOptionsSchema = external_exports.object({
  stream: StreamSchema.optional()
});
var StreamSharedOptionsSchema = external_exports.object({
  streamPersist: PersistenceSchema
});
var STREAM_PLUGIN_NAME = "stream";
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 = {
  options: StreamOptionsSchema,
  sharedOptions: StreamSharedOptionsSchema,
  async getBindings(options) {
    if (!options.stream) {
      return [];
    }
    return [
      {
        name: options.stream.binding,
        service: {
          name: getUserBindingServiceName(
            STREAM_PLUGIN_NAME,
            options.stream.binding,
            options.stream.remoteProxyConnectionString
          ),
          entrypoint: "StreamBinding"
        }
      }
    ];
  },
  getNodeBindings(options) {
    if (!options.stream) {
      return {};
    }
    return {
      [options.stream.binding]: new ProxyNodeBinding()
    };
  },
  async getServices({
    options,
    sharedOptions,
    tmpPath,
    defaultPersistRoot,
    unsafeStickyBlobs
  }) {
    if (!options.stream) {
      return [];
    }
    const serviceName = getUserBindingServiceName(
      STREAM_PLUGIN_NAME,
      options.stream.binding,
      options.stream.remoteProxyConnectionString
    );
    if (options.stream.remoteProxyConnectionString) {
      return [
        {
          name: serviceName,
          worker: remoteProxyClientWorker(
            options.stream.remoteProxyConnectionString,
            options.stream.binding
          )
        }
      ];
    }
    const persistPath = getPersistPath(
      STREAM_PLUGIN_NAME,
      tmpPath,
      defaultPersistRoot,
      sharedOptions.streamPersist
    );
    await import_promises17.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_default2()
          }
        ],
        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(unsafeStickyBlobs)
        ],
        // Allow the DO to send outbound HTTP requests (fetching watermark images)
        globalOutbound: { name: "internet" }
      }
    };
    const bindingService = {
      name: serviceName,
      worker: {
        compatibilityDate: STREAM_COMPAT_DATE,
        compatibilityFlags: ["nodejs_compat", "experimental"],
        modules: [
          {
            name: "binding.worker.js",
            esModule: binding_worker_default4()
          }
        ],
        bindings: [
          {
            name: "store",
            durableObjectNamespace: {
              className: STREAM_OBJECT_CLASS_NAME,
              serviceName: STREAM_OBJECT_SERVICE_NAME
            }
          }
        ],
        // Allow the binding worker to send outbound HTTP requests
        // (e.g. fetching video from URL in upload fn)
        globalOutbound: { name: "internet" }
      }
    };
    return [storageService, objectService, bindingService];
  },
  getPersistPath({ streamPersist }, tmpPath) {
    return getPersistPath(
      STREAM_PLUGIN_NAME,
      tmpPath,
      void 0,
      streamPersist
    );
  }
};

// src/plugins/vectorize/index.ts
var VectorizeSchema = external_exports.object({
  index_name: external_exports.string(),
  remoteProxyConnectionString: external_exports.custom().optional()
});
var VectorizeOptionsSchema = external_exports.object({
  vectorize: external_exports.record(VectorizeSchema).optional()
});
var VECTORIZE_PLUGIN_NAME = "vectorize";
var VECTORIZE_PLUGIN = {
  options: VectorizeOptionsSchema,
  async getBindings(options) {
    if (!options.vectorize) {
      return [];
    }
    return Object.entries(options.vectorize).map(
      ([name, { index_name, remoteProxyConnectionString }]) => {
        return {
          name,
          wrapped: {
            moduleName: "cloudflare-internal:vectorize-api",
            innerBindings: [
              {
                name: "fetcher",
                service: {
                  name: getUserBindingServiceName(
                    VECTORIZE_PLUGIN_NAME,
                    name,
                    remoteProxyConnectionString
                  )
                }
              },
              {
                name: "indexId",
                text: index_name
              },
              {
                name: "indexVersion",
                text: "v2"
              },
              {
                name: "useNdJson",
                json: true
              }
            ]
          }
        };
      }
    );
  },
  getNodeBindings(options) {
    if (!options.vectorize) {
      return {};
    }
    return Object.fromEntries(
      Object.keys(options.vectorize).map((name) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    if (!options.vectorize) {
      return [];
    }
    return Object.entries(options.vectorize).map(
      ([name, { remoteProxyConnectionString }]) => {
        return {
          name: getUserBindingServiceName(
            VECTORIZE_PLUGIN_NAME,
            name,
            remoteProxyConnectionString
          ),
          worker: remoteProxyClientWorker(remoteProxyConnectionString, name)
        };
      }
    );
  }
};

// src/plugins/version-metadata/index.ts
var import_node_crypto5 = require("node:crypto");
var VERSION_METADATA_PLUGIN_NAME = "version-metadata";
var VersionMetadataOptionsSchema = external_exports.object({
  versionMetadata: external_exports.string().optional()
});
var VERSION_METADATA_PLUGIN = {
  options: VersionMetadataOptionsSchema,
  async getBindings(options) {
    if (!options.versionMetadata) {
      return [];
    }
    const id = (0, import_node_crypto5.randomUUID)();
    const tag = "";
    const timestamp = (/* @__PURE__ */ new Date()).toISOString();
    const bindings = [
      {
        name: options.versionMetadata,
        json: JSON.stringify({ id, tag, timestamp })
      }
    ];
    return bindings;
  },
  getNodeBindings(options) {
    if (!options.versionMetadata) {
      return {};
    }
    const id = (0, import_node_crypto5.randomUUID)();
    const tag = "";
    const timestamp = (/* @__PURE__ */ new Date()).toISOString();
    return {
      [options.versionMetadata]: { id, tag, timestamp }
    };
  },
  async getServices() {
    return [];
  }
};

// src/plugins/vpc-networks/index.ts
var VpcNetworksSchema = external_exports.union([
  external_exports.object({
    tunnel_id: external_exports.string(),
    remoteProxyConnectionString: external_exports.custom().optional()
  }),
  external_exports.object({
    network_id: external_exports.string(),
    remoteProxyConnectionString: external_exports.custom().optional()
  })
]);
var VpcNetworksOptionsSchema = external_exports.object({
  vpcNetworks: external_exports.record(VpcNetworksSchema).optional()
});
var VPC_NETWORKS_PLUGIN_NAME = "vpc-networks";
var VPC_NETWORKS_PLUGIN = {
  options: VpcNetworksOptionsSchema,
  async getBindings(options) {
    if (!options.vpcNetworks) {
      return [];
    }
    return Object.entries(options.vpcNetworks).map(([name, binding]) => {
      const identifier = "tunnel_id" in binding ? binding.tunnel_id : binding.network_id;
      return {
        name,
        service: {
          name: getUserBindingServiceName(
            VPC_NETWORKS_PLUGIN_NAME,
            identifier,
            binding.remoteProxyConnectionString
          )
        }
      };
    });
  },
  getNodeBindings(options) {
    if (!options.vpcNetworks) {
      return {};
    }
    return Object.fromEntries(
      Object.keys(options.vpcNetworks).map((name) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    if (!options.vpcNetworks) {
      return [];
    }
    return Object.entries(options.vpcNetworks).map(([name, binding]) => {
      const identifier = "tunnel_id" in binding ? binding.tunnel_id : binding.network_id;
      return {
        name: getUserBindingServiceName(
          VPC_NETWORKS_PLUGIN_NAME,
          identifier,
          binding.remoteProxyConnectionString
        ),
        worker: remoteProxyClientWorker(
          binding.remoteProxyConnectionString,
          name
        )
      };
    });
  }
};

// src/plugins/vpc-services/index.ts
var VpcServicesSchema = external_exports.object({
  service_id: external_exports.string(),
  remoteProxyConnectionString: external_exports.custom().optional()
});
var VpcServicesOptionsSchema = external_exports.object({
  vpcServices: external_exports.record(VpcServicesSchema).optional()
});
var VPC_SERVICES_PLUGIN_NAME = "vpc-services";
var VPC_SERVICES_PLUGIN = {
  options: VpcServicesOptionsSchema,
  async getBindings(options) {
    if (!options.vpcServices) {
      return [];
    }
    return Object.entries(options.vpcServices).map(
      ([name, { service_id, remoteProxyConnectionString }]) => {
        return {
          name,
          service: {
            name: getUserBindingServiceName(
              VPC_SERVICES_PLUGIN_NAME,
              service_id,
              remoteProxyConnectionString
            )
          }
        };
      }
    );
  },
  getNodeBindings(options) {
    if (!options.vpcServices) {
      return {};
    }
    return Object.fromEntries(
      Object.keys(options.vpcServices).map((name) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    if (!options.vpcServices) {
      return [];
    }
    return Object.entries(options.vpcServices).map(
      ([name, { service_id, remoteProxyConnectionString }]) => {
        return {
          name: getUserBindingServiceName(
            VPC_SERVICES_PLUGIN_NAME,
            service_id,
            remoteProxyConnectionString
          ),
          worker: remoteProxyClientWorker(remoteProxyConnectionString, name)
        };
      }
    );
  }
};

// src/plugins/worker-loader/index.ts
var WorkerLoaderConfigSchema = external_exports.object({});
var WorkerLoaderOptionsSchema = external_exports.object({
  workerLoaders: external_exports.record(WorkerLoaderConfigSchema).optional()
});
var WORKER_LOADER_PLUGIN_NAME = "worker-loader";
var WORKER_LOADER_PLUGIN = {
  options: WorkerLoaderOptionsSchema,
  getBindings(options) {
    if (!options.workerLoaders) {
      return [];
    }
    const bindings = Object.entries(options.workerLoaders).map(
      ([name]) => ({
        name,
        workerLoader: {}
      })
    );
    return bindings;
  },
  getNodeBindings() {
    return {};
  },
  async getServices() {
    return [];
  }
};

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

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

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

// src/plugins/workflows/index.ts
var WorkflowsOptionsSchema = external_exports.object({
  workflows: external_exports.record(
    external_exports.object({
      name: external_exports.string(),
      className: external_exports.string(),
      scriptName: external_exports.string().optional(),
      remoteProxyConnectionString: external_exports.custom().optional(),
      stepLimit: external_exports.number().int().min(1).optional()
    })
  ).optional()
});
var WorkflowsSharedOptionsSchema = external_exports.object({
  workflowsPersist: PersistenceSchema
});
var WORKFLOWS_PLUGIN_NAME = "workflows";
var WORKFLOWS_STORAGE_SERVICE_NAME = `${WORKFLOWS_PLUGIN_NAME}:storage`;
var WORKFLOWS_PLUGIN = {
  options: WorkflowsOptionsSchema,
  sharedOptions: WorkflowsSharedOptionsSchema,
  async getBindings(options) {
    return Object.entries(options.workflows ?? {}).map(
      ([bindingName, workflow]) => ({
        name: bindingName,
        wrapped: {
          moduleName: `${WORKFLOWS_PLUGIN_NAME}:local-wrapped-binding`,
          innerBindings: [
            {
              name: "binding",
              service: {
                name: getUserBindingServiceName(
                  WORKFLOWS_PLUGIN_NAME,
                  workflow.name,
                  workflow.remoteProxyConnectionString
                ),
                entrypoint: "WorkflowBinding"
              }
            }
          ]
        }
      })
    );
  },
  async getNodeBindings(options) {
    return Object.fromEntries(
      Object.keys(options.workflows ?? {}).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, sharedOptions, tmpPath, defaultPersistRoot }) {
    const persistPath = getPersistPath(
      WORKFLOWS_PLUGIN_NAME,
      tmpPath,
      defaultPersistRoot,
      sharedOptions.workflowsPersist
    );
    await import_promises18.default.mkdir(persistPath, { recursive: true });
    const storageServices = Object.entries(
      options.workflows ?? {}
    ).map(([_2, workflow]) => ({
      name: `${WORKFLOWS_STORAGE_SERVICE_NAME}-${workflow.name}`,
      disk: { path: persistPath, writable: true }
    }));
    const services = Object.entries(options.workflows ?? {}).map(
      ([bindingName, workflow]) => {
        const uniqueKey = `miniflare-workflows-${workflow.name}`;
        const workflowsBinding = {
          name: getUserBindingServiceName(
            WORKFLOWS_PLUGIN_NAME,
            workflow.name,
            workflow.remoteProxyConnectionString
          ),
          worker: {
            compatibilityDate: "2024-10-22",
            modules: [
              {
                name: "workflows.mjs",
                esModule: binding_worker_default5()
              }
            ],
            durableObjectNamespaces: [
              {
                className: "Engine",
                enableSql: true,
                uniqueKey,
                preventEviction: true
              }
            ],
            durableObjectStorage: {
              localDisk: `${WORKFLOWS_STORAGE_SERVICE_NAME}-${workflow.name}`
            },
            bindings: [
              {
                name: "ENGINE",
                durableObjectNamespace: { className: "Engine" }
              },
              {
                name: "USER_WORKFLOW",
                service: {
                  name: getUserServiceName(workflow.scriptName),
                  entrypoint: workflow.className
                }
              },
              {
                name: "BINDING_NAME",
                json: JSON.stringify(bindingName)
              },
              ...workflow.stepLimit !== void 0 ? [
                {
                  name: "STEP_LIMIT",
                  json: JSON.stringify(workflow.stepLimit)
                }
              ] : []
            ]
          }
        };
        return workflowsBinding;
      }
    );
    if (services.length === 0) {
      return [];
    }
    return [...storageServices, ...services];
  },
  getPersistPath({ workflowsPersist }, tmpPath) {
    return getPersistPath(
      WORKFLOWS_PLUGIN_NAME,
      tmpPath,
      void 0,
      workflowsPersist
    );
  }
};

// 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,
  [AI_SEARCH_PLUGIN_NAME]: AI_SEARCH_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,
  [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/core/inspector-proxy/inspector-proxy-controller.ts
var import_node_crypto6 = __toESM(require("node:crypto"));
var import_node_http = require("node:http");
var import_ws4 = __toESM(require("ws"));

// package.json
var version2 = "4.20260410.0";

// src/plugins/core/inspector-proxy/inspector-proxy.ts
var import_node_assert21 = __toESM(require("node:assert"));
var import_ws3 = __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_assert21.default)(this.#devtoolsWs?.readyState === import_ws3.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", (data2) => {
      const message = JSON.parse(data2.toString());
      (0, import_node_assert21.default)(this.#runtimeWs?.OPEN);
      this.#sendMessageToRuntime(message);
    });
  }
  #runtimeMessageCounter = 1e8;
  #nextCounter() {
    return ++this.#runtimeMessageCounter;
  }
  #runtimeKeepAliveInterval;
  #handleRuntimeWebSocketOpen() {
    (0, import_node_assert21.default)(this.#runtimeWs?.OPEN);
    this.#runtimeWs.on("message", (data2) => {
      const message = JSON.parse(data2.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 url38 = new URL(message.params.sourceMapURL, message.params.url);
      if (url38.protocol === "file:") {
        message.params.sourceMapURL = url38.href.replace(
          "file:",
          "wrangler-file:"
        );
      }
    }
    return this.#sendMessageToDevtools(message);
  }
  #sendMessageToDevtools(message) {
    (0, import_node_assert21.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_assert21.default)(this.#runtimeWs?.OPEN);
    this.#runtimeWs.send(JSON.stringify(message));
  }
  async dispose() {
    clearInterval(this.#runtimeKeepAliveInterval);
    this.#devtoolsWs?.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();
  }
  #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((resolve6, reject) => {
      server.once("error", reject);
      server.listen(
        this.inspectorPortOption,
        this.inspectorHostOption,
        resolve6
      );
    });
  }
  async #closeServer(server) {
    server.closeAllConnections();
    return await new Promise((resolve6) => {
      server.close((err) => {
        if (err) {
          this.log.error(err);
        }
        resolve6();
      });
    });
  }
  #initializeWebSocketServer(server) {
    const devtoolsWebSocketServer = new import_ws4.WebSocketServer({ server });
    devtoolsWebSocketServer.on("connection", (devtoolsWs, upgradeRequest) => {
      const validationError = this.#validateDevToolsWebSocketUpgradeRequest(upgradeRequest);
      if (validationError !== null) {
        devtoolsWs.close();
        return;
      }
      const proxy = this.#proxies.find(
        ({ path: path62 }) => upgradeRequest.url === path62
      );
      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_crypto6.default.randomUUID();
  async #handleDevToolsJsonRequest(host, path62) {
    if (path62 === "/json/version") {
      return {
        Browser: `miniflare/v${version2}`,
        // TODO: (someday): The DevTools protocol should match that of workerd.
        // This could be exposed by the preview API.
        "Protocol-Version": "1.3"
      };
    }
    if (path62 === "/json" || path62 === "/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());
    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_ws4.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;
    return new Promise((resolve6, reject) => {
      server.close((err) => err ? reject(err) : resolve6());
    });
  }
};
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/hyperdrive/hyperdrive-proxy.ts
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
]);
var HyperdriveProxyController = class {
  // Map hyperdrive binding name to proxy server
  #servers = /* @__PURE__ */ new Map();
  /**
   * 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(config) {
    const { name, targetHost, targetPort, scheme, sslmode } = config;
    const server = import_node_net.default.createServer((clientSocket) => {
      this.#handleConnection(
        clientSocket,
        targetHost,
        Number.parseInt(targetPort),
        scheme,
        sslmode
      );
    });
    const port = await new Promise((resolve6, reject) => {
      server.listen(0, "127.0.0.1", () => {
        const address = server.address();
        if (address && typeof address !== "string") {
          resolve6(address.port);
        } else {
          reject("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.
   */
  async #handleConnection(clientSocket, targetHost, targetPort, scheme, sslmode) {
    const dbSocket = import_node_net.default.connect({ host: targetHost, port: targetPort });
    const sslmodeRequire = sslmode === "require";
    const sslmodePrefer = sslmode === "prefer";
    if (sslmodePrefer || sslmodeRequire) {
      try {
        if (scheme === schemes.postgres || scheme === schemes.postgresql) {
          return await handlePostgresTlsConnection(
            dbSocket,
            clientSocket,
            targetHost,
            targetPort,
            sslmodeRequire
          );
        } else if (scheme === schemes.mysql) {
          return await handleMySQLTlsConnection(
            dbSocket,
            clientSocket,
            targetHost,
            targetPort,
            sslmodeRequire
          );
        }
      } catch (e) {
        if (sslmodeRequire) {
          clientSocket.write(`${e}
`);
          clientSocket.end();
          dbSocket.destroy();
          return;
        }
      }
    }
    clientSocket.pipe(dbSocket);
    dbSocket.pipe(clientSocket);
  }
  /** Disposes of the proxy servers when shutting down the worker.*/
  async dispose() {
    await Promise.allSettled(
      Array.from(this.#servers.values()).map((server) => {
        new Promise((resolve6, reject) => {
          server.close((err) => err ? reject(err) : resolve6());
        });
      })
    );
    this.#servers.clear();
  }
};
async function handlePostgresTlsConnection(dbSocket, clientSocket, targetHost, targetPort, sslmodeRequire) {
  await writeAsync(dbSocket, POSTGRES_SSL_REQUEST_PACKET);
  const response = await readAsync(dbSocket);
  const sslResponseFlag = response.toString("utf8", 0, 1);
  if (sslResponseFlag === "S") {
    const tlsOptions = {
      socket: dbSocket,
      host: targetHost,
      servername: targetHost,
      rejectUnauthorized: false
    };
    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) {
  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 = {
      socket: dbSocket,
      host: targetHost,
      servername: targetHost,
      minVersion: "TLSv1.2",
      rejectUnauthorized: false
    };
    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((resolve6, reject) => {
    const handleConnect = () => {
      dbSocket.off("error", handleError);
      resolve6();
    };
    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((resolve6, reject) => {
    const buffer = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
    socket.write(buffer, (err) => err ? reject(err) : resolve6());
  });
}
function readAsync(socket) {
  return new Promise((resolve6, reject) => {
    const handleData = (data2) => {
      socket.off("error", handleError);
      resolve6(data2);
    };
    const handleError = (err) => {
      socket.off("data", handleData);
      reject(err);
    };
    socket.once("data", handleData);
    socket.once("error", handleError);
  });
}
function tlsConnect(options) {
  return new Promise((resolve6, reject) => {
    const socket = import_node_tls2.default.connect(options);
    const handleSecureConnect = () => {
      socket.off("error", handleError);
      resolve6(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 offset2 = 1;
  while (offset2 < payloadLength && payload[offset2] != 0) offset2++;
  offset2++;
  offset2 += MYSQL_CONNECTION_ID_LENGTH;
  offset2 += MYSQL_AUTH_PLUGIN_DATA_PART_1_LENGTH;
  offset2 += MYSQL_FILLER_LENGTH;
  if (offset2 + MYSQL_CAPABILITY_FLAGS_LOWER_LENGTH > payloadLength)
    return false;
  const caps = payload[offset2] | payload[offset2 + 1] << 8;
  return (caps & MYSQL_SSL_CAPABILITY_FLAG) != 0;
}

// src/plugins/images/fetcher.ts
var import_node_buffer5 = require("node:buffer");
function validateTransforms(inputTransforms) {
  if (!Array.isArray(inputTransforms)) {
    return null;
  }
  for (const transform of inputTransforms) {
    for (const key of ["imageIndex", "rotate", "width", "height"]) {
      if (transform[key] !== void 0 && typeof transform[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 data2 = await request4.formData();
  const body = data2.get("image");
  if (!body || !(body instanceof import_node_buffer5.File)) {
    return errorResponse(
      400,
      9523,
      `ERROR: Internal Images binding error: expected image in request, got ${body}`
    );
  }
  const transformer = sharp(await body.arrayBuffer(), {});
  const url38 = new URL(request4.url);
  if (url38.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 = data2.get("transforms");
      if (typeof transformsJson !== "string") {
        return badTransformsResponse;
      }
      const transforms = validateTransforms(JSON.parse(transformsJson));
      if (transforms === null) {
        return badTransformsResponse;
      }
      const outputFormat = data2.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;
    case "avif":
      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 Response.json(resp);
}
async function runTransform(transformer, transforms, outputFormat) {
  for (const transform of transforms) {
    if (transform.imageIndex !== void 0 && transform.imageIndex !== 0) {
      continue;
    }
    if (transform.rotate !== void 0) {
      transformer.rotate(transform.rotate);
    }
    if (transform.width !== void 0 || transform.height !== void 0) {
      transformer.resize(transform.width || null, transform.height || null, {
        fit: "contain"
      });
    }
  }
  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;
  }
  return new Response(transformer, {
    headers: {
      "content-type": outputFormat
    }
  });
}
function errorResponse(status2, code, message) {
  return new Response(`ERROR ${code}: ${message}`, {
    status: status2,
    headers: {
      "content-type": "text/plain",
      "cf-images-binding": `err=${code}`
    }
  });
}

// src/shared/dev-registry.ts
var import_node_fs16 = require("node:fs");
var import_node_path24 = __toESM(require("node:path"));
var import_node_worker_threads2 = require("node:worker_threads");

// ../../node_modules/.pnpm/chokidar@4.0.1/node_modules/chokidar/esm/index.js
var import_fs40 = require("fs");
var import_promises21 = 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_fs38 = require("fs");
var import_promises19 = require("fs/promises");
var import_stream2 = require("stream");
var import_path38 = require("path");
function defaultOptions2() {
  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 = (error) => NORMAL_FLOW_ERRORS.has(error.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_stream2.Readable {
  constructor(options = {}) {
    super({
      objectMode: true,
      autoDestroy: true,
      highWaterMark: options.highWaterMark
    });
    const opts = { ...defaultOptions2(), ...options };
    const { root, type } = opts;
    this._fileFilter = normalizeFilter(opts.fileFilter);
    this._directoryFilter = normalizeFilter(opts.directoryFilter);
    const statMethod = opts.lstat ? import_fs38.lstatSync : import_fs38.statSync;
    if (wantBigintFsStats) {
      this._stat = (path62) => statMethod(path62, { 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_path38.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: path62, depth } = par;
          const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path62));
          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 (error) {
      this.destroy(error);
    } finally {
      this.reading = false;
    }
  }
  async _exploreDir(path62, depth) {
    let files;
    try {
      files = await (0, import_promises19.readdir)(path62, this._rdOptions);
    } catch (error) {
      this._onError(error);
    }
    return { files, depth, path: path62 };
  }
  _formatEntry(dirent, path62) {
    let entry;
    const basename3 = this._isDirent ? dirent.name : dirent;
    try {
      const fullPath = (0, import_path38.resolve)((0, import_path38.join)(path62, basename3));
      entry = { path: (0, import_path38.relative)(this._root, fullPath), fullPath, basename: basename3 };
      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_promises19.realpath)(full);
        const entryRealPathStats = (0, import_fs38.lstatSync)(entryRealPath);
        if (entryRealPathStats.isFile()) {
          return "file";
        }
        if (entryRealPathStats.isDirectory()) {
          const len = entryRealPath.length;
          if (full.startsWith(entryRealPath) && full.substr(len, 1) === import_path38.sep) {
            const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
            recursiveError.code = RECURSIVE_ERROR_CODE;
            return this._onError(recursiveError);
          }
          return "directory";
        }
      } catch (error) {
        this._onError(error);
        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_fs39 = require("fs");
var import_promises20 = 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 isWindows = 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_promises20.lstat, stat: import_promises20.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 set = cont[key];
  if (set instanceof Set) {
    set.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(path62, options, listener, errHandler, emitRaw) {
  const handleEvent = (rawEvent, evPath) => {
    listener(path62);
    emitRaw(rawEvent, evPath, { watchedPath: path62 });
    if (evPath && path62 !== evPath) {
      fsWatchBroadcast(sysPath.resolve(path62, evPath), KEY_LISTENERS, sysPath.join(path62, evPath));
    }
  };
  try {
    return (0, import_fs39.watch)(path62, {
      persistent: options.persistent
    }, handleEvent);
  } catch (error) {
    errHandler(error);
    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 = (path62, fullPath, options, handlers) => {
  const { listener, errHandler, rawEmitter } = handlers;
  let cont = FsWatchInstances.get(fullPath);
  let watcher;
  if (!options.persistent) {
    watcher = createFsWatchInstance(path62, 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(
      path62,
      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 (error) => {
      const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
      if (cont)
        cont.watcherUnusable = true;
      if (isWindows && error.code === "EPERM") {
        try {
          const fd = await (0, import_promises20.open)(path62, "r");
          await fd.close();
          broadcastErr(error);
        } catch (err) {
        }
      } else {
        broadcastErr(error);
      }
    });
    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 = (path62, 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_fs39.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_fs39.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(path62, 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_fs39.unwatchFile)(fullPath);
      cont.options = cont.watcher = void 0;
      Object.freeze(cont);
    }
  };
};
var NodeFsHandler = class {
  constructor(fsW) {
    this.fsw = fsW;
    this._boundHandleError = (error) => fsW._handleError(error);
  }
  /**
   * 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(path62, listener) {
    const opts = this.fsw.options;
    const directory = sysPath.dirname(path62);
    const basename3 = sysPath.basename(path62);
    const parent = this.fsw._getWatchedDir(directory);
    parent.add(basename3);
    const absolutePath = sysPath.resolve(path62);
    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(basename3) ? opts.binaryInterval : opts.interval;
      closer = setFsWatchFileListener(path62, absolutePath, options, {
        listener,
        rawEmitter: this.fsw._emitRaw
      });
    } else {
      closer = setFsWatchListener(path62, 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(file2, stats, initialAdd) {
    if (this.fsw.closed) {
      return;
    }
    const dirname4 = sysPath.dirname(file2);
    const basename3 = sysPath.basename(file2);
    const parent = this.fsw._getWatchedDir(dirname4);
    let prevStats = stats;
    if (parent.has(basename3))
      return;
    const listener = async (path62, newStats) => {
      if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file2, 5))
        return;
      if (!newStats || newStats.mtimeMs === 0) {
        try {
          const newStats2 = await (0, import_promises20.stat)(file2);
          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, file2, newStats2);
          }
          if ((isMacos || isLinux) && prevStats.ino !== newStats2.ino) {
            this.fsw._closeFile(path62);
            prevStats = newStats2;
            const closer2 = this._watchWithNodeFs(file2, listener);
            if (closer2)
              this.fsw._addPathCloser(path62, closer2);
          } else {
            prevStats = newStats2;
          }
        } catch (error) {
          this.fsw._remove(dirname4, basename3);
        }
      } else if (parent.has(basename3)) {
        const at2 = newStats.atimeMs;
        const mt = newStats.mtimeMs;
        if (!at2 || at2 <= mt || mt !== prevStats.mtimeMs) {
          this.fsw._emit(EV.CHANGE, file2, newStats);
        }
        prevStats = newStats;
      }
    };
    const closer = this._watchWithNodeFs(file2, listener);
    if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file2)) {
      if (!this.fsw._throttle(EV.ADD, file2, 0))
        return;
      this.fsw._emit(EV.ADD, file2, 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, path62, item) {
    if (this.fsw.closed) {
      return;
    }
    const full = entry.fullPath;
    const dir = this.fsw._getWatchedDir(directory);
    if (!this.fsw.options.followSymlinks) {
      this.fsw._incrReadyCount();
      let linkPath;
      try {
        linkPath = await (0, import_promises20.realpath)(path62);
      } catch (e) {
        this.fsw._emitReady();
        return true;
      }
      if (this.fsw.closed)
        return;
      if (dir.has(item)) {
        if (this.fsw._symlinkPaths.get(full) !== linkPath) {
          this.fsw._symlinkPaths.set(full, linkPath);
          this.fsw._emit(EV.CHANGE, path62, entry.stats);
        }
      } else {
        dir.add(item);
        this.fsw._symlinkPaths.set(full, linkPath);
        this.fsw._emit(EV.ADD, path62, 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, dir, depth, throttler) {
    directory = sysPath.join(directory, "");
    throttler = this.fsw._throttle("readdir", directory, 1e3);
    if (!throttler)
      return;
    const previous = this.fsw._getWatchedDir(wh.path);
    const current2 = /* @__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 path62 = sysPath.join(directory, item);
      current2.add(item);
      if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path62, item)) {
        return;
      }
      if (this.fsw.closed) {
        stream = void 0;
        return;
      }
      if (item === target || !target && !previous.has(item)) {
        this.fsw._incrReadyCount();
        path62 = sysPath.join(dir, sysPath.relative(dir, path62));
        this._addToNodeFs(path62, initialAdd, wh, depth + 1);
      }
    }).on(EV.ERROR, this._boundHandleError);
    return new Promise((resolve6, reject) => {
      if (!stream)
        return reject();
      stream.once(STR_END, () => {
        if (this.fsw.closed) {
          stream = void 0;
          return;
        }
        const wasThrottled = throttler ? throttler.clear() : false;
        resolve6(void 0);
        previous.getChildren().filter((item) => {
          return item !== directory && !current2.has(item);
        }).forEach((item) => {
          this.fsw._remove(directory, item);
        });
        stream = void 0;
        if (wasThrottled)
          this._handleRead(directory, false, wh, target, dir, 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(dir, stats, initialAdd, depth, target, wh, realpath2) {
    const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
    const tracked = parentDir.has(sysPath.basename(dir));
    if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
      this.fsw._emit(EV.ADD_DIR, dir, stats);
    }
    parentDir.add(sysPath.basename(dir));
    this.fsw._getWatchedDir(dir);
    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(dir, initialAdd, wh, target, dir, depth, throttler);
        if (this.fsw.closed)
          return;
      }
      closer = this._watchWithNodeFs(dir, (dirPath, stats2) => {
        if (stats2 && stats2.mtimeMs === 0)
          return;
        this._handleRead(dirPath, false, wh, target, dir, 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(path62, initialAdd, priorWh, depth, target) {
    const ready = this.fsw._emitReady;
    if (this.fsw._isIgnored(path62) || this.fsw.closed) {
      ready();
      return false;
    }
    const wh = this.fsw._getWatchHelpers(path62);
    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(path62);
        const targetPath = follow ? await (0, import_promises20.realpath)(path62) : path62;
        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_promises20.realpath)(path62) : path62;
        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, path62, wh, targetPath);
        if (this.fsw.closed)
          return;
        if (targetPath !== void 0) {
          this.fsw._symlinkPaths.set(sysPath.resolve(path62), targetPath);
        }
      } else {
        closer = this._handleFile(wh.watchPath, stats, initialAdd);
      }
      ready();
      if (closer)
        this.fsw._addPathCloser(path62, closer);
      return false;
    } catch (error) {
      if (this.fsw._handleError(error)) {
        ready();
        return path62;
      }
    }
  }
};

// ../../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 (string) => matcher === string;
  if (matcher instanceof RegExp)
    return (string) => matcher.test(string);
  if (typeof matcher === "object" && matcher !== null) {
    return (string) => {
      if (matcher.path === string)
        return true;
      if (matcher.recursive) {
        const relative4 = sysPath2.relative(matcher.path, string);
        if (!relative4) {
          return false;
        }
        return !relative4.startsWith("..") && !sysPath2.isAbsolute(relative4);
      }
      return false;
    };
  }
  return () => false;
}
function normalizePath(path62) {
  if (typeof path62 !== "string")
    throw new Error("string expected");
  path62 = sysPath2.normalize(path62);
  path62 = path62.replace(/\\/g, "/");
  let prepend = false;
  if (path62.startsWith("//"))
    prepend = true;
  const DOUBLE_SLASH_RE2 = /\/\//;
  while (path62.match(DOUBLE_SLASH_RE2))
    path62 = path62.replace(DOUBLE_SLASH_RE2, "/");
  if (prepend)
    path62 = "/" + path62;
  return path62;
}
function matchPatterns(patterns, testString, stats) {
  const path62 = normalizePath(testString);
  for (let index = 0; index < patterns.length; index++) {
    const pattern = patterns[index];
    if (pattern(path62, 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((p) => typeof p === STRING_TYPE)) {
    throw new TypeError(`Non-string provided as watch path: ${paths}`);
  }
  return paths.map(normalizePathToUnix);
};
var toUnix = (string) => {
  let str = string.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 = (path62) => toUnix(sysPath2.normalize(toUnix(path62)));
var normalizeIgnored = (cwd2 = "") => (path62) => {
  if (typeof path62 === "string") {
    return normalizePathToUnix(sysPath2.isAbsolute(path62) ? path62 : sysPath2.join(cwd2, path62));
  } else {
    return path62;
  }
};
var getAbsolutePath = (path62, cwd2) => {
  if (sysPath2.isAbsolute(path62)) {
    return path62;
  }
  return sysPath2.join(cwd2, path62);
};
var EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
var DirEntry = class {
  constructor(dir, removeWatcher) {
    this.path = dir;
    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 dir = this.path;
    try {
      await (0, import_promises21.readdir)(dir);
    } catch (err) {
      if (this._removeWatcher) {
        this._removeWatcher(sysPath2.dirname(dir), sysPath2.basename(dir));
      }
    }
  }
  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(path62, follow, fsw) {
    this.fsw = fsw;
    const watchPath = path62;
    this.path = path62 = path62.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((path62) => {
        const absPath = getAbsolutePath(path62, cwd2);
        return absPath;
      });
    }
    paths.forEach((path62) => {
      this._removeIgnoredPath(path62);
    });
    this._userIgnored = void 0;
    if (!this._readyCount)
      this._readyCount = 0;
    this._readyCount += paths.length;
    Promise.all(paths.map(async (path62) => {
      const res = await this._nodeFsHandler._addToNodeFs(path62, !_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((path62) => {
      if (!sysPath2.isAbsolute(path62) && !this._closers.has(path62)) {
        if (cwd2)
          path62 = sysPath2.join(cwd2, path62);
        path62 = sysPath2.resolve(path62);
      }
      this._closePath(path62);
      this._addIgnoredPath(path62);
      if (this._watched.has(path62)) {
        this._addIgnoredPath({
          path: path62,
          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 promise = closer();
      if (promise instanceof Promise)
        closers.push(promise);
    }));
    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, dir) => {
      const key = this.options.cwd ? sysPath2.relative(this.options.cwd, dir) : dir;
      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, path62, stats) {
    if (this.closed)
      return;
    const opts = this.options;
    if (isWindows)
      path62 = sysPath2.normalize(path62);
    if (opts.cwd)
      path62 = sysPath2.relative(opts.cwd, path62);
    const args = [event, path62];
    if (stats != null)
      args.push(stats);
    const awf = opts.awaitWriteFinish;
    let pw;
    if (awf && (pw = this._pendingWrites.get(path62))) {
      pw.lastChange = /* @__PURE__ */ new Date();
      return this;
    }
    if (opts.atomic) {
      if (event === EVENTS.UNLINK) {
        this._pendingUnlinks.set(path62, args);
        setTimeout(() => {
          this._pendingUnlinks.forEach((entry, path63) => {
            this.emit(...entry);
            this.emit(EVENTS.ALL, ...entry);
            this._pendingUnlinks.delete(path63);
          });
        }, typeof opts.atomic === "number" ? opts.atomic : 100);
        return this;
      }
      if (event === EVENTS.ADD && this._pendingUnlinks.has(path62)) {
        event = args[0] = EVENTS.CHANGE;
        this._pendingUnlinks.delete(path62);
      }
    }
    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(path62, awf.stabilityThreshold, event, awfEmit);
      return this;
    }
    if (event === EVENTS.CHANGE) {
      const isThrottled = !this._throttle(EVENTS.CHANGE, path62, 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, path62) : path62;
      let stats2;
      try {
        stats2 = await (0, import_promises21.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(error) {
    const code = error && error.code;
    if (error && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) {
      this.emit(EVENTS.ERROR, error);
    }
    return error || 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, path62, 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(path62);
    if (actionPath) {
      actionPath.count++;
      return false;
    }
    let timeoutObject;
    const clear = () => {
      const item = action.get(path62);
      const count = item ? item.count : 0;
      action.delete(path62);
      clearTimeout(timeoutObject);
      if (item)
        clearTimeout(item.timeoutObject);
      return count;
    };
    timeoutObject = setTimeout(clear, timeout);
    const thr = { timeoutObject, clear, count: 0 };
    action.set(path62, 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(path62, threshold, event, awfEmit) {
    const awf = this.options.awaitWriteFinish;
    if (typeof awf !== "object")
      return;
    const pollInterval = awf.pollInterval;
    let timeoutHandler;
    let fullPath = path62;
    if (this.options.cwd && !sysPath2.isAbsolute(path62)) {
      fullPath = sysPath2.join(this.options.cwd, path62);
    }
    const now = /* @__PURE__ */ new Date();
    const writes = this._pendingWrites;
    function awaitWriteFinishFn(prevStat) {
      (0, import_fs40.stat)(fullPath, (err, curStat) => {
        if (err || !writes.has(path62)) {
          if (err && err.code !== "ENOENT")
            awfEmit(err);
          return;
        }
        const now2 = Number(/* @__PURE__ */ new Date());
        if (prevStat && curStat.size !== prevStat.size) {
          writes.get(path62).lastChange = now2;
        }
        const pw = writes.get(path62);
        const df = now2 - pw.lastChange;
        if (df >= threshold) {
          writes.delete(path62);
          awfEmit(void 0, curStat);
        } else {
          timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
        }
      });
    }
    if (!writes.has(path62)) {
      writes.set(path62, {
        lastChange: now,
        cancelWait: () => {
          writes.delete(path62);
          clearTimeout(timeoutHandler);
          return event;
        }
      });
      timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
    }
  }
  /**
   * Determines whether user has asked to ignore this path.
   */
  _isIgnored(path62, stats) {
    if (this.options.atomic && DOT_RE.test(path62))
      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(path62, stats);
  }
  _isntIgnored(path62, stat4) {
    return !this._isIgnored(path62, stat4);
  }
  /**
   * Provides a set of common helpers and properties relating to symlink handling.
   * @param path file or directory pattern being watched
   */
  _getWatchHelpers(path62) {
    return new WatchHelper(path62, this.options.followSymlinks, this);
  }
  // Directory helpers
  // -----------------
  /**
   * Provides directory tracking objects
   * @param directory path of the directory
   */
  _getWatchedDir(directory) {
    const dir = sysPath2.resolve(directory);
    if (!this._watched.has(dir))
      this._watched.set(dir, new DirEntry(dir, this._boundRemove));
    return this._watched.get(dir);
  }
  // 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, isDirectory3) {
    const path62 = sysPath2.join(directory, item);
    const fullPath = sysPath2.resolve(path62);
    isDirectory3 = isDirectory3 != null ? isDirectory3 : this._watched.has(path62) || this._watched.has(fullPath);
    if (!this._throttle("remove", path62, 100))
      return;
    if (!isDirectory3 && this._watched.size === 1) {
      this.add(directory, item, true);
    }
    const wp = this._getWatchedDir(path62);
    const nestedDirectoryChildren = wp.getChildren();
    nestedDirectoryChildren.forEach((nested) => this._remove(path62, 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 = path62;
    if (this.options.cwd)
      relPath = sysPath2.relative(this.options.cwd, path62);
    if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
      const event = this._pendingWrites.get(relPath).cancelWait();
      if (event === EVENTS.ADD)
        return;
    }
    this._watched.delete(path62);
    this._watched.delete(fullPath);
    const eventName = isDirectory3 ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
    if (wasTracked && !this._isIgnored(path62))
      this._emit(eventName, path62);
    this._closePath(path62);
  }
  /**
   * Closes all watchers for a path
   */
  _closePath(path62) {
    this._closeFile(path62);
    const dir = sysPath2.dirname(path62);
    this._getWatchedDir(dir).remove(sysPath2.basename(path62));
  }
  /**
   * Closes only file-specific watchers
   */
  _closeFile(path62) {
    const closers = this._closers.get(path62);
    if (!closers)
      return;
    closers.forEach((closer) => closer());
    this._closers.delete(path62);
  }
  _addPathCloser(path62, closer) {
    if (!closer)
      return;
    let list = this._closers.get(path62);
    if (!list) {
      list = [];
      this._closers.set(path62, 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, enableDurableObjectProxy, onUpdate, log2) {
    this.registryPath = registryPath;
    this.enableDurableObjectProxy = enableDurableObjectProxy;
    this.onUpdate = onUpdate;
    this.log = log2;
  }
  heartbeats = /* @__PURE__ */ new Map();
  registry = {};
  registeredWorkers = /* @__PURE__ */ new Set();
  externalServices = /* @__PURE__ */ new Map();
  watcher;
  proxyWorker;
  proxyAddress;
  /**
   * Watch files inside the registry directory for changes.
   */
  watch(services) {
    if (services.size === 0 || !this.registryPath) {
      return;
    }
    this.externalServices = new Map(services);
    if (!this.watcher) {
      this.watcher = watch(this.registryPath).on("all", () => this.refresh());
      this.refresh();
    }
  }
  /**
   * Initialize the worker thread proxy server
   */
  async initializeProxyWorker() {
    if (!this.isEnabled()) {
      return null;
    }
    if (this.proxyAddress !== void 0) {
      this.log.debug("Dev registry proxy is already running");
      return this.proxyAddress;
    }
    const worker = new import_node_worker_threads2.Worker(
      import_node_path24.default.join(__dirname, "shared", "dev-registry.worker.js")
    );
    const address = await new Promise((resolve6, reject) => {
      worker.once("message", (message) => {
        if (message.type === "ready") {
          resolve6(message.address);
        } else if (message.type === "error") {
          reject(new Error(message.error));
        }
      });
      worker.once("error", reject);
    });
    this.proxyWorker = worker;
    this.proxyAddress = address;
    this.log.debug(`Dev registry proxy started on http://${address}`);
    return address;
  }
  /**
   * 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();
    this.registry = {};
    return Promise.all([this.watcher?.close(), this.proxyWorker?.terminate()]).then(() => {
      return;
    }).finally(() => {
      this.watcher = void 0;
      this.proxyWorker = void 0;
      this.proxyAddress = void 0;
    });
  }
  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_fs16.unlinkSync)(import_node_path24.default.join(this.registryPath, name));
      }
    } catch (e) {
      this.log?.debug(`Failed to unregister worker "${name}": ${e}`);
    }
  }
  isEnabled() {
    return this.registryPath !== void 0 && this.registryPath !== "";
  }
  isDurableObjectProxyEnabled() {
    return this.isEnabled() && this.enableDurableObjectProxy;
  }
  getRegistryPath() {
    return this.registryPath;
  }
  async updateRegistryPath(registryPath, enableDurableObjectProxy, onUpdate) {
    this.unregisterWorkers();
    this.enableDurableObjectProxy = enableDurableObjectProxy;
    this.onUpdate = onUpdate;
    if (registryPath !== this.registryPath) {
      await this.watcher?.close();
      this.watcher = void 0;
      this.registryPath = registryPath;
    }
  }
  configureProxyWorker(runtimeEntryURL, socketPorts) {
    if (!this.proxyWorker) {
      return;
    }
    const fallbackServicePorts = {};
    for (const [service, { entrypoints }] of this.externalServices) {
      for (const entrypoint of entrypoints) {
        const port = socketPorts.get(
          getProxyFallbackServiceSocketName(service, entrypoint)
        );
        if (!port) {
          throw new Error(
            `There is no socket opened for "${service}" with the "${entrypoint ?? "default"}" entrypoint`
          );
        }
        fallbackServicePorts[service] ??= {};
        fallbackServicePorts[service][entrypoint ?? "default"] = port;
      }
    }
    this.proxyWorker.postMessage({
      type: "setup",
      runtimeEntryURL,
      fallbackServicePorts,
      logLevel: this.log.level
    });
  }
  register(workers) {
    if (!this.registryPath) {
      return;
    }
    (0, import_node_fs16.mkdirSync)(this.registryPath, { recursive: true });
    for (const [name, definition] of Object.entries(workers)) {
      const definitionPath = import_node_path24.default.join(this.registryPath, name);
      const existingHeartbeat = this.heartbeats.get(name);
      if (existingHeartbeat) {
        clearInterval(existingHeartbeat);
      }
      if (!this.enableDurableObjectProxy) {
        definition.durableObjects = [];
      }
      (0, import_node_fs16.writeFileSync)(definitionPath, JSON.stringify(definition, null, 2));
      this.registeredWorkers.add(name);
      this.heartbeats.set(
        name,
        setInterval(() => {
          if ((0, import_node_fs16.existsSync)(definitionPath)) {
            (0, import_node_fs16.utimesSync)(definitionPath, /* @__PURE__ */ new Date(), /* @__PURE__ */ new Date());
          }
        }, 3e4)
      );
    }
  }
  refresh() {
    if (!this.registryPath) {
      return;
    }
    const registry = getWorkerRegistry(this.registryPath, (workerName) => {
      this.unregister(workerName);
    });
    if (this.onUpdate) {
      for (const [service] of this.externalServices) {
        if (JSON.stringify(registry[service]) !== JSON.stringify(this.registry[service])) {
          this.onUpdate(JSON.parse(JSON.stringify(registry)));
          break;
        }
      }
    }
    if (this.proxyWorker) {
      this.proxyWorker.postMessage({
        type: "update",
        workers: registry
      });
    }
    this.registry = registry;
  }
};
function getWorkerRegistry(registryPath, unregisterStaleWorker) {
  const registry = {};
  if (!(0, import_node_fs16.existsSync)(registryPath)) {
    return registry;
  }
  for (const workerName of (0, import_node_fs16.readdirSync)(registryPath)) {
    try {
      const definitionPath = import_node_path24.default.join(registryPath, workerName);
      const stats = (0, import_node_fs16.statSync)(definitionPath, { throwIfNoEntry: false });
      if (stats === void 0 || stats.mtime.getTime() < Date.now() - 3e5) {
        unregisterStaleWorker?.(workerName);
        continue;
      }
      const file2 = (0, import_node_fs16.readFileSync)(definitionPath, {
        encoding: "utf8",
        flag: "r"
      });
      registry[workerName] = JSON.parse(file2);
    } catch {
    }
  }
  return registry;
}
function getDefaultDevRegistryPath() {
  return process.env.MINIFLARE_REGISTRY_PATH ?? import_node_path24.default.join(getGlobalWranglerConfigPath2(), "registry");
}

// 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/zod-format.ts
var import_node_assert22 = __toESM(require("node:assert"));
var import_node_util5 = __toESM(require("node:util"));
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;
}
function isRecord2(value) {
  return typeof value === "object" && value !== null;
}
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;
}
function issueEqual(a, b) {
  return a.message === b.message && arrayShallowEqual(a.path, b.path);
}
function hasMultipleDistinctMessages(issues, atDepth) {
  let firstIssue;
  for (const issue of issues) {
    if (issue.path.length < atDepth) continue;
    if (firstIssue === void 0) firstIssue = issue;
    else if (!issueEqual(firstIssue, issue)) return true;
  }
  return false;
}
function annotate(groupCounts, annotated, input, issue, path62, groupId) {
  if (path62.length === 0) {
    if (issue.code === "invalid_union") {
      const unionIssues = issue.unionErrors.flatMap(({ issues }) => issues);
      let newGroupId;
      const multipleDistinct = hasMultipleDistinctMessages(
        unionIssues,
        // For this check, we only include messages that are deeper than our
        // current level, so we don't include messages we'd ignore if we grouped
        issue.path.length + 1
      );
      if (isRecord2(input) && multipleDistinct) {
        newGroupId = groupCounts.size;
        groupCounts.set(newGroupId, 0);
      }
      for (const unionIssue of unionIssues) {
        const unionPath = unionIssue.path.slice(issue.path.length);
        if (multipleDistinct && unionPath.length === 0) continue;
        annotated = annotate(
          groupCounts,
          annotated,
          input,
          unionIssue,
          unionPath,
          newGroupId
        );
      }
      return annotated;
    }
    const message = issue.message;
    if (annotated !== void 0) {
      if (isAnnotation(annotated) && !annotated[kMessages].includes(message)) {
        annotated[kMessages].push(message);
      }
      return annotated;
    }
    if (groupId !== void 0) {
      const current2 = groupCounts.get(groupId);
      (0, import_node_assert22.default)(current2 !== void 0);
      groupCounts.set(groupId, current2 + 1);
    }
    return {
      [kMessages]: [message],
      [kActual]: input,
      [kGroupId]: groupId
    };
  }
  const [head, ...tail] = path62;
  (0, import_node_assert22.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_assert22.default)(isRecord2(annotated), "Expected object/array for nested issue");
  annotated[head] = annotate(
    groupCounts,
    annotated[head],
    input[head],
    issue,
    tail,
    groupId
  );
  return annotated;
}
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_util5.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_assert22.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((m2) => m2.split("\n")).map((line, i) => i > 0 ? messageIndent + line : line).join("\n");
    const error = messageColour(`${messagePrefix}${messageIndented}${groupOr}`);
    return `${indent}${dim2(prefix)}${actualIndented}${dim2(suffix)}
${error}`;
  } 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 "";
}
function formatZodError(error, input) {
  const sortedIssues = Array.from(error.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 issue of sortedIssues) {
    annotated = annotate(groupCounts, annotated, input, issue, issue.path);
  }
  const inspectOptions = {
    depth: 0,
    colors: $.enabled
  };
  return print(inspectOptions, groupCounts, annotated);
}

// src/merge.ts
var objectProtoNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
function isPlainObject(value) {
  const proto2 = Object.getPrototypeOf(value);
  return proto2 === Object.prototype || proto2 === null || Object.getOwnPropertyNames(proto2).sort().join("\0") === objectProtoNames;
}
function convertWorkerOptionsArrayToObject(key, array) {
  const _2 = array;
  if (key === "queueConsumers") {
    const object = Object.fromEntries(
      array.map((item) => [item, {}])
    );
    return object;
  } else {
    const object = Object.fromEntries(array.map((item) => [item, item]));
    return object;
  }
}
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 = isPlainObject(aValue);
    const bIsObject = isPlainObject(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/index.ts
var DEFAULT_HOST = "127.0.0.1";
function getURLSafeHost(host) {
  return import_node_net2.default.isIPv6(host) ? `[${host}]` : host;
}
function maybeGetLocallyAccessibleHost(h2) {
  if (h2 === "localhost") return "localhost";
  if (h2 === "127.0.0.1" || h2 === "*" || h2 === "0.0.0.0" || h2 === "::") {
    return "127.0.0.1";
  }
  if (h2 === "::1") return "[::1]";
}
function getServerPort(server) {
  const address = server.address();
  (0, import_node_assert23.default)(address !== null && typeof address === "object");
  return address.port;
}
function hasMultipleWorkers(opts) {
  return typeof opts === "object" && opts !== null && "workers" in opts && Array.isArray(opts.workers);
}
function getRootPath(opts) {
  if (typeof opts === "object" && opts !== null && "rootPath" in opts && typeof opts.rootPath === "string") {
    return opts.rootPath;
  } else {
    return "";
  }
}
function validateOptions(opts) {
  const sharedOpts = opts;
  const multipleWorkers = hasMultipleWorkers(opts);
  const workerOpts = multipleWorkers ? opts.workers : [opts];
  if (workerOpts.length === 0) {
    throw new MiniflareCoreError("ERR_NO_WORKERS", "No workers defined");
  }
  const pluginSharedOpts = {};
  const pluginWorkerOpts = Array.from(Array(workerOpts.length)).map(
    () => ({})
  );
  const sharedRootPath = multipleWorkers ? getRootPath(sharedOpts) : "";
  const workerRootPaths = workerOpts.map(
    (opts2) => import_node_path25.default.resolve(sharedRootPath, getRootPath(opts2))
  );
  try {
    for (const [key, plugin2] of PLUGIN_ENTRIES) {
      pluginSharedOpts[key] = plugin2.sharedOptions === void 0 ? void 0 : parseWithRootPath(sharedRootPath, plugin2.sharedOptions, sharedOpts);
      for (let i = 0; i < workerOpts.length; i++) {
        const optionsPath = multipleWorkers ? ["workers", i] : void 0;
        pluginWorkerOpts[i][key] = parseWithRootPath(
          workerRootPaths[i],
          plugin2.options,
          workerOpts[i],
          { path: optionsPath }
        );
      }
    }
  } catch (e) {
    if (e instanceof external_exports.ZodError) {
      let formatted;
      try {
        formatted = formatZodError(e, opts);
      } catch (formatError2) {
        const title = "[Miniflare] Validation Error Format Failure";
        const message = [
          "### Input",
          "```",
          import_node_util6.default.inspect(opts, { depth: null }),
          "```",
          "",
          "### Validation Error",
          "```",
          e.stack,
          "```",
          "",
          "### Format Error",
          "```",
          typeof formatError2 === "object" && formatError2 !== null && "stack" in formatError2 && typeof formatError2.stack === "string" ? formatError2.stack : String(formatError2),
          "```"
        ].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 error = new MiniflareCoreError(
        "ERR_VALIDATION",
        `Unexpected options passed to \`new Miniflare()\` constructor:
${formatted}`
      );
      Object.defineProperty(error, "cause", { get: () => e });
      throw error;
    }
    throw e;
  }
  const names = /* @__PURE__ */ new Set();
  for (const opts2 of pluginWorkerOpts) {
    const name = opts2.core.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 [pluginSharedOpts, pluginWorkerOpts];
}
function getDurableObjectClassNames(allWorkerOpts) {
  const serviceClassNames = /* @__PURE__ */ new Map();
  const allDurableObjects = allWorkerOpts.flatMap((workerOpts) => {
    const workerServiceName = getUserServiceName(workerOpts.core.name);
    return [
      ...Object.values(workerOpts.do.durableObjects ?? {}),
      ...workerOpts.do.additionalUnboundDurableObjects ?? []
    ].map((workerDODesignator) => {
      const doInfo = normaliseDurableObject(workerDODesignator);
      if (doInfo.serviceName === void 0) {
        doInfo.serviceName = workerServiceName;
      }
      return {
        doInfo,
        workerRawName: workerOpts.core.name
      };
    });
  }).sort(
    ({ doInfo, workerRawName }) => doInfo.scriptName === void 0 || doInfo.scriptName === workerRawName ? -1 : 0
  ).map(({ doInfo }) => doInfo);
  for (const doInfo of allDurableObjects) {
    const { className, serviceName, container, ...doConfigs } = doInfo;
    (0, import_node_assert23.default)(serviceName);
    let classNames = serviceClassNames.get(serviceName);
    if (classNames === void 0) {
      classNames = /* @__PURE__ */ new Map();
      serviceClassNames.set(serviceName, classNames);
    }
    if (classNames.has(className)) {
      const existingInfo = classNames.get(className);
      const isDoUnacceptableDiff = (field) => {
        if (!existingInfo) {
          return false;
        }
        const same = existingInfo[field] === doConfigs[field];
        if (same) {
          return false;
        }
        const oneIsUndefined = existingInfo[field] === void 0 || doConfigs[field] === void 0;
        if (oneIsUndefined) {
          return false;
        }
        return true;
      };
      if (isDoUnacceptableDiff("enableSql")) {
        throw new MiniflareCoreError(
          "ERR_DIFFERENT_STORAGE_BACKEND",
          `Different storage backends defined for Durable Object "${className}" in "${serviceName}": ${JSON.stringify(
            doConfigs.enableSql
          )} and ${JSON.stringify(existingInfo?.enableSql)}`
        );
      }
      if (isDoUnacceptableDiff("unsafeUniqueKey")) {
        throw new MiniflareCoreError(
          "ERR_DIFFERENT_UNIQUE_KEYS",
          `Multiple unsafe unique keys defined for Durable Object "${className}" in "${serviceName}": ${JSON.stringify(
            doConfigs.unsafeUniqueKey
          )} and ${JSON.stringify(existingInfo?.unsafeUniqueKey)}`
        );
      }
      if (isDoUnacceptableDiff("unsafePreventEviction")) {
        throw new MiniflareCoreError(
          "ERR_DIFFERENT_PREVENT_EVICTION",
          `Multiple unsafe prevent eviction values defined for Durable Object "${className}" in "${serviceName}": ${JSON.stringify(
            doConfigs.unsafePreventEviction
          )} and ${JSON.stringify(existingInfo?.unsafePreventEviction)}`
        );
      }
    } else {
      classNames.set(className, {
        enableSql: doConfigs.enableSql,
        unsafeUniqueKey: doConfigs.unsafeUniqueKey,
        unsafePreventEviction: doConfigs.unsafePreventEviction,
        container
      });
    }
  }
  return serviceClassNames;
}
function getExternalServiceEntrypoints(allWorkerOpts, proxyAddress) {
  const externalServices = /* @__PURE__ */ new Map();
  const allWorkerNames = allWorkerOpts.map((opts) => opts.core.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) {
    if (workerOpts.core.serviceBindings) {
      for (const [name, service] of Object.entries(
        workerOpts.core.serviceBindings
      )) {
        const { serviceName, entrypoint, remoteProxyConnectionString } = normaliseServiceDesignator(service);
        if (
          // Skip if it is a remote service
          remoteProxyConnectionString === void 0 && // Skip if the service is bound to another Worker defined in the Miniflare config
          serviceName && !allWorkerNames.includes(serviceName)
        ) {
          workerOpts.core.serviceBindings[name] = {
            external: {
              address: proxyAddress,
              http: getHttpProxyOptions(serviceName, entrypoint)
            }
          };
          const entrypoints = getEntrypoints(serviceName);
          entrypoints.entrypoints.add(entrypoint);
        }
      }
    }
    if (workerOpts.do.durableObjects) {
      for (const [bindingName, designator] of Object.entries(
        workerOpts.do.durableObjects
      )) {
        const {
          className,
          scriptName,
          unsafePreventEviction,
          enableSql: useSQLite,
          remoteProxyConnectionString
        } = normaliseDurableObject(designator);
        if (
          // Skip if it is a remote durable object
          remoteProxyConnectionString === void 0 && // Skip if the durable object is bound to a Worker that exists in the current Miniflare config
          scriptName && !allWorkerNames.includes(scriptName)
        ) {
          workerOpts.do.durableObjects[bindingName] = {
            className: getOutboundDoProxyClassName(scriptName, className),
            scriptName: OUTBOUND_DO_PROXY_SERVICE_NAME,
            useSQLite,
            // Matches the unique key Miniflare will generate for this object in
            // the target session. We need to do this so workerd generates the
            // same IDs it would if this were part of the same process. workerd
            // doesn't allow IDs from Durable Objects with different unique keys
            // to be used with each other.
            unsafeUniqueKey: `${scriptName}-${className}`,
            unsafePreventEviction
          };
          const entrypoints = getEntrypoints(scriptName);
          entrypoints.classNames.add(className);
        }
      }
    }
    if (workerOpts.core.tails) {
      for (let i = 0; i < workerOpts.core.tails.length; i++) {
        const {
          serviceName = workerOpts.core.name,
          entrypoint,
          remoteProxyConnectionString
        } = normaliseServiceDesignator(workerOpts.core.tails[i]);
        if (
          // Skip if it is a remote service
          remoteProxyConnectionString === void 0 && // Skip if the service is bound to the existing workers
          serviceName && !allWorkerNames.includes(serviceName)
        ) {
          workerOpts.core.tails[i] = {
            external: {
              address: proxyAddress,
              http: getHttpProxyOptions(serviceName, entrypoint)
            }
          };
          const entrypoints = getEntrypoints(serviceName);
          entrypoints.entrypoints.add(entrypoint);
        }
      }
    }
  }
  return externalServices;
}
function invalidWrappedAsBound(name, bindingType) {
  const stringName = JSON.stringify(name);
  throw new MiniflareCoreError(
    "ERR_INVALID_WRAPPED",
    `Cannot use ${stringName} for wrapped binding because it is bound to with ${bindingType} bindings.
Ensure other workers don't define ${bindingType} bindings to ${stringName}.`
  );
}
function getWrappedBindingNames(allWorkerOpts, durableObjectClassNames) {
  const wrappedBindingWorkerNames = /* @__PURE__ */ new Set();
  for (const workerOpts of allWorkerOpts) {
    for (const designator of Object.values(
      workerOpts.core.wrappedBindings ?? {}
    )) {
      const scriptName = typeof designator === "object" ? designator.scriptName : designator;
      if (durableObjectClassNames.has(getUserServiceName(scriptName))) {
        invalidWrappedAsBound(scriptName, "Durable Object");
      }
      wrappedBindingWorkerNames.add(scriptName);
    }
  }
  for (const workerOpts of allWorkerOpts) {
    for (const designator of Object.values(
      workerOpts.core.serviceBindings ?? {}
    )) {
      if (typeof designator !== "string") continue;
      if (wrappedBindingWorkerNames.has(designator)) {
        invalidWrappedAsBound(designator, "service");
      }
    }
  }
  return wrappedBindingWorkerNames;
}
function getQueueProducers(allWorkerOpts) {
  const queueProducers = /* @__PURE__ */ new Map();
  for (const workerOpts of allWorkerOpts) {
    const workerName = workerOpts.core.name ?? "";
    let workerProducers = workerOpts.queues.queueProducers;
    if (workerProducers !== void 0) {
      if (Array.isArray(workerProducers)) {
        workerProducers = Object.fromEntries(
          workerProducers.map((bindingName) => [
            bindingName,
            { queueName: bindingName }
          ])
        );
      }
      const producersIterable = Object.entries(
        workerProducers
      );
      for (const [bindingName, opts] of producersIterable) {
        if (typeof opts === "string") {
          queueProducers.set(bindingName, { workerName, queueName: opts });
        } else {
          queueProducers.set(bindingName, { workerName, ...opts });
        }
      }
    }
  }
  return queueProducers;
}
function getQueueConsumers(allWorkerOpts) {
  const queueConsumers = /* @__PURE__ */ new Map();
  for (const workerOpts of allWorkerOpts) {
    const workerName = workerOpts.core.name ?? "";
    let workerConsumers = workerOpts.queues.queueConsumers;
    if (workerConsumers !== void 0) {
      if (Array.isArray(workerConsumers)) {
        workerConsumers = Object.fromEntries(
          workerConsumers.map((queueName) => [queueName, {}])
        );
      }
      for (const [queueName, opts] of Object.entries(workerConsumers)) {
        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, ...opts });
      }
    }
  }
  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, wrappedBindingNames) {
  const allRoutes = /* @__PURE__ */ new Map();
  for (const workerOpts of allWorkerOpts) {
    const name = workerOpts.core.name ?? "";
    if (wrappedBindingNames.has(name)) continue;
    (0, import_node_assert23.default)(!allRoutes.has(name));
    allRoutes.set(name, workerOpts.core.routes ?? []);
  }
  return allRoutes;
}
function getProxyBindingName(plugin2, worker, binding) {
  return [
    CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY,
    plugin2,
    worker,
    binding
  ].join(":");
}
function isNativeTargetBinding(binding) {
  return !("json" in binding || "wasmModule" in binding || "text" in binding || "data" in binding);
}
function buildProxyBinding(plugin2, worker, binding) {
  (0, import_node_assert23.default)(binding.name !== void 0);
  const name = getProxyBindingName(plugin2, worker, binding.name);
  const proxyBinding = { ...binding, name };
  if ("durableObjectNamespace" in proxyBinding && proxyBinding.durableObjectNamespace !== void 0) {
    proxyBinding.durableObjectNamespace.serviceName ??= getUserServiceName(worker);
  }
  return proxyBinding;
}
function getInternalDurableObjectProxyBindings(plugin2, service) {
  if (!("worker" in service)) return;
  (0, import_node_assert23.default)(service.worker !== void 0);
  const serviceName = service.name;
  (0, import_node_assert23.default)(serviceName !== void 0);
  return service.worker.durableObjectNamespaces?.map(({ className }) => {
    (0, import_node_assert23.default)(className !== void 0);
    return {
      name: getProxyBindingName(`${plugin2}-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((x2) => x2.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(error) {
  if (error instanceof Error) {
    return error.stack || error.message;
  }
  if (typeof error === "string") {
    return error;
  }
  try {
    return JSON.stringify(error);
  } 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 is the browser process
  #browserProcesses = /* @__PURE__ */ new Map();
  #runtime;
  #removeExitHook;
  #runtimeEntryURL;
  #socketPorts;
  #runtimeDispatcher;
  #proxyClient;
  #structuredWorkerdLogs;
  #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;
  #liveReloadServer;
  #webSocketServer;
  #webSocketExtraHeaders;
  #devRegistry;
  #maybeInspectorProxyController;
  #previousRuntimeInspectorPort;
  #hyperdriveProxyController = new HyperdriveProxyController();
  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.core.inspectorPort === void 0) {
        throw new MiniflareCoreError(
          "ERR_MISSING_INSPECTOR_PROXY_PORT",
          "inspector proxy requested but without an inspectorPort specified"
        );
      }
    }
    if (maybeInstanceRegistry !== void 0) {
      const object = { name: "Miniflare", stack: "" };
      Error.captureStackTrace(object, _Miniflare);
      maybeInstanceRegistry.set(this, object.stack);
    }
    this.#log = this.#sharedOpts.core.log ?? new NoOpLog();
    this.#structuredWorkerdLogs = this.#sharedOpts.core.structuredWorkerdLogs ?? // If there is a `handleStructuredLogs` set then `structuredWorkerdLogs` defaults
    // to `true`, otherwise it defaults to `false`
    (this.#sharedOpts.core.handleStructuredLogs ? true : false);
    const inVscodeJsDebugTerminal = !!process.env.VSCODE_INSPECTOR_OPTIONS;
    if (enableInspectorProxy && !inVscodeJsDebugTerminal) {
      if (this.#sharedOpts.core.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.core.inspectorPort,
        this.#sharedOpts.core.inspectorHost,
        this.#log,
        workerNamesToProxy
      );
    }
    this.#liveReloadServer = new import_ws5.WebSocketServer({ noServer: true });
    this.#webSocketServer = new import_ws5.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.core.unsafeDevRegistryPath,
      this.#sharedOpts.core.unsafeDevRegistryDurableObjectProxy,
      this.#sharedOpts.core.unsafeHandleDevRegistryUpdate,
      this.#log
    );
    this.#tmpPath = import_node_path25.default.join(
      import_node_os10.default.tmpdir(),
      `miniflare-${import_node_crypto7.default.randomBytes(16).toString("hex")}`
    );
    this.#runtime = new Runtime();
    this.#removeExitHook = (0, import_exit_hook.default)(() => {
      void this.#runtime?.dispose();
      try {
        removeDirSync(this.#tmpPath);
      } catch (e) {
        this.#log.debug(`Unable to remove temporary 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(({ core: { unsafeInspectorProxy } }) => !!unsafeInspectorProxy).map((w2) => w2.core.name ?? "")
    );
  }
  #handleReload() {
    for (const ws of this.#liveReloadServer.clients) {
      ws.close(1012, "Service Restart");
    }
    for (const ws of this.#webSocketServer.clients) {
      ws.close(1012, "Service Restart");
    }
  }
  async #handleLoopbackCustomFetchService(request4, customService) {
    let service;
    if (customService === CoreBindings.IMAGES_SERVICE) {
      service = imagesLocalFetcher;
    } else {
      const { workerIndex, serviceKind, serviceName } = extractCustomService(customService);
      if (serviceKind === "#" /* UNKNOWN */) {
        service = this.#workerOpts[workerIndex]?.core.serviceBindings?.[serviceName];
      } else if (serviceName === CUSTOM_SERVICE_KNOWN_OUTBOUND) {
        service = this.#workerOpts[workerIndex]?.core.outboundService;
      }
    }
    (0, import_node_assert23.default)(typeof service === "function");
    try {
      let response = await service(request4, this);
      if (!(response instanceof Response2)) {
        response = new Response2(response.body, response);
      }
      return external_exports.instanceof(Response2).parse(response);
    } catch (error) {
      return new Response2(getErrorMessage(error), { status: 500 });
    }
  }
  async #handleLoopbackCustomNodeService(req, res, customService) {
    let service;
    const { workerIndex, serviceKind, serviceName } = extractCustomService(customService);
    if (serviceKind === "#" /* UNKNOWN */) {
      service = this.#workerOpts[workerIndex]?.core.serviceBindings?.[serviceName];
    } else if (serviceName === CUSTOM_SERVICE_KNOWN_OUTBOUND) {
      service = this.#workerOpts[workerIndex]?.core.outboundService;
    }
    (0, import_node_assert23.default)(typeof service === "object" && "node" in service);
    try {
      await service.node(req, res, this);
    } catch (error) {
      if (!res.headersSent) {
        res.writeHead(500);
      }
      res.end(getErrorMessage(error));
    }
  }
  /**
   * 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(url38) {
    const namespaceId = decodeURIComponent(
      url38.pathname.slice("/core/do-storage/".length)
    );
    (0, import_node_assert23.default)(namespaceId, "Namespace ID is required");
    const doSharedOpts = this.#sharedOpts.do;
    const coreSharedOpts = this.#sharedOpts.core;
    const doPersistPath = getPersistPath(
      DURABLE_OBJECTS_PLUGIN_NAME,
      this.#tmpPath,
      coreSharedOpts.defaultPersistRoot,
      doSharedOpts.durableObjectsPersist
    );
    const namespacePath = import_node_path25.default.join(doPersistPath, namespaceId);
    if (!namespacePath.startsWith(import_node_path25.default.resolve(doPersistPath) + import_node_path25.default.sep)) {
      return new Response2("Invalid namespace ID", { status: 400 });
    }
    try {
      const dirEntries = await import_node_fs17.default.promises.readdir(namespacePath, {
        withFileTypes: true
      });
      return Response2.json(
        dirEntries.map((entry) => ({
          name: entry.name,
          type: entry.isDirectory() ? "directory" : "file"
        }))
      );
    } catch (e) {
      if (isFileNotFoundError(e)) {
        return new Response2("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(url38) {
    const workflowName = decodeURIComponent(
      url38.pathname.slice("/core/workflow-storage/".length)
    );
    (0, import_node_assert23.default)(workflowName, "Workflow name is required");
    const workflowsSharedOpts = this.#sharedOpts.workflows;
    const coreSharedOpts = this.#sharedOpts.core;
    const workflowsPersistPath = getPersistPath(
      WORKFLOWS_PLUGIN_NAME,
      this.#tmpPath,
      coreSharedOpts.defaultPersistRoot,
      workflowsSharedOpts.workflowsPersist
    );
    const uniqueKey = `miniflare-workflows-${workflowName}`;
    const namespacePath = import_node_path25.default.join(workflowsPersistPath, uniqueKey);
    if (!namespacePath.startsWith(import_node_path25.default.resolve(workflowsPersistPath) + import_node_path25.default.sep)) {
      return new Response2("Invalid workflow name", { status: 400 });
    }
    try {
      const dirEntries = await import_node_fs17.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_fs17.default.promises.stat(
                import_node_path25.default.join(namespacePath, entry.name)
              );
              birthtimeMs = stat4.birthtimeMs;
            } catch {
            }
          }
          return {
            name: entry.name,
            type: entry.isDirectory() ? "directory" : "file",
            birthtimeMs
          };
        })
      );
      return Response2.json(entries);
    } catch (e) {
      if (isFileNotFoundError(e)) {
        return new Response2("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(url38) {
    const pathAfterPrefix = url38.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_assert23.default)(workflowName, "Workflow name is required");
    const workflowsSharedOpts = this.#sharedOpts.workflows;
    const coreSharedOpts = this.#sharedOpts.core;
    const workflowsPersistPath = getPersistPath(
      WORKFLOWS_PLUGIN_NAME,
      this.#tmpPath,
      coreSharedOpts.defaultPersistRoot,
      workflowsSharedOpts.workflowsPersist
    );
    const uniqueKey = `miniflare-workflows-${workflowName}`;
    const namespacePath = import_node_path25.default.join(workflowsPersistPath, uniqueKey);
    if (!namespacePath.startsWith(import_node_path25.default.resolve(workflowsPersistPath) + import_node_path25.default.sep)) {
      return new Response2("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_path25.default.join(namespacePath, `${hexId}${ext}`);
        if (!filePath.startsWith(namespacePath + import_node_path25.default.sep)) {
          return new Response2("Invalid instance ID", { status: 400 });
        }
        try {
          await import_node_fs17.default.promises.unlink(filePath);
          if (ext === ".sqlite") {
            deleted = true;
          }
        } catch (e) {
          if (!isFileNotFoundError(e)) {
            throw e;
          }
        }
      }
      if (!deleted) {
        return new Response2("Not Found", { status: 404 });
      }
    } else {
      try {
        const dirEntries = await import_node_fs17.default.promises.readdir(namespacePath);
        await Promise.all(
          dirEntries.filter((name) => extensions.some((ext) => name.endsWith(ext))).map(
            (name) => import_node_fs17.default.promises.unlink(import_node_path25.default.join(namespacePath, name)).catch(() => {
            })
          )
        );
      } catch (e) {
        if (!isFileNotFoundError(e)) {
          throw e;
        }
      }
    }
    return new Response2("OK", { status: 200 });
  }
  get #workerSrcOpts() {
    return this.#workerOpts.map(({ core }) => core);
  }
  #handleLoopback = async (req, res) => {
    const customNodeService = req.headers[CoreHeaders.CUSTOM_NODE_SERVICE.toLowerCase()];
    if (typeof customNodeService === "string") {
      (0, import_node_assert23.default)(res);
      this.#handleLoopbackCustomNodeService(req, res, customNodeService);
      return;
    }
    const headers = new import_undici4.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_assert23.default)(!Array.isArray(cfBlob));
    const cf = cfBlob ? JSON.parse(cfBlob) : void 0;
    const originalUrl = headers.get(CoreHeaders.ORIGINAL_URL);
    const url38 = 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(url38, {
      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 (this.#sharedOpts.core.unsafeModuleFallbackService !== void 0 && request4.headers.has("X-Resolve-Method") && originalUrl === null) {
        response = await this.#sharedOpts.core.unsafeModuleFallbackService(
          request4,
          this
        );
      } else if (url38.pathname === "/core/error") {
        response = await handlePrettyErrorRequest(
          this.#log,
          this.#workerSrcOpts,
          request4
        );
      } else if (url38.pathname === "/core/log") {
        const level = parseInt(request4.headers.get(SharedHeaders.LOG_LEVEL));
        (0, import_node_assert23.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 (!$.enabled) message = stripAnsi(message);
        this.#log.logWithLevel(logLevel, message);
        response = new Response2(null, { status: 204 });
      } else if (url38.pathname === "/browser/launch") {
        const headful = this.#workerOpts.some(
          (w2) => w2[BROWSER_RENDERING_PLUGIN_NAME].browserRendering?.headful
        );
        const { sessionId, browserProcess, startTime, wsEndpoint } = await launchBrowser({
          // Puppeteer v22.13.1 supported chrome version:
          // https://pptr.dev/supported-browsers#supported-browser-version-list
          //
          // It should match the supported chrome version for the upstream puppeteer
          // version from which @cloudflare/puppeteer branched off, which is specified in:
          // https://github.com/cloudflare/puppeteer/?tab=readme-ov-file#workers-version-of-puppeteer-core
          browserVersion: "126.0.6478.182",
          log: this.#log,
          tmpPath: this.#tmpPath,
          headful
        });
        browserProcess.nodeProcess.on("exit", () => {
          this.#browserProcesses.delete(sessionId);
        });
        this.#browserProcesses.set(sessionId, browserProcess);
        response = Response2.json({ wsEndpoint, sessionId, startTime });
      } else if (url38.pathname === "/browser/status") {
        const sessionId = url38.searchParams.get("sessionId");
        (0, import_node_assert23.default)(sessionId !== null, "Missing sessionId query parameter");
        const process7 = this.#browserProcesses.get(sessionId);
        response = new Response2(null, { status: process7 ? 200 : 410 });
      } else if (url38.pathname === "/browser/close") {
        const sessionId = url38.searchParams.get("sessionId");
        (0, import_node_assert23.default)(sessionId !== null, "Missing sessionId query parameter");
        const browserProcess = this.#browserProcesses.get(sessionId);
        if (!browserProcess) {
          response = new Response2("Session not found", { status: 404 });
        } else {
          this.#browserProcesses.delete(sessionId);
          await browserProcess.close().catch(() => {
          });
          response = new Response2(null, { status: 200 });
        }
      } else if (url38.pathname === "/browser/sessionIds") {
        const sessionIds = this.#browserProcesses.keys();
        response = Response2.json(Array.from(sessionIds));
      } else if (url38.pathname === "/core/store-temp-file") {
        const prefix = url38.searchParams.get("prefix");
        const folder5 = prefix ? `files/${prefix}` : "files";
        await (0, import_promises22.mkdir)(import_node_path25.default.join(this.#tmpPath, folder5), { recursive: true });
        const filePath = import_node_path25.default.join(
          this.#tmpPath,
          folder5,
          `${import_node_crypto7.default.randomUUID()}.${url38.searchParams.get("extension") ?? "txt"}`
        );
        await (0, import_promises22.writeFile)(filePath, await request4.text());
        response = new Response2(filePath, { status: 200 });
      } else if (url38.pathname.startsWith("/core/do-storage/")) {
        response = await this.#handleLoopbackDOStorageRequest(url38);
      } else if (url38.pathname.startsWith("/core/workflow-storage/")) {
        if (request4.method === "DELETE") {
          response = await this.#handleLoopbackWorkflowStorageDeleteRequest(url38);
        } else {
          response = await this.#handleLoopbackWorkflowStorageRequest(url38);
        }
      } else if (url38.pathname === "/core/dev-registry") {
        const registryPath = this.#devRegistry.getRegistryPath();
        const registry = registryPath ? getWorkerRegistry(registryPath) : {};
        response = Response2.json(registry);
      }
    } 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 { pathname } = new URL(req.url ?? "", "http://localhost");
    if (pathname === CorePaths.LIVE_RELOAD) {
      this.#liveReloadServer.handleUpgrade(req, socket, head, (ws) => {
        this.#liveReloadServer.emit("connection", ws, req);
      });
      return;
    }
    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_assert23.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 (error) {
        this.#log.debug(
          `Error writing response body, closing response early: ${error}`
        );
      }
    }
    initialStream.end();
  }
  async #getLoopbackPort() {
    const loopbackHost = this.#sharedOpts.core.host ?? DEFAULT_HOST;
    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(hostname) {
    if (hostname === "*") hostname = "::";
    return new Promise((resolve6) => {
      const server = (0, import_stoppable.default)(
        import_node_http2.default.createServer(this.#handleLoopback),
        /* grace */
        0
      );
      server.on("upgrade", this.#handleLoopbackUpgrade);
      server.listen(0, hostname, () => resolve6(server));
    });
  }
  #stopLoopbackServer() {
    return new Promise((resolve6, reject) => {
      (0, import_node_assert23.default)(this.#loopbackServer !== void 0);
      this.#loopbackServer.stop((err) => err ? reject(err) : resolve6());
    });
  }
  #getSocketAddress(id, previousRequestedPort, host = DEFAULT_HOST, 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 unsafeBinding of worker.core.unsafeBindings ?? []) {
        requestedExternalPlugins.set(
          unsafeBinding.plugin.name,
          unsafeBinding.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, plugin2] of Object.entries(providedPlugins)) {
          this.#externalPlugins.set(name, plugin2);
        }
      }
    }
  }
  /**
   * External plugins take an array of unsafe bindings that match the plugin name,
   * while internal plugins have more structured config.
   */
  #getWorkerOptsForPlugin(pluginName, workerOpts) {
    if (this.#externalPlugins.has(pluginName)) {
      return workerOpts.core.unsafeBindings?.filter(
        (b) => b.plugin.name === pluginName
      );
    } else {
      return workerOpts[pluginName];
    }
  }
  async #assembleConfig(loopbackPort, proxyAddress) {
    const allPreviousWorkerOpts = this.#previousWorkerOpts;
    const allWorkerOpts = this.#workerOpts;
    const sharedOpts = this.#sharedOpts;
    await this.#loadExternalPlugins(allWorkerOpts);
    sharedOpts.core.cf = await setupCf(this.#log, sharedOpts.core.cf);
    this.#cfObject = sharedOpts.core.cf;
    const externalServices = proxyAddress !== null ? getExternalServiceEntrypoints(allWorkerOpts, proxyAddress) : null;
    const durableObjectClassNames = getDurableObjectClassNames(allWorkerOpts);
    const wrappedBindingNames = getWrappedBindingNames(
      allWorkerOpts,
      durableObjectClassNames
    );
    const queueProducers = getQueueProducers(allWorkerOpts);
    const queueConsumers = getQueueConsumers(allWorkerOpts);
    const allWorkerRoutes = getWorkerRoutes(allWorkerOpts, wrappedBindingNames);
    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.core)
      }
    ];
    const configuredHost = sharedOpts.core.host ?? DEFAULT_HOST;
    if (maybeGetLocallyAccessibleHost(configuredHost) === void 0) {
      sockets.push({
        name: SOCKET_ENTRY_LOCAL,
        service: { name: SERVICE_ENTRY },
        http: {},
        address: "127.0.0.1:0"
      });
    }
    const proxyBindings = [];
    const allWorkerBindings = /* @__PURE__ */ new Map();
    const wrappedBindingsToPopulate = [];
    for (const [key, plugin2] of this.#mergedPluginEntries) {
      const pluginExtensions = await plugin2.getExtensions?.({
        // @ts-expect-error `CoreOptionsSchema` has required options which are
        //  missing in other plugins' options.
        options: allWorkerOpts.map((o) => this.#getWorkerOptsForPlugin(key, o))
      });
      if (pluginExtensions) {
        extensions.push(...pluginExtensions);
      }
    }
    for (let i = 0; i < allWorkerOpts.length; i++) {
      const previousWorkerOpts = allPreviousWorkerOpts?.[i];
      const workerOpts = allWorkerOpts[i];
      const workerName = workerOpts.core.name ?? "";
      const isModulesWorker = Boolean(workerOpts.core.modules);
      if (workerOpts.workflows.workflows) {
        for (const workflow of Object.values(workerOpts.workflows.workflows)) {
          workflow.scriptName ??= workerOpts.core.name;
        }
      }
      if (workerOpts.assets.assets) {
        workerOpts.assets.assets.workerName = workerOpts.core.name;
      }
      const workerBindings = [];
      allWorkerBindings.set(workerName, workerBindings);
      const additionalModules = [];
      for (const [key, plugin2] of this.#mergedPluginEntries) {
        const pluginBindings = await plugin2.getBindings(
          this.#getWorkerOptsForPlugin(key, workerOpts),
          i
        );
        if (pluginBindings !== void 0) {
          for (const binding of pluginBindings) {
            if (key === "kv" && binding.name === SiteBindings.JSON_SITE_MANIFEST && isModulesWorker) {
              (0, import_node_assert23.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 ("wrapped" in binding && binding.wrapped?.moduleName !== void 0 && binding.wrapped.innerBindings !== void 0) {
              const workerName2 = maybeWrappedModuleToWorkerName(
                binding.wrapped.moduleName
              );
              if (workerName2 !== void 0) {
                wrappedBindingsToPopulate.push({
                  workerName: workerName2,
                  innerBindings: binding.wrapped.innerBindings
                });
              }
            }
            if ("service" in binding) {
              const targetWorkerName = binding.service?.name?.replace(
                "core:user:",
                ""
              );
              const maybeAssetTargetService = allWorkerOpts.find(
                (worker) => worker.core.name === targetWorkerName && worker.assets.assets
              );
              if (maybeAssetTargetService && !binding.service?.entrypoint) {
                (0, import_node_assert23.default)(binding.service?.name);
                binding.service.name = `${RPC_PROXY_SERVICE_NAME}:${targetWorkerName}`;
              }
            }
          }
        }
      }
      const unsafeStickyBlobs = sharedOpts.core.unsafeStickyBlobs ?? false;
      const unsafeEphemeralDurableObjects = workerOpts.core.unsafeEphemeralDurableObjects ?? false;
      const pluginServicesOptionsBase = {
        log: this.#log,
        workerBindings,
        workerIndex: i,
        additionalModules,
        tmpPath: this.#tmpPath,
        defaultPersistRoot: sharedOpts.core.defaultPersistRoot,
        workerNames,
        loopbackPort,
        unsafeStickyBlobs,
        wrappedBindingNames,
        durableObjectClassNames,
        unsafeEphemeralDurableObjects,
        queueProducers,
        queueConsumers,
        hyperdriveProxyController: this.#hyperdriveProxyController
      };
      for (const [key, plugin2] of this.#mergedPluginEntries) {
        const workerOptions = this.#getWorkerOptsForPlugin(key, workerOpts);
        const pluginServicesExtensions = await plugin2.getServices({
          ...pluginServicesOptionsBase,
          // @ts-expect-error `CoreOptionsSchema` has required options which are
          //  missing in other plugins' options.
          options: workerOptions,
          // @ts-expect-error `QueuesPlugin` doesn't define shared options
          sharedOptions: sharedOpts[key]
        });
        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?.core.unsafeDirectSockets ?? [];
      const directSockets = workerOpts.core.unsafeDirectSockets ?? [];
      for (let j = 0; j < directSockets.length; j++) {
        const previousDirectSocket = previousDirectSockets[j];
        const directSocket = directSockets[j];
        const serviceName = directSocket.serviceName ?? workerName;
        const entrypoint = directSocket.entrypoint ?? "default";
        const name = getDirectSocketName(i, entrypoint);
        const address = this.#getSocketAddress(
          name,
          previousDirectSocket?.port,
          directSocket.host,
          directSocket.port
        );
        const service = workerOpts.assets.assets && entrypoint === "default" ? {
          name: `${RPC_PROXY_SERVICE_NAME}:${workerOpts.core.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) {
      for (const [serviceName, { entrypoints }] of externalServices) {
        const proxyFallbackService = createProxyFallbackService(
          serviceName,
          entrypoints
        );
        (0, import_node_assert23.default)(proxyFallbackService.name !== void 0);
        services.set(proxyFallbackService.name, proxyFallbackService);
        for (const entrypoint of entrypoints) {
          const socketName = getProxyFallbackServiceSocketName(
            serviceName,
            entrypoint
          );
          sockets.push({
            name: socketName,
            // Reuse the socket address from the previous direct socket if exists
            address: this.#getSocketAddress(socketName, 0, DEFAULT_HOST, 0),
            service: {
              name: proxyFallbackService.name,
              entrypoint
            },
            http: {
              style: HttpOptions_Style.PROXY,
              cfBlobHeader: CoreHeaders.CF_BLOB,
              capnpConnectHost: HOST_CAPNP_CONNECT
            }
          });
        }
      }
      const externalObjects = Array.from(externalServices).flatMap(
        ([scriptName, { classNames }]) => Array.from(classNames).map((className) => [
          scriptName,
          className
        ])
      );
      const outboundDoProxyService = createOutboundDoProxyService(
        externalObjects,
        `http://${proxyAddress}`,
        this.#devRegistry.isDurableObjectProxyEnabled()
      );
      (0, import_node_assert23.default)(outboundDoProxyService.name !== void 0);
      services.set(outboundDoProxyService.name, outboundDoProxyService);
      await this.#devRegistry.watch(externalServices);
    }
    if (this.#devRegistry.isDurableObjectProxyEnabled()) {
      const internalObjects = allWorkerOpts.flatMap((workerOpts) => {
        const scriptName = workerOpts.core.name;
        const serviceName = getUserServiceName(scriptName);
        const classNames = durableObjectClassNames.get(serviceName);
        if (!classNames || !scriptName) {
          return [];
        }
        return Array.from(classNames.keys()).map(
          (className) => [scriptName, className]
        );
      });
      if (internalObjects.length > 0) {
        const service = createInboundDoProxyService(internalObjects);
        (0, import_node_assert23.default)(service.name !== void 0);
        services.set(service.name, service);
        allWorkerRoutes.set(INBOUND_DO_PROXY_SERVICE_NAME, [
          `*/${INBOUND_DO_PROXY_SERVICE_PATH}`
        ]);
      }
    }
    const workflowOptions = /* @__PURE__ */ new Map();
    for (const workerOpts of allWorkerOpts) {
      if (workerOpts.workflows.workflows) {
        for (const workflow of Object.values(workerOpts.workflows.workflows)) {
          workflowOptions.set(workflow.name, {
            name: workflow.name,
            className: workflow.className,
            scriptName: workflow.scriptName
          });
        }
      }
    }
    const globalServices = getGlobalServices({
      sharedOptions: sharedOpts.core,
      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].assets.assets && !this.#workerOpts[0].core.name?.startsWith(
        "vitest-pool-workers-runner-"
      ) ? `${RPC_PROXY_SERVICE_NAME}:${this.#workerOpts[0].core.name}` : getUserServiceName(this.#workerOpts[0].core.name),
      loopbackPort,
      log: this.#log,
      proxyBindings,
      durableObjectClassNames,
      workflowOptions: workflowOptions.size > 0 ? workflowOptions : void 0,
      allWorkerOpts
    });
    for (const service of globalServices) {
      (0, import_node_assert23.default)(service.name !== void 0 && !services.has(service.name));
      services.set(service.name, service);
    }
    for (const toPopulate of wrappedBindingsToPopulate) {
      const bindings = allWorkerBindings.get(toPopulate.workerName);
      if (bindings === void 0) continue;
      const existingBindingNames = new Set(
        toPopulate.innerBindings.map(({ name }) => name)
      );
      toPopulate.innerBindings.push(
        ...bindings.filter(({ name }) => !existingBindingNames.has(name))
      );
    }
    const servicesArray = Array.from(services.values());
    if (wrappedBindingsToPopulate.length > 0 && _isCyclic(servicesArray)) {
      throw new MiniflareCoreError(
        "ERR_CYCLIC",
        "Generated workerd config contains cycles. Ensure wrapped bindings don't have bindings to themselves."
      );
    }
    return {
      services: servicesArray,
      sockets,
      extensions,
      structuredLogging: this.#structuredWorkerdLogs
    };
  }
  async #assembleAndUpdateConfig() {
    await this.#closeBrowserProcesses();
    const initial = !this.#runtimeEntryURL;
    (0, import_node_assert23.default)(this.#runtime !== void 0);
    const configuredHost = this.#sharedOpts.core.host ?? DEFAULT_HOST;
    const loopbackHost = maybeGetLocallyAccessibleHost(configuredHost) ?? getURLSafeHost(configuredHost);
    const loopbackPort = await this.#getLoopbackPort();
    const proxyAddress = await this.#devRegistry.initializeProxyWorker();
    const config = await this.#assembleConfig(loopbackPort, proxyAddress);
    const configBuffer = serializeConfig(config);
    (0, import_node_assert23.default)(config.sockets !== void 0);
    const requiredSockets = config.sockets.map(
      ({ name }) => {
        (0, import_node_assert23.default)(name !== void 0);
        return name;
      }
    );
    if (this.#sharedOpts.core.inspectorPort !== void 0) {
      requiredSockets.push(kInspectorSocket);
    }
    const entryAddress = this.#getSocketAddress(
      SOCKET_ENTRY,
      this.#previousSharedOpts?.core.port,
      configuredHost,
      this.#sharedOpts.core.port
    );
    let runtimeInspectorAddress;
    if (this.#sharedOpts.core.inspectorPort !== void 0) {
      let runtimeInspectorPort = this.#sharedOpts.core.inspectorPort;
      if (this.#maybeInspectorProxyController !== void 0) {
        runtimeInspectorPort = 0;
      }
      runtimeInspectorAddress = this.#getSocketAddress(
        kInspectorSocket,
        this.#previousRuntimeInspectorPort,
        "localhost",
        runtimeInspectorPort
      );
      this.#previousRuntimeInspectorPort = runtimeInspectorPort;
    }
    const loopbackAddress = `${loopbackHost}:${loopbackPort}`;
    const runtimeOpts = {
      signal: this.#disposeController.signal,
      entryAddress,
      loopbackAddress,
      requiredSockets,
      inspectorAddress: runtimeInspectorAddress,
      verbose: this.#sharedOpts.core.verbose,
      handleRuntimeStdio: this.#sharedOpts.core.handleRuntimeStdio,
      handleStructuredLogs: this.#sharedOpts.core.handleStructuredLogs
    };
    const maybeSocketPorts = await this.#runtime.updateConfig(
      configBuffer,
      runtimeOpts,
      this.#workerOpts.flatMap((w2) => w2.core.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.core.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.core.inspectorPort,
          this.#sharedOpts.core.inspectorHost ?? "127.0.0.1",
          maybePort,
          this.#workerNamesToProxy()
        );
      }
    }
    const entrySocket = config.sockets?.[0];
    const secure = entrySocket !== void 0 && "https" in entrySocket;
    const previousEntryURL = this.#runtimeEntryURL;
    const entryPort = maybeSocketPorts.get(SOCKET_ENTRY);
    (0, import_node_assert23.default)(entryPort !== void 0);
    const maybeAccessibleHost = maybeGetLocallyAccessibleHost(configuredHost);
    if (maybeAccessibleHost === void 0) {
      const localEntryPort = maybeSocketPorts.get(SOCKET_ENTRY_LOCAL);
      (0, import_node_assert23.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()) {
      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
      });
    }
    if (this.#proxyClient === void 0) {
      this.#proxyClient = new ProxyClient(
        this.#runtimeEntryURL,
        this.dispatchFetch
      );
    } else {
      this.#proxyClient.setRuntimeEntryURL(this.#runtimeEntryURL);
    }
    if (!this.#runtimeMutex.hasWaiting) {
      const ready = initial ? "Ready" : "Updated and ready";
      const urlSafeHost = getURLSafeHost(configuredHost);
      if (this.#sharedOpts.core.logRequests) {
        this.#log.logReady(
          `${ready} on ${green2(
            `${secure ? "https" : "http"}://${urlSafeHost}:${entryPort}`
          )}`
        );
      }
      if (initial && this.#sharedOpts.core.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 h2 of hosts) {
          this.#log.logReady(
            `- ${secure ? "https" : "http"}://${h2}:${entryPort}`
          );
        }
      }
      this.#handleReload();
    }
  }
  async #closeBrowserProcesses() {
    await Promise.all(
      Array.from(this.#browserProcesses.values()).map(
        (process7) => process7.close()
      )
    );
    (0, import_node_assert23.default)(
      this.#browserProcesses.size === 0,
      "Not all browser processes were closed"
    );
  }
  async #waitForReady(disposing = false) {
    await this.#initPromise;
    await this.#runtimeMutex.drained();
    if (disposing) return new URL("http://[100::]/");
    await this.#maybeInspectorProxyController?.ready;
    this.#checkDisposed();
    (0, import_node_assert23.default)(this.#runtimeEntryURL !== void 0);
    return new URL(this.#runtimeEntryURL.toString());
  }
  async #registerWorkers(url38) {
    if (!this.#devRegistry.isEnabled()) {
      return;
    }
    const protocol = getProtocol(url38);
    const allWorkerNames = this.#workerOpts.map(
      (workerOpt) => workerOpt.core.name
    );
    const entries = await Promise.all(
      this.#workerOpts.map(
        async (workerOpts) => {
          if (!workerOpts.core.name) {
            return;
          }
          try {
            const entrypointAddressesEntries = await Promise.all(
              workerOpts.core.unsafeDirectSockets?.map(async (directSocket) => {
                const directUrl = await this.unsafeGetDirectURL(
                  workerOpts.core.name,
                  directSocket.entrypoint
                );
                return [
                  directSocket.entrypoint ?? "default",
                  {
                    host: directUrl.hostname,
                    port: parseInt(directUrl.port)
                  }
                ];
              }) ?? []
            );
            const internalObjects = Object.entries(
              workerOpts.do.durableObjects ?? {}
            ).reduce(
              (internalObjects2, [bindingName, designator]) => {
                const { className, scriptName, remoteProxyConnectionString } = normaliseDurableObject(designator);
                if (
                  // If the scriptName is undefined, it defaults to the current worker
                  scriptName === void 0 || // If the scriptName matches one of the workers defined, it is internal as well
                  allWorkerNames.includes(scriptName) || // If it is not a remote durable object
                  remoteProxyConnectionString === void 0
                ) {
                  internalObjects2.push({
                    name: bindingName,
                    className
                  });
                }
                return internalObjects2;
              },
              []
            );
            return [
              workerOpts.core.name,
              {
                protocol,
                // These host and port values are used only when the registered definition
                // does not include direct entrypoint (i.e. old wrangler version) or uses service-worker syntax.
                // See https://github.com/cloudflare/workers-sdk/blob/8cdabe23fcc2813f970db02928b016bbf3b155e5/packages/wrangler/src/dev/miniflare.ts#L506-L507
                host: url38.hostname,
                port: parseInt(url38.port),
                entrypointAddresses: Object.fromEntries(
                  entrypointAddressesEntries
                ),
                durableObjects: internalObjects
              }
            ];
          } catch (e) {
            this.#log.error(e);
            return;
          }
        }
      )
    );
    this.#devRegistry.register(
      Object.fromEntries(entries.filter((entry) => entry !== void 0))
    );
  }
  get ready() {
    return this.#waitForReady().then(async (url38) => {
      (0, import_node_assert23.default)(this.#socketPorts !== void 0);
      this.#devRegistry.configureProxyWorker(url38.toString(), this.#socketPorts);
      await this.#registerWorkers(url38);
      return url38;
    });
  }
  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_assert23.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_assert23.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.core.unsafeDirectSockets?.find(
      (socket) => (socket.entrypoint ?? "default") === entrypoint
    );
    (0, import_node_assert23.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.core.log ?? this.#log;
    this.#structuredWorkerdLogs = this.#sharedOpts.core.structuredWorkerdLogs ?? this.#structuredWorkerdLogs;
    await this.#devRegistry.updateRegistryPath(
      sharedOpts.core.unsafeDevRegistryPath,
      sharedOpts.core.unsafeDevRegistryDurableObjectProxy,
      sharedOpts.core.unsafeHandleDevRegistryUpdate
    );
    await this.#assembleAndUpdateConfig();
  }
  setOptions(opts) {
    this.#checkDisposed();
    this.#proxyClient?.poisonProxies();
    return this.#runtimeMutex.runWith(() => this.#setOptions(opts)).then(() => {
      (0, import_node_assert23.default)(
        this.#runtimeEntryURL !== void 0,
        "The runtime entry URL should be defined at this point"
      );
      return this.#registerWorkers(this.#runtimeEntryURL);
    });
  }
  dispatchFetch = async (input, init2) => {
    this.#checkDisposed();
    await this.ready;
    (0, import_node_assert23.default)(this.#runtimeEntryURL !== void 0);
    (0, import_node_assert23.default)(this.#runtimeDispatcher !== void 0);
    const forward = new Request(input, init2);
    const url38 = new URL(forward.url);
    const actualRuntimeOrigin = this.#runtimeEntryURL.origin;
    const userRuntimeOrigin = url38.origin;
    url38.protocol = this.#runtimeEntryURL.protocol;
    url38.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 fetch4(url38, forwardInit);
    const stack = response.headers.get(CoreHeaders.ERROR_STACK);
    if (response.status === 500 && stack !== null) {
      const caught = JsonErrorSchema.parse(await response.json());
      throw reviveError(this.#workerSrcOpts, 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 error = new Error(
        "`body` returned from `Miniflare#dispatchFetch()` not consumed immediately"
      );
      Error.stackTraceLimit = originalLimit;
      setImmediate(() => {
        if (!response.bodyUsed) throw error;
      });
    }
    return response;
  };
  /** @internal */
  async _getProxyClient() {
    this.#checkDisposed();
    await this.ready;
    (0, import_node_assert23.default)(this.#proxyClient !== void 0);
    return this.#proxyClient;
  }
  #findAndAssertWorkerIndex(workerName) {
    if (workerName === void 0) {
      return 0;
    } else {
      const index = this.#workerOpts.findIndex(
        ({ core }) => (core.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.core.name ?? "";
    for (const [key, plugin2] of this.#mergedPluginEntries) {
      const pluginBindings = await plugin2.getNodeBindings(
        this.#getWorkerOptsForPlugin(key, 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_assert23.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.core.name ?? "";
    const bindingName = CoreBindings.SERVICE_USER_ROUTE_PREFIX + workerName;
    const fetcher = proxyClient.env[bindingName];
    if (fetcher === void 0) {
      const stringName = JSON.stringify(workerName);
      throw new TypeError(
        `${stringName} is being used as a wrapped binding, and cannot be accessed as a worker`
      );
    }
    return fetcher;
  }
  async #getProxy(pluginName, bindingName, workerName) {
    const proxyClient = await this._getProxyClient();
    const proxyBindingName = getProxyBindingName(
      pluginName,
      // Default to entrypoint worker if none specified
      workerName ?? this.#workerOpts[0].core.name ?? "",
      bindingName
    );
    const proxy = proxyClient.env[proxyBindingName];
    if (proxy === void 0) {
      const friendlyWorkerName = workerName === void 0 ? "entrypoint" : JSON.stringify(workerName);
      throw new TypeError(
        `${JSON.stringify(bindingName)} unbound in ${friendlyWorkerName} worker`
      );
    }
    return proxy;
  }
  // 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);
  }
  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);
  }
  unsafeGetPersistPaths() {
    const result = /* @__PURE__ */ new Map();
    for (const [key, plugin2] of PLUGIN_ENTRIES) {
      const sharedOpts = this.#sharedOpts[key];
      const maybePath = plugin2.getPersistPath?.(sharedOpts, this.#tmpPath);
      if (maybePath !== void 0) result.set(key, maybePath);
    }
    return result;
  }
  get #mergedPluginEntries() {
    return [...PLUGIN_ENTRIES, ...this.#externalPlugins.entries()];
  }
  async dispose() {
    this.#disposeController.abort();
    this.#proxyClient?.poisonProxies();
    try {
      await this.#waitForReady(
        /* disposing */
        true
      );
    } finally {
      await this.#closeBrowserProcesses();
      this.#removeExitHook?.();
      await this.#proxyClient?.dispose();
      await this.#runtime?.dispose();
      await this.#stopLoopbackServer();
      removeDir(this.#tmpPath, { fireAndForget: true });
      await this.#maybeInspectorProxyController?.dispose();
      await this.#devRegistry.dispose();
      await this.#hyperdriveProxyController.dispose();
      maybeInstanceRegistry?.delete(this);
    }
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  AIOptionsSchema,
  AISearchOptionsSchema,
  AI_PLUGIN,
  AI_PLUGIN_NAME,
  AI_SEARCH_PLUGIN,
  AI_SEARCH_PLUGIN_NAME,
  ANALYTICS_ENGINE_PLUGIN,
  ANALYTICS_ENGINE_PLUGIN_NAME,
  ASSETS_PLUGIN,
  AnalyticsEngineSchemaOptionsSchema,
  AnalyticsEngineSchemaSharedOptionsSchema,
  AssetsOptionsSchema,
  BROWSER_RENDERING_PLUGIN,
  BROWSER_RENDERING_PLUGIN_NAME,
  BrowserRenderingOptionsSchema,
  CACHE_PLUGIN,
  CACHE_PLUGIN_NAME,
  CORE_PLUGIN,
  CORE_PLUGIN_NAME,
  CacheBindings,
  CacheHeaders,
  CacheOptionsSchema,
  CacheSharedOptionsSchema,
  CloseEvent,
  CoreBindings,
  CoreHeaders,
  CoreOptionsSchema,
  CorePaths,
  CoreSharedOptionsSchema,
  D1OptionsSchema,
  D1SharedOptionsSchema,
  D1_PLUGIN,
  D1_PLUGIN_NAME,
  DEFAULT_PERSIST_ROOT,
  DISPATCH_NAMESPACE_PLUGIN,
  DISPATCH_NAMESPACE_PLUGIN_NAME,
  DOContainerOptionsSchema,
  DURABLE_OBJECTS_PLUGIN,
  DURABLE_OBJECTS_PLUGIN_NAME,
  DURABLE_OBJECTS_STORAGE_SERVICE_NAME,
  DeferredPromise,
  DispatchFetchDispatcher,
  DispatchNamespaceOptionsSchema,
  DurableObjectsOptionsSchema,
  DurableObjectsSharedOptionsSchema,
  EMAIL_PLUGIN,
  EMAIL_PLUGIN_NAME,
  EmailOptionsSchema,
  ErrorEvent,
  FLAGSHIP_PLUGIN,
  FLAGSHIP_PLUGIN_NAME,
  FlagshipOptionsSchema,
  FormData,
  HELLO_WORLD_PLUGIN,
  HELLO_WORLD_PLUGIN_NAME,
  HOST_CAPNP_CONNECT,
  HYPERDRIVE_PLUGIN,
  HYPERDRIVE_PLUGIN_NAME,
  Headers,
  HelloWorldOptionsSchema,
  HelloWorldSharedOptionsSchema,
  HttpOptions_Style,
  HyperdriveInputOptionsSchema,
  HyperdriveSchema,
  IMAGES_PLUGIN,
  IMAGES_PLUGIN_NAME,
  INTROSPECT_SQLITE_METHOD,
  ImagesOptionsSchema,
  ImagesSharedOptionsSchema,
  JsonSchema,
  KVHeaders,
  KVLimits,
  KVOptionsSchema,
  KVParams,
  KVSharedOptionsSchema,
  KV_NAMESPACE_OBJECT_CLASS_NAME,
  KV_PLUGIN,
  KV_PLUGIN_NAME,
  LiteralSchema,
  Log,
  LogLevel,
  MAX_BULK_GET_KEYS,
  MEDIA_PLUGIN,
  MEDIA_PLUGIN_NAME,
  MTLS_PLUGIN,
  MTLS_PLUGIN_NAME,
  MediaOptionsSchema,
  MessageEvent,
  Miniflare,
  MiniflareCoreError,
  MiniflareError,
  ModuleDefinitionSchema,
  ModuleRuleSchema,
  ModuleRuleTypeSchema,
  MtlsOptionsSchema,
  Mutex,
  NoOpLog,
  PIPELINES_PLUGIN_NAME,
  PIPELINE_PLUGIN,
  PLUGINS,
  PLUGIN_ENTRIES,
  PathSchema,
  PeriodType,
  PersistenceSchema,
  PipelineOptionsSchema,
  ProxyAddresses,
  ProxyClient,
  ProxyNodeBinding,
  ProxyOps,
  QUEUES_PLUGIN,
  QUEUES_PLUGIN_NAME,
  QueueBindings,
  QueueConsumerOptionsSchema,
  QueueConsumerSchema,
  QueueConsumersSchema,
  QueueContentTypeSchema,
  QueueIncomingMessageSchema,
  QueueMessageDelaySchema,
  QueueProducerOptionsSchema,
  QueueProducerSchema,
  QueueProducersSchema,
  QueuesBatchRequestSchema,
  QueuesError,
  QueuesOptionsSchema,
  R2OptionsSchema,
  R2SharedOptionsSchema,
  R2_PLUGIN,
  R2_PLUGIN_NAME,
  RATELIMIT_PLUGIN,
  RATELIMIT_PLUGIN_NAME,
  RatelimitConfigSchema,
  RatelimitOptionsSchema,
  Request,
  Response,
  RouterError,
  Runtime,
  SECRET_STORE_PLUGIN,
  SECRET_STORE_PLUGIN_NAME,
  SERVICE_ENTRY,
  SERVICE_LOOPBACK,
  SITES_NO_CACHE_PREFIX,
  SOCKET_ENTRY,
  SOCKET_ENTRY_LOCAL,
  STREAM_COMPAT_DATE,
  STREAM_OBJECT_CLASS_NAME,
  STREAM_PLUGIN,
  STREAM_PLUGIN_NAME,
  SYSTEM_ERROR_CODES,
  SecretsStoreSecretsOptionsSchema,
  SecretsStoreSecretsSharedOptionsSchema,
  SharedBindings,
  SharedHeaders,
  SiteBindings,
  SourceOptionsSchema,
  StreamOptionsSchema,
  StreamSharedOptionsSchema,
  TlsOptions_Version,
  TypedEventTarget,
  USER_ERROR_CODES,
  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,
  VectorizeOptionsSchema,
  VersionMetadataOptionsSchema,
  VpcNetworksOptionsSchema,
  VpcServicesOptionsSchema,
  WORKER_BINDING_SERVICE_LOOPBACK,
  WORKER_LOADER_PLUGIN,
  WORKER_LOADER_PLUGIN_NAME,
  WORKFLOWS_PLUGIN,
  WORKFLOWS_PLUGIN_NAME,
  WORKFLOWS_STORAGE_SERVICE_NAME,
  WaitGroup,
  WebSocket,
  WebSocketPair,
  WorkerLoaderConfigSchema,
  WorkerLoaderOptionsSchema,
  Worker_Binding_CryptoKey_Usage,
  WorkflowsOptionsSchema,
  WorkflowsSharedOptionsSchema,
  __MiniflareFunctionWrapper,
  _enableControlEndpoints,
  _forceColour,
  _initialiseInstanceRegistry,
  _isCyclic,
  _transformsForContentEncodingAndContentType,
  base64Decode,
  base64Encode,
  buildAssetManifest,
  compileModuleRules,
  coupleWebSocket,
  createFetchMock,
  createHTTPReducers,
  createHTTPRevivers,
  decodeSitesKey,
  deserialiseRegExps,
  deserialiseSiteRegExps,
  encodeSitesKey,
  fetch,
  formatError,
  formatZodError,
  getAccessibleHosts,
  getAssetsBindingsNames,
  getCacheServiceName,
  getDefaultDevRegistryPath,
  getDirectSocketName,
  getEntrySocketHttpOptions,
  getFreshSourceMapSupport,
  getGlobalServices,
  getMiniflareObjectBindings,
  getNodeCompat,
  getPersistPath,
  getRootPath,
  getUserBindingServiceName,
  getWorkerRegistry,
  globsToRegExps,
  isDurableObjectStub,
  isFetcherFetch,
  isFileNotFoundError,
  isImagesInput,
  isR2ObjectWriteHttpMetadata,
  isSitesRequest,
  kCurrentWorker,
  kInspectorSocket,
  kUnsafeEphemeralUniqueKey,
  kVoid,
  launchBrowser,
  loadExternalPlugins,
  matchRoutes,
  maybeApply,
  maybeParseURL,
  mergeWorkerOptions,
  migrateDatabase,
  namespaceEntries,
  namespaceKeys,
  normaliseDurableObject,
  objectEntryWorker,
  parseRanges,
  parseRoutes,
  parseWithReadableStreams,
  parseWithRootPath,
  prefixError,
  prefixStream,
  processStackTrace,
  readPrefix,
  reduceError,
  remoteProxyClientWorker,
  sanitisePath,
  serialiseRegExps,
  serialiseSiteRegExps,
  serializeConfig,
  stringifyWithStreams,
  stripAnsi,
  structuredSerializableReducers,
  structuredSerializableRevivers,
  supportedCompatibilityDate,
  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.
   *)
*/
/*! 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
