#!/usr/bin/env node
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 __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// _prefix.js
var _path;
var init_prefix = __esm({
  "_prefix.js"() {
    _path = require("path");
    if (!global.__original_dirname) {
      global.__original_dirname = _path.dirname(process.execPath);
    }
  }
});

// node_modules/ms/index.js
var require_ms = __commonJS({
  "node_modules/ms/index.js"(exports2, module2) {
    init_prefix();
    var s = 1e3;
    var m = s * 60;
    var h = m * 60;
    var d = h * 24;
    var w = d * 7;
    var y = d * 365.25;
    module2.exports = function(val, options) {
      options = options || {};
      var type = typeof val;
      if (type === "string" && val.length > 0) {
        return parse(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 parse(str) {
      str = String(str);
      if (str.length > 100) {
        return;
      }
      var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
        str
      );
      if (!match) {
        return;
      }
      var n = parseFloat(match[1]);
      var type = (match[2] || "ms").toLowerCase();
      switch (type) {
        case "years":
        case "year":
        case "yrs":
        case "yr":
        case "y":
          return n * y;
        case "weeks":
        case "week":
        case "w":
          return n * w;
        case "days":
        case "day":
        case "d":
          return n * d;
        case "hours":
        case "hour":
        case "hrs":
        case "hr":
        case "h":
          return n * h;
        case "minutes":
        case "minute":
        case "mins":
        case "min":
        case "m":
          return n * m;
        case "seconds":
        case "second":
        case "secs":
        case "sec":
        case "s":
          return n * s;
        case "milliseconds":
        case "millisecond":
        case "msecs":
        case "msec":
        case "ms":
          return n;
        default:
          return void 0;
      }
    }
    function fmtShort(ms) {
      var msAbs = Math.abs(ms);
      if (msAbs >= d) {
        return Math.round(ms / d) + "d";
      }
      if (msAbs >= h) {
        return Math.round(ms / h) + "h";
      }
      if (msAbs >= m) {
        return Math.round(ms / m) + "m";
      }
      if (msAbs >= s) {
        return Math.round(ms / s) + "s";
      }
      return ms + "ms";
    }
    function fmtLong(ms) {
      var msAbs = Math.abs(ms);
      if (msAbs >= d) {
        return plural(ms, msAbs, d, "day");
      }
      if (msAbs >= h) {
        return plural(ms, msAbs, h, "hour");
      }
      if (msAbs >= m) {
        return plural(ms, msAbs, m, "minute");
      }
      if (msAbs >= s) {
        return plural(ms, msAbs, s, "second");
      }
      return ms + " ms";
    }
    function plural(ms, msAbs, n, name) {
      var isPlural = msAbs >= n * 1.5;
      return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
    }
  }
});

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

// node_modules/debug/src/browser.js
var require_browser = __commonJS({
  "node_modules/debug/src/browser.js"(exports2, module2) {
    init_prefix();
    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 m;
      return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
      typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
      // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
      typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
      typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
    }
    function formatArgs(args2) {
      args2[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args2[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff);
      if (!this.useColors) {
        return;
      }
      const c = "color: " + this.color;
      args2.splice(1, 0, c, "color: inherit");
      let index = 0;
      let lastC = 0;
      args2[0].replace(/%[a-zA-Z%]/g, (match) => {
        if (match === "%%") {
          return;
        }
        index++;
        if (match === "%c") {
          lastC = index;
        }
      });
      args2.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 r;
      try {
        r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG");
      } catch (error) {
      }
      if (!r && typeof process !== "undefined" && "env" in process) {
        r = process.env.DEBUG;
      }
      return r;
    }
    function localstorage() {
      try {
        return localStorage;
      } catch (error) {
      }
    }
    module2.exports = require_common()(exports2);
    var { formatters } = module2.exports;
    formatters.j = function(v) {
      try {
        return JSON.stringify(v);
      } catch (error) {
        return "[UnexpectedJSONParseError]: " + error.message;
      }
    };
  }
});

// node_modules/debug/src/node.js
var require_node = __commonJS({
  "node_modules/debug/src/node.js"(exports2, module2) {
    init_prefix();
    var tty = require("tty");
    var util = require("util");
    exports2.init = init;
    exports2.log = log;
    exports2.formatArgs = formatArgs;
    exports2.save = save;
    exports2.load = load;
    exports2.useColors = useColors;
    exports2.destroy = util.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 supportsColor = require("supports-color");
      if (supportsColor && (supportsColor.stderr || supportsColor).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, (_, 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) : tty.isatty(process.stderr.fd);
    }
    function formatArgs(args2) {
      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`;
        args2[0] = prefix + args2[0].split("\n").join("\n" + prefix);
        args2.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m");
      } else {
        args2[0] = getDate() + name + " " + args2[0];
      }
    }
    function getDate() {
      if (exports2.inspectOpts.hideDate) {
        return "";
      }
      return (/* @__PURE__ */ new Date()).toISOString() + " ";
    }
    function log(...args2) {
      return process.stderr.write(util.formatWithOptions(exports2.inspectOpts, ...args2) + "\n");
    }
    function save(namespaces) {
      if (namespaces) {
        process.env.DEBUG = namespaces;
      } else {
        delete process.env.DEBUG;
      }
    }
    function load() {
      return process.env.DEBUG;
    }
    function init(debug) {
      debug.inspectOpts = {};
      const keys = Object.keys(exports2.inspectOpts);
      for (let i = 0; i < keys.length; i++) {
        debug.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]];
      }
    }
    module2.exports = require_common()(exports2);
    var { formatters } = module2.exports;
    formatters.o = function(v) {
      this.inspectOpts.colors = this.useColors;
      return util.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
    };
    formatters.O = function(v) {
      this.inspectOpts.colors = this.useColors;
      return util.inspect(v, this.inspectOpts);
    };
  }
});

// node_modules/debug/src/index.js
var require_src = __commonJS({
  "node_modules/debug/src/index.js"(exports2, module2) {
    init_prefix();
    if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) {
      module2.exports = require_browser();
    } else {
      module2.exports = require_node();
    }
  }
});

// node_modules/deepmerge/dist/cjs.js
var require_cjs = __commonJS({
  "node_modules/deepmerge/dist/cjs.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var isMergeableObject = function isMergeableObject2(value) {
      return isNonNullObject(value) && !isSpecial(value);
    };
    function isNonNullObject(value) {
      return !!value && typeof value === "object";
    }
    function isSpecial(value) {
      var stringValue = Object.prototype.toString.call(value);
      return stringValue === "[object RegExp]" || stringValue === "[object Date]" || isReactElement(value);
    }
    var canUseSymbol = typeof Symbol === "function" && Symbol.for;
    var REACT_ELEMENT_TYPE = canUseSymbol ? /* @__PURE__ */ Symbol.for("react.element") : 60103;
    function isReactElement(value) {
      return value.$$typeof === REACT_ELEMENT_TYPE;
    }
    function emptyTarget(val) {
      return Array.isArray(val) ? [] : {};
    }
    function cloneUnlessOtherwiseSpecified(value, options) {
      return options.clone !== false && options.isMergeableObject(value) ? deepmerge(emptyTarget(value), value, options) : value;
    }
    function defaultArrayMerge(target, source, options) {
      return target.concat(source).map(function(element) {
        return cloneUnlessOtherwiseSpecified(element, options);
      });
    }
    function getMergeFunction(key, options) {
      if (!options.customMerge) {
        return deepmerge;
      }
      var customMerge = options.customMerge(key);
      return typeof customMerge === "function" ? customMerge : deepmerge;
    }
    function getEnumerableOwnPropertySymbols(target) {
      return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function(symbol) {
        return Object.propertyIsEnumerable.call(target, symbol);
      }) : [];
    }
    function getKeys(target) {
      return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target));
    }
    function propertyIsOnObject(object, property) {
      try {
        return property in object;
      } catch (_) {
        return false;
      }
    }
    function propertyIsUnsafe(target, key) {
      return propertyIsOnObject(target, key) && !(Object.hasOwnProperty.call(target, key) && Object.propertyIsEnumerable.call(target, key));
    }
    function mergeObject(target, source, options) {
      var destination = {};
      if (options.isMergeableObject(target)) {
        getKeys(target).forEach(function(key) {
          destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
        });
      }
      getKeys(source).forEach(function(key) {
        if (propertyIsUnsafe(target, key)) {
          return;
        }
        if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
          destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
        } else {
          destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
        }
      });
      return destination;
    }
    function deepmerge(target, source, options) {
      options = options || {};
      options.arrayMerge = options.arrayMerge || defaultArrayMerge;
      options.isMergeableObject = options.isMergeableObject || isMergeableObject;
      options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
      var sourceIsArray = Array.isArray(source);
      var targetIsArray = Array.isArray(target);
      var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
      if (!sourceAndTargetTypesMatch) {
        return cloneUnlessOtherwiseSpecified(source, options);
      } else if (sourceIsArray) {
        return options.arrayMerge(target, source, options);
      } else {
        return mergeObject(target, source, options);
      }
    }
    deepmerge.all = function deepmergeAll(array, options) {
      if (!Array.isArray(array)) {
        throw new Error("first argument should be an array");
      }
      return array.reduce(function(prev, next) {
        return deepmerge(prev, next, options);
      }, {});
    };
    var deepmerge_1 = deepmerge;
    module2.exports = deepmerge_1;
  }
});

// node_modules/puppeteer-core/lib/cjs/third_party/rxjs/rxjs.js
var require_rxjs = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/third_party/rxjs/rxjs.js"(exports2) {
    "use strict";
    init_prefix();
    var __getOwnPropNames2 = Object.getOwnPropertyNames;
    var __commonJS2 = (cb, mod) => function __require() {
      return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
    };
    var require_isFunction = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/isFunction.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.isFunction = void 0;
        function isFunction2(value) {
          return typeof value === "function";
        }
        exports22.isFunction = isFunction2;
      }
    });
    var require_createErrorClass = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/createErrorClass.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.createErrorClass = void 0;
        function createErrorClass(createImpl) {
          var _super = function(instance) {
            Error.call(instance);
            instance.stack = new Error().stack;
          };
          var ctorFunc = createImpl(_super);
          ctorFunc.prototype = Object.create(Error.prototype);
          ctorFunc.prototype.constructor = ctorFunc;
          return ctorFunc;
        }
        exports22.createErrorClass = createErrorClass;
      }
    });
    var require_UnsubscriptionError = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/UnsubscriptionError.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.UnsubscriptionError = void 0;
        var createErrorClass_1 = require_createErrorClass();
        exports22.UnsubscriptionError = createErrorClass_1.createErrorClass(function(_super) {
          return function UnsubscriptionErrorImpl(errors) {
            _super(this);
            this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function(err, i) {
              return i + 1 + ") " + err.toString();
            }).join("\n  ") : "";
            this.name = "UnsubscriptionError";
            this.errors = errors;
          };
        });
      }
    });
    var require_arrRemove = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/arrRemove.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.arrRemove = void 0;
        function arrRemove(arr, item) {
          if (arr) {
            var index = arr.indexOf(item);
            0 <= index && arr.splice(index, 1);
          }
        }
        exports22.arrRemove = arrRemove;
      }
    });
    var require_Subscription = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/Subscription.js"(exports22) {
        "use strict";
        var __values2 = exports22 && exports22.__values || function(o) {
          var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
          if (m) return m.call(o);
          if (o && typeof o.length === "number") return {
            next: function() {
              if (o && i >= o.length) o = void 0;
              return { value: o && o[i++], done: !o };
            }
          };
          throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
        };
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.isSubscription = exports22.EMPTY_SUBSCRIPTION = exports22.Subscription = void 0;
        var isFunction_1 = require_isFunction();
        var UnsubscriptionError_1 = require_UnsubscriptionError();
        var arrRemove_1 = require_arrRemove();
        var Subscription = (function() {
          function Subscription2(initialTeardown) {
            this.initialTeardown = initialTeardown;
            this.closed = false;
            this._parentage = null;
            this._finalizers = null;
          }
          Subscription2.prototype.unsubscribe = function() {
            var e_1, _a2, e_2, _b2;
            var errors;
            if (!this.closed) {
              this.closed = true;
              var _parentage = this._parentage;
              if (_parentage) {
                this._parentage = null;
                if (Array.isArray(_parentage)) {
                  try {
                    for (var _parentage_1 = __values2(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
                      var parent_1 = _parentage_1_1.value;
                      parent_1.remove(this);
                    }
                  } catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                  } finally {
                    try {
                      if (_parentage_1_1 && !_parentage_1_1.done && (_a2 = _parentage_1.return)) _a2.call(_parentage_1);
                    } finally {
                      if (e_1) throw e_1.error;
                    }
                  }
                } else {
                  _parentage.remove(this);
                }
              }
              var initialFinalizer = this.initialTeardown;
              if (isFunction_1.isFunction(initialFinalizer)) {
                try {
                  initialFinalizer();
                } catch (e) {
                  errors = e instanceof UnsubscriptionError_1.UnsubscriptionError ? e.errors : [e];
                }
              }
              var _finalizers = this._finalizers;
              if (_finalizers) {
                this._finalizers = null;
                try {
                  for (var _finalizers_1 = __values2(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
                    var finalizer = _finalizers_1_1.value;
                    try {
                      execFinalizer(finalizer);
                    } catch (err) {
                      errors = errors !== null && errors !== void 0 ? errors : [];
                      if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
                        errors = __spreadArray2(__spreadArray2([], __read2(errors)), __read2(err.errors));
                      } else {
                        errors.push(err);
                      }
                    }
                  }
                } catch (e_2_1) {
                  e_2 = { error: e_2_1 };
                } finally {
                  try {
                    if (_finalizers_1_1 && !_finalizers_1_1.done && (_b2 = _finalizers_1.return)) _b2.call(_finalizers_1);
                  } finally {
                    if (e_2) throw e_2.error;
                  }
                }
              }
              if (errors) {
                throw new UnsubscriptionError_1.UnsubscriptionError(errors);
              }
            }
          };
          Subscription2.prototype.add = function(teardown) {
            var _a2;
            if (teardown && teardown !== this) {
              if (this.closed) {
                execFinalizer(teardown);
              } else {
                if (teardown instanceof Subscription2) {
                  if (teardown.closed || teardown._hasParent(this)) {
                    return;
                  }
                  teardown._addParent(this);
                }
                (this._finalizers = (_a2 = this._finalizers) !== null && _a2 !== void 0 ? _a2 : []).push(teardown);
              }
            }
          };
          Subscription2.prototype._hasParent = function(parent) {
            var _parentage = this._parentage;
            return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
          };
          Subscription2.prototype._addParent = function(parent) {
            var _parentage = this._parentage;
            this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
          };
          Subscription2.prototype._removeParent = function(parent) {
            var _parentage = this._parentage;
            if (_parentage === parent) {
              this._parentage = null;
            } else if (Array.isArray(_parentage)) {
              arrRemove_1.arrRemove(_parentage, parent);
            }
          };
          Subscription2.prototype.remove = function(teardown) {
            var _finalizers = this._finalizers;
            _finalizers && arrRemove_1.arrRemove(_finalizers, teardown);
            if (teardown instanceof Subscription2) {
              teardown._removeParent(this);
            }
          };
          Subscription2.EMPTY = (function() {
            var empty = new Subscription2();
            empty.closed = true;
            return empty;
          })();
          return Subscription2;
        })();
        exports22.Subscription = Subscription;
        exports22.EMPTY_SUBSCRIPTION = Subscription.EMPTY;
        function isSubscription(value) {
          return value instanceof Subscription || value && "closed" in value && isFunction_1.isFunction(value.remove) && isFunction_1.isFunction(value.add) && isFunction_1.isFunction(value.unsubscribe);
        }
        exports22.isSubscription = isSubscription;
        function execFinalizer(finalizer) {
          if (isFunction_1.isFunction(finalizer)) {
            finalizer();
          } else {
            finalizer.unsubscribe();
          }
        }
      }
    });
    var require_config = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/config.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.config = void 0;
        exports22.config = {
          onUnhandledError: null,
          onStoppedNotification: null,
          Promise: void 0,
          useDeprecatedSynchronousErrorHandling: false,
          useDeprecatedNextContext: false
        };
      }
    });
    var require_timeoutProvider = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/timeoutProvider.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.timeoutProvider = void 0;
        exports22.timeoutProvider = {
          setTimeout: function(handler, timeout) {
            var args2 = [];
            for (var _i = 2; _i < arguments.length; _i++) {
              args2[_i - 2] = arguments[_i];
            }
            var delegate = exports22.timeoutProvider.delegate;
            if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {
              return delegate.setTimeout.apply(delegate, __spreadArray2([handler, timeout], __read2(args2)));
            }
            return setTimeout.apply(void 0, __spreadArray2([handler, timeout], __read2(args2)));
          },
          clearTimeout: function(handle) {
            var delegate = exports22.timeoutProvider.delegate;
            return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);
          },
          delegate: void 0
        };
      }
    });
    var require_reportUnhandledError = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/reportUnhandledError.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.reportUnhandledError = void 0;
        var config_1 = require_config();
        var timeoutProvider_1 = require_timeoutProvider();
        function reportUnhandledError(err) {
          timeoutProvider_1.timeoutProvider.setTimeout(function() {
            var onUnhandledError = config_1.config.onUnhandledError;
            if (onUnhandledError) {
              onUnhandledError(err);
            } else {
              throw err;
            }
          });
        }
        exports22.reportUnhandledError = reportUnhandledError;
      }
    });
    var require_noop = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/noop.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.noop = void 0;
        function noop() {
        }
        exports22.noop = noop;
      }
    });
    var require_NotificationFactories = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/NotificationFactories.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.createNotification = exports22.nextNotification = exports22.errorNotification = exports22.COMPLETE_NOTIFICATION = void 0;
        exports22.COMPLETE_NOTIFICATION = (function() {
          return createNotification("C", void 0, void 0);
        })();
        function errorNotification(error) {
          return createNotification("E", void 0, error);
        }
        exports22.errorNotification = errorNotification;
        function nextNotification(value) {
          return createNotification("N", value, void 0);
        }
        exports22.nextNotification = nextNotification;
        function createNotification(kind, value, error) {
          return {
            kind,
            value,
            error
          };
        }
        exports22.createNotification = createNotification;
      }
    });
    var require_errorContext = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/errorContext.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.captureError = exports22.errorContext = void 0;
        var config_1 = require_config();
        var context = null;
        function errorContext(cb) {
          if (config_1.config.useDeprecatedSynchronousErrorHandling) {
            var isRoot = !context;
            if (isRoot) {
              context = { errorThrown: false, error: null };
            }
            cb();
            if (isRoot) {
              var _a2 = context, errorThrown = _a2.errorThrown, error = _a2.error;
              context = null;
              if (errorThrown) {
                throw error;
              }
            }
          } else {
            cb();
          }
        }
        exports22.errorContext = errorContext;
        function captureError(err) {
          if (config_1.config.useDeprecatedSynchronousErrorHandling && context) {
            context.errorThrown = true;
            context.error = err;
          }
        }
        exports22.captureError = captureError;
      }
    });
    var require_Subscriber = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/Subscriber.js"(exports22) {
        "use strict";
        var __extends2 = exports22 && exports22.__extends || /* @__PURE__ */ (function() {
          var extendStatics2 = function(d, b) {
            extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
              d2.__proto__ = b2;
            } || function(d2, b2) {
              for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
            };
            return extendStatics2(d, b);
          };
          return function(d, b) {
            if (typeof b !== "function" && b !== null)
              throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
            extendStatics2(d, b);
            function __() {
              this.constructor = d;
            }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
        })();
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.EMPTY_OBSERVER = exports22.SafeSubscriber = exports22.Subscriber = void 0;
        var isFunction_1 = require_isFunction();
        var Subscription_1 = require_Subscription();
        var config_1 = require_config();
        var reportUnhandledError_1 = require_reportUnhandledError();
        var noop_1 = require_noop();
        var NotificationFactories_1 = require_NotificationFactories();
        var timeoutProvider_1 = require_timeoutProvider();
        var errorContext_1 = require_errorContext();
        var Subscriber = (function(_super) {
          __extends2(Subscriber2, _super);
          function Subscriber2(destination) {
            var _this = _super.call(this) || this;
            _this.isStopped = false;
            if (destination) {
              _this.destination = destination;
              if (Subscription_1.isSubscription(destination)) {
                destination.add(_this);
              }
            } else {
              _this.destination = exports22.EMPTY_OBSERVER;
            }
            return _this;
          }
          Subscriber2.create = function(next, error, complete) {
            return new SafeSubscriber(next, error, complete);
          };
          Subscriber2.prototype.next = function(value) {
            if (this.isStopped) {
              handleStoppedNotification(NotificationFactories_1.nextNotification(value), this);
            } else {
              this._next(value);
            }
          };
          Subscriber2.prototype.error = function(err) {
            if (this.isStopped) {
              handleStoppedNotification(NotificationFactories_1.errorNotification(err), this);
            } else {
              this.isStopped = true;
              this._error(err);
            }
          };
          Subscriber2.prototype.complete = function() {
            if (this.isStopped) {
              handleStoppedNotification(NotificationFactories_1.COMPLETE_NOTIFICATION, this);
            } else {
              this.isStopped = true;
              this._complete();
            }
          };
          Subscriber2.prototype.unsubscribe = function() {
            if (!this.closed) {
              this.isStopped = true;
              _super.prototype.unsubscribe.call(this);
              this.destination = null;
            }
          };
          Subscriber2.prototype._next = function(value) {
            this.destination.next(value);
          };
          Subscriber2.prototype._error = function(err) {
            try {
              this.destination.error(err);
            } finally {
              this.unsubscribe();
            }
          };
          Subscriber2.prototype._complete = function() {
            try {
              this.destination.complete();
            } finally {
              this.unsubscribe();
            }
          };
          return Subscriber2;
        })(Subscription_1.Subscription);
        exports22.Subscriber = Subscriber;
        var _bind = Function.prototype.bind;
        function bind(fn, thisArg) {
          return _bind.call(fn, thisArg);
        }
        var ConsumerObserver = (function() {
          function ConsumerObserver2(partialObserver) {
            this.partialObserver = partialObserver;
          }
          ConsumerObserver2.prototype.next = function(value) {
            var partialObserver = this.partialObserver;
            if (partialObserver.next) {
              try {
                partialObserver.next(value);
              } catch (error) {
                handleUnhandledError(error);
              }
            }
          };
          ConsumerObserver2.prototype.error = function(err) {
            var partialObserver = this.partialObserver;
            if (partialObserver.error) {
              try {
                partialObserver.error(err);
              } catch (error) {
                handleUnhandledError(error);
              }
            } else {
              handleUnhandledError(err);
            }
          };
          ConsumerObserver2.prototype.complete = function() {
            var partialObserver = this.partialObserver;
            if (partialObserver.complete) {
              try {
                partialObserver.complete();
              } catch (error) {
                handleUnhandledError(error);
              }
            }
          };
          return ConsumerObserver2;
        })();
        var SafeSubscriber = (function(_super) {
          __extends2(SafeSubscriber2, _super);
          function SafeSubscriber2(observerOrNext, error, complete) {
            var _this = _super.call(this) || this;
            var partialObserver;
            if (isFunction_1.isFunction(observerOrNext) || !observerOrNext) {
              partialObserver = {
                next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : void 0,
                error: error !== null && error !== void 0 ? error : void 0,
                complete: complete !== null && complete !== void 0 ? complete : void 0
              };
            } else {
              var context_1;
              if (_this && config_1.config.useDeprecatedNextContext) {
                context_1 = Object.create(observerOrNext);
                context_1.unsubscribe = function() {
                  return _this.unsubscribe();
                };
                partialObserver = {
                  next: observerOrNext.next && bind(observerOrNext.next, context_1),
                  error: observerOrNext.error && bind(observerOrNext.error, context_1),
                  complete: observerOrNext.complete && bind(observerOrNext.complete, context_1)
                };
              } else {
                partialObserver = observerOrNext;
              }
            }
            _this.destination = new ConsumerObserver(partialObserver);
            return _this;
          }
          return SafeSubscriber2;
        })(Subscriber);
        exports22.SafeSubscriber = SafeSubscriber;
        function handleUnhandledError(error) {
          if (config_1.config.useDeprecatedSynchronousErrorHandling) {
            errorContext_1.captureError(error);
          } else {
            reportUnhandledError_1.reportUnhandledError(error);
          }
        }
        function defaultErrorHandler(err) {
          throw err;
        }
        function handleStoppedNotification(notification, subscriber) {
          var onStoppedNotification = config_1.config.onStoppedNotification;
          onStoppedNotification && timeoutProvider_1.timeoutProvider.setTimeout(function() {
            return onStoppedNotification(notification, subscriber);
          });
        }
        exports22.EMPTY_OBSERVER = {
          closed: true,
          next: noop_1.noop,
          error: defaultErrorHandler,
          complete: noop_1.noop
        };
      }
    });
    var require_observable = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/symbol/observable.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.observable = void 0;
        exports22.observable = (function() {
          return typeof Symbol === "function" && Symbol.observable || "@@observable";
        })();
      }
    });
    var require_identity = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/identity.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.identity = void 0;
        function identity(x) {
          return x;
        }
        exports22.identity = identity;
      }
    });
    var require_pipe = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/pipe.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.pipeFromArray = exports22.pipe = void 0;
        var identity_1 = require_identity();
        function pipe() {
          var fns = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            fns[_i] = arguments[_i];
          }
          return pipeFromArray(fns);
        }
        exports22.pipe = pipe;
        function pipeFromArray(fns) {
          if (fns.length === 0) {
            return identity_1.identity;
          }
          if (fns.length === 1) {
            return fns[0];
          }
          return function piped(input) {
            return fns.reduce(function(prev, fn) {
              return fn(prev);
            }, input);
          };
        }
        exports22.pipeFromArray = pipeFromArray;
      }
    });
    var require_Observable = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/Observable.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.Observable = void 0;
        var Subscriber_1 = require_Subscriber();
        var Subscription_1 = require_Subscription();
        var observable_1 = require_observable();
        var pipe_1 = require_pipe();
        var config_1 = require_config();
        var isFunction_1 = require_isFunction();
        var errorContext_1 = require_errorContext();
        var Observable = (function() {
          function Observable2(subscribe) {
            if (subscribe) {
              this._subscribe = subscribe;
            }
          }
          Observable2.prototype.lift = function(operator) {
            var observable = new Observable2();
            observable.source = this;
            observable.operator = operator;
            return observable;
          };
          Observable2.prototype.subscribe = function(observerOrNext, error, complete) {
            var _this = this;
            var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new Subscriber_1.SafeSubscriber(observerOrNext, error, complete);
            errorContext_1.errorContext(function() {
              var _a2 = _this, operator = _a2.operator, source = _a2.source;
              subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber));
            });
            return subscriber;
          };
          Observable2.prototype._trySubscribe = function(sink) {
            try {
              return this._subscribe(sink);
            } catch (err) {
              sink.error(err);
            }
          };
          Observable2.prototype.forEach = function(next, promiseCtor) {
            var _this = this;
            promiseCtor = getPromiseCtor(promiseCtor);
            return new promiseCtor(function(resolve5, reject) {
              var subscriber = new Subscriber_1.SafeSubscriber({
                next: function(value) {
                  try {
                    next(value);
                  } catch (err) {
                    reject(err);
                    subscriber.unsubscribe();
                  }
                },
                error: reject,
                complete: resolve5
              });
              _this.subscribe(subscriber);
            });
          };
          Observable2.prototype._subscribe = function(subscriber) {
            var _a2;
            return (_a2 = this.source) === null || _a2 === void 0 ? void 0 : _a2.subscribe(subscriber);
          };
          Observable2.prototype[observable_1.observable] = function() {
            return this;
          };
          Observable2.prototype.pipe = function() {
            var operations = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              operations[_i] = arguments[_i];
            }
            return pipe_1.pipeFromArray(operations)(this);
          };
          Observable2.prototype.toPromise = function(promiseCtor) {
            var _this = this;
            promiseCtor = getPromiseCtor(promiseCtor);
            return new promiseCtor(function(resolve5, reject) {
              var value;
              _this.subscribe(function(x) {
                return value = x;
              }, function(err) {
                return reject(err);
              }, function() {
                return resolve5(value);
              });
            });
          };
          Observable2.create = function(subscribe) {
            return new Observable2(subscribe);
          };
          return Observable2;
        })();
        exports22.Observable = Observable;
        function getPromiseCtor(promiseCtor) {
          var _a2;
          return (_a2 = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config_1.config.Promise) !== null && _a2 !== void 0 ? _a2 : Promise;
        }
        function isObserver(value) {
          return value && isFunction_1.isFunction(value.next) && isFunction_1.isFunction(value.error) && isFunction_1.isFunction(value.complete);
        }
        function isSubscriber(value) {
          return value && value instanceof Subscriber_1.Subscriber || isObserver(value) && Subscription_1.isSubscription(value);
        }
      }
    });
    var require_lift = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/lift.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.operate = exports22.hasLift = void 0;
        var isFunction_1 = require_isFunction();
        function hasLift(source) {
          return isFunction_1.isFunction(source === null || source === void 0 ? void 0 : source.lift);
        }
        exports22.hasLift = hasLift;
        function operate(init) {
          return function(source) {
            if (hasLift(source)) {
              return source.lift(function(liftedSource) {
                try {
                  return init(liftedSource, this);
                } catch (err) {
                  this.error(err);
                }
              });
            }
            throw new TypeError("Unable to lift unknown Observable type");
          };
        }
        exports22.operate = operate;
      }
    });
    var require_OperatorSubscriber = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/OperatorSubscriber.js"(exports22) {
        "use strict";
        var __extends2 = exports22 && exports22.__extends || /* @__PURE__ */ (function() {
          var extendStatics2 = function(d, b) {
            extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
              d2.__proto__ = b2;
            } || function(d2, b2) {
              for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
            };
            return extendStatics2(d, b);
          };
          return function(d, b) {
            if (typeof b !== "function" && b !== null)
              throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
            extendStatics2(d, b);
            function __() {
              this.constructor = d;
            }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
        })();
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.OperatorSubscriber = exports22.createOperatorSubscriber = void 0;
        var Subscriber_1 = require_Subscriber();
        function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
          return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
        }
        exports22.createOperatorSubscriber = createOperatorSubscriber;
        var OperatorSubscriber = (function(_super) {
          __extends2(OperatorSubscriber2, _super);
          function OperatorSubscriber2(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
            var _this = _super.call(this, destination) || this;
            _this.onFinalize = onFinalize;
            _this.shouldUnsubscribe = shouldUnsubscribe;
            _this._next = onNext ? function(value) {
              try {
                onNext(value);
              } catch (err) {
                destination.error(err);
              }
            } : _super.prototype._next;
            _this._error = onError ? function(err) {
              try {
                onError(err);
              } catch (err2) {
                destination.error(err2);
              } finally {
                this.unsubscribe();
              }
            } : _super.prototype._error;
            _this._complete = onComplete ? function() {
              try {
                onComplete();
              } catch (err) {
                destination.error(err);
              } finally {
                this.unsubscribe();
              }
            } : _super.prototype._complete;
            return _this;
          }
          OperatorSubscriber2.prototype.unsubscribe = function() {
            var _a2;
            if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
              var closed_1 = this.closed;
              _super.prototype.unsubscribe.call(this);
              !closed_1 && ((_a2 = this.onFinalize) === null || _a2 === void 0 ? void 0 : _a2.call(this));
            }
          };
          return OperatorSubscriber2;
        })(Subscriber_1.Subscriber);
        exports22.OperatorSubscriber = OperatorSubscriber;
      }
    });
    var require_refCount = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/refCount.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.refCount = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function refCount() {
          return lift_1.operate(function(source, subscriber) {
            var connection = null;
            source._refCount++;
            var refCounter = OperatorSubscriber_1.createOperatorSubscriber(subscriber, void 0, void 0, void 0, function() {
              if (!source || source._refCount <= 0 || 0 < --source._refCount) {
                connection = null;
                return;
              }
              var sharedConnection = source._connection;
              var conn = connection;
              connection = null;
              if (sharedConnection && (!conn || sharedConnection === conn)) {
                sharedConnection.unsubscribe();
              }
              subscriber.unsubscribe();
            });
            source.subscribe(refCounter);
            if (!refCounter.closed) {
              connection = source.connect();
            }
          });
        }
        exports22.refCount = refCount;
      }
    });
    var require_ConnectableObservable = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/ConnectableObservable.js"(exports22) {
        "use strict";
        var __extends2 = exports22 && exports22.__extends || /* @__PURE__ */ (function() {
          var extendStatics2 = function(d, b) {
            extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
              d2.__proto__ = b2;
            } || function(d2, b2) {
              for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
            };
            return extendStatics2(d, b);
          };
          return function(d, b) {
            if (typeof b !== "function" && b !== null)
              throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
            extendStatics2(d, b);
            function __() {
              this.constructor = d;
            }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
        })();
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.ConnectableObservable = void 0;
        var Observable_1 = require_Observable();
        var Subscription_1 = require_Subscription();
        var refCount_1 = require_refCount();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var lift_1 = require_lift();
        var ConnectableObservable = (function(_super) {
          __extends2(ConnectableObservable2, _super);
          function ConnectableObservable2(source, subjectFactory) {
            var _this = _super.call(this) || this;
            _this.source = source;
            _this.subjectFactory = subjectFactory;
            _this._subject = null;
            _this._refCount = 0;
            _this._connection = null;
            if (lift_1.hasLift(source)) {
              _this.lift = source.lift;
            }
            return _this;
          }
          ConnectableObservable2.prototype._subscribe = function(subscriber) {
            return this.getSubject().subscribe(subscriber);
          };
          ConnectableObservable2.prototype.getSubject = function() {
            var subject = this._subject;
            if (!subject || subject.isStopped) {
              this._subject = this.subjectFactory();
            }
            return this._subject;
          };
          ConnectableObservable2.prototype._teardown = function() {
            this._refCount = 0;
            var _connection = this._connection;
            this._subject = this._connection = null;
            _connection === null || _connection === void 0 ? void 0 : _connection.unsubscribe();
          };
          ConnectableObservable2.prototype.connect = function() {
            var _this = this;
            var connection = this._connection;
            if (!connection) {
              connection = this._connection = new Subscription_1.Subscription();
              var subject_1 = this.getSubject();
              connection.add(this.source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subject_1, void 0, function() {
                _this._teardown();
                subject_1.complete();
              }, function(err) {
                _this._teardown();
                subject_1.error(err);
              }, function() {
                return _this._teardown();
              })));
              if (connection.closed) {
                this._connection = null;
                connection = Subscription_1.Subscription.EMPTY;
              }
            }
            return connection;
          };
          ConnectableObservable2.prototype.refCount = function() {
            return refCount_1.refCount()(this);
          };
          return ConnectableObservable2;
        })(Observable_1.Observable);
        exports22.ConnectableObservable = ConnectableObservable;
      }
    });
    var require_performanceTimestampProvider = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/performanceTimestampProvider.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.performanceTimestampProvider = void 0;
        exports22.performanceTimestampProvider = {
          now: function() {
            return (exports22.performanceTimestampProvider.delegate || performance).now();
          },
          delegate: void 0
        };
      }
    });
    var require_animationFrameProvider = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/animationFrameProvider.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.animationFrameProvider = void 0;
        var Subscription_1 = require_Subscription();
        exports22.animationFrameProvider = {
          schedule: function(callback) {
            var request = requestAnimationFrame;
            var cancel = cancelAnimationFrame;
            var delegate = exports22.animationFrameProvider.delegate;
            if (delegate) {
              request = delegate.requestAnimationFrame;
              cancel = delegate.cancelAnimationFrame;
            }
            var handle = request(function(timestamp) {
              cancel = void 0;
              callback(timestamp);
            });
            return new Subscription_1.Subscription(function() {
              return cancel === null || cancel === void 0 ? void 0 : cancel(handle);
            });
          },
          requestAnimationFrame: function() {
            var args2 = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              args2[_i] = arguments[_i];
            }
            var delegate = exports22.animationFrameProvider.delegate;
            return ((delegate === null || delegate === void 0 ? void 0 : delegate.requestAnimationFrame) || requestAnimationFrame).apply(void 0, __spreadArray2([], __read2(args2)));
          },
          cancelAnimationFrame: function() {
            var args2 = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              args2[_i] = arguments[_i];
            }
            var delegate = exports22.animationFrameProvider.delegate;
            return ((delegate === null || delegate === void 0 ? void 0 : delegate.cancelAnimationFrame) || cancelAnimationFrame).apply(void 0, __spreadArray2([], __read2(args2)));
          },
          delegate: void 0
        };
      }
    });
    var require_animationFrames = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/dom/animationFrames.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.animationFrames = void 0;
        var Observable_1 = require_Observable();
        var performanceTimestampProvider_1 = require_performanceTimestampProvider();
        var animationFrameProvider_1 = require_animationFrameProvider();
        function animationFrames(timestampProvider) {
          return timestampProvider ? animationFramesFactory(timestampProvider) : DEFAULT_ANIMATION_FRAMES;
        }
        exports22.animationFrames = animationFrames;
        function animationFramesFactory(timestampProvider) {
          return new Observable_1.Observable(function(subscriber) {
            var provider = timestampProvider || performanceTimestampProvider_1.performanceTimestampProvider;
            var start = provider.now();
            var id = 0;
            var run = function() {
              if (!subscriber.closed) {
                id = animationFrameProvider_1.animationFrameProvider.requestAnimationFrame(function(timestamp) {
                  id = 0;
                  var now = provider.now();
                  subscriber.next({
                    timestamp: timestampProvider ? now : timestamp,
                    elapsed: now - start
                  });
                  run();
                });
              }
            };
            run();
            return function() {
              if (id) {
                animationFrameProvider_1.animationFrameProvider.cancelAnimationFrame(id);
              }
            };
          });
        }
        var DEFAULT_ANIMATION_FRAMES = animationFramesFactory();
      }
    });
    var require_ObjectUnsubscribedError = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/ObjectUnsubscribedError.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.ObjectUnsubscribedError = void 0;
        var createErrorClass_1 = require_createErrorClass();
        exports22.ObjectUnsubscribedError = createErrorClass_1.createErrorClass(function(_super) {
          return function ObjectUnsubscribedErrorImpl() {
            _super(this);
            this.name = "ObjectUnsubscribedError";
            this.message = "object unsubscribed";
          };
        });
      }
    });
    var require_Subject = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/Subject.js"(exports22) {
        "use strict";
        var __extends2 = exports22 && exports22.__extends || /* @__PURE__ */ (function() {
          var extendStatics2 = function(d, b) {
            extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
              d2.__proto__ = b2;
            } || function(d2, b2) {
              for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
            };
            return extendStatics2(d, b);
          };
          return function(d, b) {
            if (typeof b !== "function" && b !== null)
              throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
            extendStatics2(d, b);
            function __() {
              this.constructor = d;
            }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
        })();
        var __values2 = exports22 && exports22.__values || function(o) {
          var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
          if (m) return m.call(o);
          if (o && typeof o.length === "number") return {
            next: function() {
              if (o && i >= o.length) o = void 0;
              return { value: o && o[i++], done: !o };
            }
          };
          throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.AnonymousSubject = exports22.Subject = void 0;
        var Observable_1 = require_Observable();
        var Subscription_1 = require_Subscription();
        var ObjectUnsubscribedError_1 = require_ObjectUnsubscribedError();
        var arrRemove_1 = require_arrRemove();
        var errorContext_1 = require_errorContext();
        var Subject = (function(_super) {
          __extends2(Subject2, _super);
          function Subject2() {
            var _this = _super.call(this) || this;
            _this.closed = false;
            _this.currentObservers = null;
            _this.observers = [];
            _this.isStopped = false;
            _this.hasError = false;
            _this.thrownError = null;
            return _this;
          }
          Subject2.prototype.lift = function(operator) {
            var subject = new AnonymousSubject(this, this);
            subject.operator = operator;
            return subject;
          };
          Subject2.prototype._throwIfClosed = function() {
            if (this.closed) {
              throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
            }
          };
          Subject2.prototype.next = function(value) {
            var _this = this;
            errorContext_1.errorContext(function() {
              var e_1, _a2;
              _this._throwIfClosed();
              if (!_this.isStopped) {
                if (!_this.currentObservers) {
                  _this.currentObservers = Array.from(_this.observers);
                }
                try {
                  for (var _b2 = __values2(_this.currentObservers), _c2 = _b2.next(); !_c2.done; _c2 = _b2.next()) {
                    var observer = _c2.value;
                    observer.next(value);
                  }
                } catch (e_1_1) {
                  e_1 = { error: e_1_1 };
                } finally {
                  try {
                    if (_c2 && !_c2.done && (_a2 = _b2.return)) _a2.call(_b2);
                  } finally {
                    if (e_1) throw e_1.error;
                  }
                }
              }
            });
          };
          Subject2.prototype.error = function(err) {
            var _this = this;
            errorContext_1.errorContext(function() {
              _this._throwIfClosed();
              if (!_this.isStopped) {
                _this.hasError = _this.isStopped = true;
                _this.thrownError = err;
                var observers = _this.observers;
                while (observers.length) {
                  observers.shift().error(err);
                }
              }
            });
          };
          Subject2.prototype.complete = function() {
            var _this = this;
            errorContext_1.errorContext(function() {
              _this._throwIfClosed();
              if (!_this.isStopped) {
                _this.isStopped = true;
                var observers = _this.observers;
                while (observers.length) {
                  observers.shift().complete();
                }
              }
            });
          };
          Subject2.prototype.unsubscribe = function() {
            this.isStopped = this.closed = true;
            this.observers = this.currentObservers = null;
          };
          Object.defineProperty(Subject2.prototype, "observed", {
            get: function() {
              var _a2;
              return ((_a2 = this.observers) === null || _a2 === void 0 ? void 0 : _a2.length) > 0;
            },
            enumerable: false,
            configurable: true
          });
          Subject2.prototype._trySubscribe = function(subscriber) {
            this._throwIfClosed();
            return _super.prototype._trySubscribe.call(this, subscriber);
          };
          Subject2.prototype._subscribe = function(subscriber) {
            this._throwIfClosed();
            this._checkFinalizedStatuses(subscriber);
            return this._innerSubscribe(subscriber);
          };
          Subject2.prototype._innerSubscribe = function(subscriber) {
            var _this = this;
            var _a2 = this, hasError = _a2.hasError, isStopped = _a2.isStopped, observers = _a2.observers;
            if (hasError || isStopped) {
              return Subscription_1.EMPTY_SUBSCRIPTION;
            }
            this.currentObservers = null;
            observers.push(subscriber);
            return new Subscription_1.Subscription(function() {
              _this.currentObservers = null;
              arrRemove_1.arrRemove(observers, subscriber);
            });
          };
          Subject2.prototype._checkFinalizedStatuses = function(subscriber) {
            var _a2 = this, hasError = _a2.hasError, thrownError = _a2.thrownError, isStopped = _a2.isStopped;
            if (hasError) {
              subscriber.error(thrownError);
            } else if (isStopped) {
              subscriber.complete();
            }
          };
          Subject2.prototype.asObservable = function() {
            var observable = new Observable_1.Observable();
            observable.source = this;
            return observable;
          };
          Subject2.create = function(destination, source) {
            return new AnonymousSubject(destination, source);
          };
          return Subject2;
        })(Observable_1.Observable);
        exports22.Subject = Subject;
        var AnonymousSubject = (function(_super) {
          __extends2(AnonymousSubject2, _super);
          function AnonymousSubject2(destination, source) {
            var _this = _super.call(this) || this;
            _this.destination = destination;
            _this.source = source;
            return _this;
          }
          AnonymousSubject2.prototype.next = function(value) {
            var _a2, _b2;
            (_b2 = (_a2 = this.destination) === null || _a2 === void 0 ? void 0 : _a2.next) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, value);
          };
          AnonymousSubject2.prototype.error = function(err) {
            var _a2, _b2;
            (_b2 = (_a2 = this.destination) === null || _a2 === void 0 ? void 0 : _a2.error) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, err);
          };
          AnonymousSubject2.prototype.complete = function() {
            var _a2, _b2;
            (_b2 = (_a2 = this.destination) === null || _a2 === void 0 ? void 0 : _a2.complete) === null || _b2 === void 0 ? void 0 : _b2.call(_a2);
          };
          AnonymousSubject2.prototype._subscribe = function(subscriber) {
            var _a2, _b2;
            return (_b2 = (_a2 = this.source) === null || _a2 === void 0 ? void 0 : _a2.subscribe(subscriber)) !== null && _b2 !== void 0 ? _b2 : Subscription_1.EMPTY_SUBSCRIPTION;
          };
          return AnonymousSubject2;
        })(Subject);
        exports22.AnonymousSubject = AnonymousSubject;
      }
    });
    var require_BehaviorSubject = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/BehaviorSubject.js"(exports22) {
        "use strict";
        var __extends2 = exports22 && exports22.__extends || /* @__PURE__ */ (function() {
          var extendStatics2 = function(d, b) {
            extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
              d2.__proto__ = b2;
            } || function(d2, b2) {
              for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
            };
            return extendStatics2(d, b);
          };
          return function(d, b) {
            if (typeof b !== "function" && b !== null)
              throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
            extendStatics2(d, b);
            function __() {
              this.constructor = d;
            }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
        })();
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.BehaviorSubject = void 0;
        var Subject_1 = require_Subject();
        var BehaviorSubject = (function(_super) {
          __extends2(BehaviorSubject2, _super);
          function BehaviorSubject2(_value) {
            var _this = _super.call(this) || this;
            _this._value = _value;
            return _this;
          }
          Object.defineProperty(BehaviorSubject2.prototype, "value", {
            get: function() {
              return this.getValue();
            },
            enumerable: false,
            configurable: true
          });
          BehaviorSubject2.prototype._subscribe = function(subscriber) {
            var subscription = _super.prototype._subscribe.call(this, subscriber);
            !subscription.closed && subscriber.next(this._value);
            return subscription;
          };
          BehaviorSubject2.prototype.getValue = function() {
            var _a2 = this, hasError = _a2.hasError, thrownError = _a2.thrownError, _value = _a2._value;
            if (hasError) {
              throw thrownError;
            }
            this._throwIfClosed();
            return _value;
          };
          BehaviorSubject2.prototype.next = function(value) {
            _super.prototype.next.call(this, this._value = value);
          };
          return BehaviorSubject2;
        })(Subject_1.Subject);
        exports22.BehaviorSubject = BehaviorSubject;
      }
    });
    var require_dateTimestampProvider = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/dateTimestampProvider.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.dateTimestampProvider = void 0;
        exports22.dateTimestampProvider = {
          now: function() {
            return (exports22.dateTimestampProvider.delegate || Date).now();
          },
          delegate: void 0
        };
      }
    });
    var require_ReplaySubject = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/ReplaySubject.js"(exports22) {
        "use strict";
        var __extends2 = exports22 && exports22.__extends || /* @__PURE__ */ (function() {
          var extendStatics2 = function(d, b) {
            extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
              d2.__proto__ = b2;
            } || function(d2, b2) {
              for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
            };
            return extendStatics2(d, b);
          };
          return function(d, b) {
            if (typeof b !== "function" && b !== null)
              throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
            extendStatics2(d, b);
            function __() {
              this.constructor = d;
            }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
        })();
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.ReplaySubject = void 0;
        var Subject_1 = require_Subject();
        var dateTimestampProvider_1 = require_dateTimestampProvider();
        var ReplaySubject = (function(_super) {
          __extends2(ReplaySubject2, _super);
          function ReplaySubject2(_bufferSize, _windowTime, _timestampProvider) {
            if (_bufferSize === void 0) {
              _bufferSize = Infinity;
            }
            if (_windowTime === void 0) {
              _windowTime = Infinity;
            }
            if (_timestampProvider === void 0) {
              _timestampProvider = dateTimestampProvider_1.dateTimestampProvider;
            }
            var _this = _super.call(this) || this;
            _this._bufferSize = _bufferSize;
            _this._windowTime = _windowTime;
            _this._timestampProvider = _timestampProvider;
            _this._buffer = [];
            _this._infiniteTimeWindow = true;
            _this._infiniteTimeWindow = _windowTime === Infinity;
            _this._bufferSize = Math.max(1, _bufferSize);
            _this._windowTime = Math.max(1, _windowTime);
            return _this;
          }
          ReplaySubject2.prototype.next = function(value) {
            var _a2 = this, isStopped = _a2.isStopped, _buffer = _a2._buffer, _infiniteTimeWindow = _a2._infiniteTimeWindow, _timestampProvider = _a2._timestampProvider, _windowTime = _a2._windowTime;
            if (!isStopped) {
              _buffer.push(value);
              !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);
            }
            this._trimBuffer();
            _super.prototype.next.call(this, value);
          };
          ReplaySubject2.prototype._subscribe = function(subscriber) {
            this._throwIfClosed();
            this._trimBuffer();
            var subscription = this._innerSubscribe(subscriber);
            var _a2 = this, _infiniteTimeWindow = _a2._infiniteTimeWindow, _buffer = _a2._buffer;
            var copy = _buffer.slice();
            for (var i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {
              subscriber.next(copy[i]);
            }
            this._checkFinalizedStatuses(subscriber);
            return subscription;
          };
          ReplaySubject2.prototype._trimBuffer = function() {
            var _a2 = this, _bufferSize = _a2._bufferSize, _timestampProvider = _a2._timestampProvider, _buffer = _a2._buffer, _infiniteTimeWindow = _a2._infiniteTimeWindow;
            var adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;
            _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);
            if (!_infiniteTimeWindow) {
              var now = _timestampProvider.now();
              var last = 0;
              for (var i = 1; i < _buffer.length && _buffer[i] <= now; i += 2) {
                last = i;
              }
              last && _buffer.splice(0, last + 1);
            }
          };
          return ReplaySubject2;
        })(Subject_1.Subject);
        exports22.ReplaySubject = ReplaySubject;
      }
    });
    var require_AsyncSubject = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/AsyncSubject.js"(exports22) {
        "use strict";
        var __extends2 = exports22 && exports22.__extends || /* @__PURE__ */ (function() {
          var extendStatics2 = function(d, b) {
            extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
              d2.__proto__ = b2;
            } || function(d2, b2) {
              for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
            };
            return extendStatics2(d, b);
          };
          return function(d, b) {
            if (typeof b !== "function" && b !== null)
              throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
            extendStatics2(d, b);
            function __() {
              this.constructor = d;
            }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
        })();
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.AsyncSubject = void 0;
        var Subject_1 = require_Subject();
        var AsyncSubject = (function(_super) {
          __extends2(AsyncSubject2, _super);
          function AsyncSubject2() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this._value = null;
            _this._hasValue = false;
            _this._isComplete = false;
            return _this;
          }
          AsyncSubject2.prototype._checkFinalizedStatuses = function(subscriber) {
            var _a2 = this, hasError = _a2.hasError, _hasValue = _a2._hasValue, _value = _a2._value, thrownError = _a2.thrownError, isStopped = _a2.isStopped, _isComplete = _a2._isComplete;
            if (hasError) {
              subscriber.error(thrownError);
            } else if (isStopped || _isComplete) {
              _hasValue && subscriber.next(_value);
              subscriber.complete();
            }
          };
          AsyncSubject2.prototype.next = function(value) {
            if (!this.isStopped) {
              this._value = value;
              this._hasValue = true;
            }
          };
          AsyncSubject2.prototype.complete = function() {
            var _a2 = this, _hasValue = _a2._hasValue, _value = _a2._value, _isComplete = _a2._isComplete;
            if (!_isComplete) {
              this._isComplete = true;
              _hasValue && _super.prototype.next.call(this, _value);
              _super.prototype.complete.call(this);
            }
          };
          return AsyncSubject2;
        })(Subject_1.Subject);
        exports22.AsyncSubject = AsyncSubject;
      }
    });
    var require_Action = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/Action.js"(exports22) {
        "use strict";
        var __extends2 = exports22 && exports22.__extends || /* @__PURE__ */ (function() {
          var extendStatics2 = function(d, b) {
            extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
              d2.__proto__ = b2;
            } || function(d2, b2) {
              for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
            };
            return extendStatics2(d, b);
          };
          return function(d, b) {
            if (typeof b !== "function" && b !== null)
              throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
            extendStatics2(d, b);
            function __() {
              this.constructor = d;
            }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
        })();
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.Action = void 0;
        var Subscription_1 = require_Subscription();
        var Action = (function(_super) {
          __extends2(Action2, _super);
          function Action2(scheduler, work) {
            return _super.call(this) || this;
          }
          Action2.prototype.schedule = function(state, delay) {
            if (delay === void 0) {
              delay = 0;
            }
            return this;
          };
          return Action2;
        })(Subscription_1.Subscription);
        exports22.Action = Action;
      }
    });
    var require_intervalProvider = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/intervalProvider.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.intervalProvider = void 0;
        exports22.intervalProvider = {
          setInterval: function(handler, timeout) {
            var args2 = [];
            for (var _i = 2; _i < arguments.length; _i++) {
              args2[_i - 2] = arguments[_i];
            }
            var delegate = exports22.intervalProvider.delegate;
            if (delegate === null || delegate === void 0 ? void 0 : delegate.setInterval) {
              return delegate.setInterval.apply(delegate, __spreadArray2([handler, timeout], __read2(args2)));
            }
            return setInterval.apply(void 0, __spreadArray2([handler, timeout], __read2(args2)));
          },
          clearInterval: function(handle) {
            var delegate = exports22.intervalProvider.delegate;
            return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearInterval) || clearInterval)(handle);
          },
          delegate: void 0
        };
      }
    });
    var require_AsyncAction = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/AsyncAction.js"(exports22) {
        "use strict";
        var __extends2 = exports22 && exports22.__extends || /* @__PURE__ */ (function() {
          var extendStatics2 = function(d, b) {
            extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
              d2.__proto__ = b2;
            } || function(d2, b2) {
              for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
            };
            return extendStatics2(d, b);
          };
          return function(d, b) {
            if (typeof b !== "function" && b !== null)
              throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
            extendStatics2(d, b);
            function __() {
              this.constructor = d;
            }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
        })();
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.AsyncAction = void 0;
        var Action_1 = require_Action();
        var intervalProvider_1 = require_intervalProvider();
        var arrRemove_1 = require_arrRemove();
        var AsyncAction = (function(_super) {
          __extends2(AsyncAction2, _super);
          function AsyncAction2(scheduler, work) {
            var _this = _super.call(this, scheduler, work) || this;
            _this.scheduler = scheduler;
            _this.work = work;
            _this.pending = false;
            return _this;
          }
          AsyncAction2.prototype.schedule = function(state, delay) {
            var _a2;
            if (delay === void 0) {
              delay = 0;
            }
            if (this.closed) {
              return this;
            }
            this.state = state;
            var id = this.id;
            var scheduler = this.scheduler;
            if (id != null) {
              this.id = this.recycleAsyncId(scheduler, id, delay);
            }
            this.pending = true;
            this.delay = delay;
            this.id = (_a2 = this.id) !== null && _a2 !== void 0 ? _a2 : this.requestAsyncId(scheduler, this.id, delay);
            return this;
          };
          AsyncAction2.prototype.requestAsyncId = function(scheduler, _id, delay) {
            if (delay === void 0) {
              delay = 0;
            }
            return intervalProvider_1.intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);
          };
          AsyncAction2.prototype.recycleAsyncId = function(_scheduler, id, delay) {
            if (delay === void 0) {
              delay = 0;
            }
            if (delay != null && this.delay === delay && this.pending === false) {
              return id;
            }
            if (id != null) {
              intervalProvider_1.intervalProvider.clearInterval(id);
            }
            return void 0;
          };
          AsyncAction2.prototype.execute = function(state, delay) {
            if (this.closed) {
              return new Error("executing a cancelled action");
            }
            this.pending = false;
            var error = this._execute(state, delay);
            if (error) {
              return error;
            } else if (this.pending === false && this.id != null) {
              this.id = this.recycleAsyncId(this.scheduler, this.id, null);
            }
          };
          AsyncAction2.prototype._execute = function(state, _delay) {
            var errored = false;
            var errorValue;
            try {
              this.work(state);
            } catch (e) {
              errored = true;
              errorValue = e ? e : new Error("Scheduled action threw falsy error");
            }
            if (errored) {
              this.unsubscribe();
              return errorValue;
            }
          };
          AsyncAction2.prototype.unsubscribe = function() {
            if (!this.closed) {
              var _a2 = this, id = _a2.id, scheduler = _a2.scheduler;
              var actions = scheduler.actions;
              this.work = this.state = this.scheduler = null;
              this.pending = false;
              arrRemove_1.arrRemove(actions, this);
              if (id != null) {
                this.id = this.recycleAsyncId(scheduler, id, null);
              }
              this.delay = null;
              _super.prototype.unsubscribe.call(this);
            }
          };
          return AsyncAction2;
        })(Action_1.Action);
        exports22.AsyncAction = AsyncAction;
      }
    });
    var require_Immediate = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/Immediate.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.TestTools = exports22.Immediate = void 0;
        var nextHandle = 1;
        var resolved;
        var activeHandles = {};
        function findAndClearHandle(handle) {
          if (handle in activeHandles) {
            delete activeHandles[handle];
            return true;
          }
          return false;
        }
        exports22.Immediate = {
          setImmediate: function(cb) {
            var handle = nextHandle++;
            activeHandles[handle] = true;
            if (!resolved) {
              resolved = Promise.resolve();
            }
            resolved.then(function() {
              return findAndClearHandle(handle) && cb();
            });
            return handle;
          },
          clearImmediate: function(handle) {
            findAndClearHandle(handle);
          }
        };
        exports22.TestTools = {
          pending: function() {
            return Object.keys(activeHandles).length;
          }
        };
      }
    });
    var require_immediateProvider = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/immediateProvider.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.immediateProvider = void 0;
        var Immediate_1 = require_Immediate();
        var setImmediate2 = Immediate_1.Immediate.setImmediate;
        var clearImmediate = Immediate_1.Immediate.clearImmediate;
        exports22.immediateProvider = {
          setImmediate: function() {
            var args2 = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              args2[_i] = arguments[_i];
            }
            var delegate = exports22.immediateProvider.delegate;
            return ((delegate === null || delegate === void 0 ? void 0 : delegate.setImmediate) || setImmediate2).apply(void 0, __spreadArray2([], __read2(args2)));
          },
          clearImmediate: function(handle) {
            var delegate = exports22.immediateProvider.delegate;
            return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearImmediate) || clearImmediate)(handle);
          },
          delegate: void 0
        };
      }
    });
    var require_AsapAction = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/AsapAction.js"(exports22) {
        "use strict";
        var __extends2 = exports22 && exports22.__extends || /* @__PURE__ */ (function() {
          var extendStatics2 = function(d, b) {
            extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
              d2.__proto__ = b2;
            } || function(d2, b2) {
              for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
            };
            return extendStatics2(d, b);
          };
          return function(d, b) {
            if (typeof b !== "function" && b !== null)
              throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
            extendStatics2(d, b);
            function __() {
              this.constructor = d;
            }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
        })();
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.AsapAction = void 0;
        var AsyncAction_1 = require_AsyncAction();
        var immediateProvider_1 = require_immediateProvider();
        var AsapAction = (function(_super) {
          __extends2(AsapAction2, _super);
          function AsapAction2(scheduler, work) {
            var _this = _super.call(this, scheduler, work) || this;
            _this.scheduler = scheduler;
            _this.work = work;
            return _this;
          }
          AsapAction2.prototype.requestAsyncId = function(scheduler, id, delay) {
            if (delay === void 0) {
              delay = 0;
            }
            if (delay !== null && delay > 0) {
              return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
            }
            scheduler.actions.push(this);
            return scheduler._scheduled || (scheduler._scheduled = immediateProvider_1.immediateProvider.setImmediate(scheduler.flush.bind(scheduler, void 0)));
          };
          AsapAction2.prototype.recycleAsyncId = function(scheduler, id, delay) {
            var _a2;
            if (delay === void 0) {
              delay = 0;
            }
            if (delay != null ? delay > 0 : this.delay > 0) {
              return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
            }
            var actions = scheduler.actions;
            if (id != null && ((_a2 = actions[actions.length - 1]) === null || _a2 === void 0 ? void 0 : _a2.id) !== id) {
              immediateProvider_1.immediateProvider.clearImmediate(id);
              if (scheduler._scheduled === id) {
                scheduler._scheduled = void 0;
              }
            }
            return void 0;
          };
          return AsapAction2;
        })(AsyncAction_1.AsyncAction);
        exports22.AsapAction = AsapAction;
      }
    });
    var require_Scheduler = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/Scheduler.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.Scheduler = void 0;
        var dateTimestampProvider_1 = require_dateTimestampProvider();
        var Scheduler = (function() {
          function Scheduler2(schedulerActionCtor, now) {
            if (now === void 0) {
              now = Scheduler2.now;
            }
            this.schedulerActionCtor = schedulerActionCtor;
            this.now = now;
          }
          Scheduler2.prototype.schedule = function(work, delay, state) {
            if (delay === void 0) {
              delay = 0;
            }
            return new this.schedulerActionCtor(this, work).schedule(state, delay);
          };
          Scheduler2.now = dateTimestampProvider_1.dateTimestampProvider.now;
          return Scheduler2;
        })();
        exports22.Scheduler = Scheduler;
      }
    });
    var require_AsyncScheduler = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/AsyncScheduler.js"(exports22) {
        "use strict";
        var __extends2 = exports22 && exports22.__extends || /* @__PURE__ */ (function() {
          var extendStatics2 = function(d, b) {
            extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
              d2.__proto__ = b2;
            } || function(d2, b2) {
              for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
            };
            return extendStatics2(d, b);
          };
          return function(d, b) {
            if (typeof b !== "function" && b !== null)
              throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
            extendStatics2(d, b);
            function __() {
              this.constructor = d;
            }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
        })();
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.AsyncScheduler = void 0;
        var Scheduler_1 = require_Scheduler();
        var AsyncScheduler = (function(_super) {
          __extends2(AsyncScheduler2, _super);
          function AsyncScheduler2(SchedulerAction, now) {
            if (now === void 0) {
              now = Scheduler_1.Scheduler.now;
            }
            var _this = _super.call(this, SchedulerAction, now) || this;
            _this.actions = [];
            _this._active = false;
            return _this;
          }
          AsyncScheduler2.prototype.flush = function(action) {
            var actions = this.actions;
            if (this._active) {
              actions.push(action);
              return;
            }
            var error;
            this._active = true;
            do {
              if (error = action.execute(action.state, action.delay)) {
                break;
              }
            } while (action = actions.shift());
            this._active = false;
            if (error) {
              while (action = actions.shift()) {
                action.unsubscribe();
              }
              throw error;
            }
          };
          return AsyncScheduler2;
        })(Scheduler_1.Scheduler);
        exports22.AsyncScheduler = AsyncScheduler;
      }
    });
    var require_AsapScheduler = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/AsapScheduler.js"(exports22) {
        "use strict";
        var __extends2 = exports22 && exports22.__extends || /* @__PURE__ */ (function() {
          var extendStatics2 = function(d, b) {
            extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
              d2.__proto__ = b2;
            } || function(d2, b2) {
              for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
            };
            return extendStatics2(d, b);
          };
          return function(d, b) {
            if (typeof b !== "function" && b !== null)
              throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
            extendStatics2(d, b);
            function __() {
              this.constructor = d;
            }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
        })();
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.AsapScheduler = void 0;
        var AsyncScheduler_1 = require_AsyncScheduler();
        var AsapScheduler = (function(_super) {
          __extends2(AsapScheduler2, _super);
          function AsapScheduler2() {
            return _super !== null && _super.apply(this, arguments) || this;
          }
          AsapScheduler2.prototype.flush = function(action) {
            this._active = true;
            var flushId = this._scheduled;
            this._scheduled = void 0;
            var actions = this.actions;
            var error;
            action = action || actions.shift();
            do {
              if (error = action.execute(action.state, action.delay)) {
                break;
              }
            } while ((action = actions[0]) && action.id === flushId && actions.shift());
            this._active = false;
            if (error) {
              while ((action = actions[0]) && action.id === flushId && actions.shift()) {
                action.unsubscribe();
              }
              throw error;
            }
          };
          return AsapScheduler2;
        })(AsyncScheduler_1.AsyncScheduler);
        exports22.AsapScheduler = AsapScheduler;
      }
    });
    var require_asap = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/asap.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.asap = exports22.asapScheduler = void 0;
        var AsapAction_1 = require_AsapAction();
        var AsapScheduler_1 = require_AsapScheduler();
        exports22.asapScheduler = new AsapScheduler_1.AsapScheduler(AsapAction_1.AsapAction);
        exports22.asap = exports22.asapScheduler;
      }
    });
    var require_async2 = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/async.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.async = exports22.asyncScheduler = void 0;
        var AsyncAction_1 = require_AsyncAction();
        var AsyncScheduler_1 = require_AsyncScheduler();
        exports22.asyncScheduler = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction);
        exports22.async = exports22.asyncScheduler;
      }
    });
    var require_QueueAction = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/QueueAction.js"(exports22) {
        "use strict";
        var __extends2 = exports22 && exports22.__extends || /* @__PURE__ */ (function() {
          var extendStatics2 = function(d, b) {
            extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
              d2.__proto__ = b2;
            } || function(d2, b2) {
              for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
            };
            return extendStatics2(d, b);
          };
          return function(d, b) {
            if (typeof b !== "function" && b !== null)
              throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
            extendStatics2(d, b);
            function __() {
              this.constructor = d;
            }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
        })();
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.QueueAction = void 0;
        var AsyncAction_1 = require_AsyncAction();
        var QueueAction = (function(_super) {
          __extends2(QueueAction2, _super);
          function QueueAction2(scheduler, work) {
            var _this = _super.call(this, scheduler, work) || this;
            _this.scheduler = scheduler;
            _this.work = work;
            return _this;
          }
          QueueAction2.prototype.schedule = function(state, delay) {
            if (delay === void 0) {
              delay = 0;
            }
            if (delay > 0) {
              return _super.prototype.schedule.call(this, state, delay);
            }
            this.delay = delay;
            this.state = state;
            this.scheduler.flush(this);
            return this;
          };
          QueueAction2.prototype.execute = function(state, delay) {
            return delay > 0 || this.closed ? _super.prototype.execute.call(this, state, delay) : this._execute(state, delay);
          };
          QueueAction2.prototype.requestAsyncId = function(scheduler, id, delay) {
            if (delay === void 0) {
              delay = 0;
            }
            if (delay != null && delay > 0 || delay == null && this.delay > 0) {
              return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
            }
            scheduler.flush(this);
            return 0;
          };
          return QueueAction2;
        })(AsyncAction_1.AsyncAction);
        exports22.QueueAction = QueueAction;
      }
    });
    var require_QueueScheduler = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/QueueScheduler.js"(exports22) {
        "use strict";
        var __extends2 = exports22 && exports22.__extends || /* @__PURE__ */ (function() {
          var extendStatics2 = function(d, b) {
            extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
              d2.__proto__ = b2;
            } || function(d2, b2) {
              for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
            };
            return extendStatics2(d, b);
          };
          return function(d, b) {
            if (typeof b !== "function" && b !== null)
              throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
            extendStatics2(d, b);
            function __() {
              this.constructor = d;
            }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
        })();
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.QueueScheduler = void 0;
        var AsyncScheduler_1 = require_AsyncScheduler();
        var QueueScheduler = (function(_super) {
          __extends2(QueueScheduler2, _super);
          function QueueScheduler2() {
            return _super !== null && _super.apply(this, arguments) || this;
          }
          return QueueScheduler2;
        })(AsyncScheduler_1.AsyncScheduler);
        exports22.QueueScheduler = QueueScheduler;
      }
    });
    var require_queue = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/queue.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.queue = exports22.queueScheduler = void 0;
        var QueueAction_1 = require_QueueAction();
        var QueueScheduler_1 = require_QueueScheduler();
        exports22.queueScheduler = new QueueScheduler_1.QueueScheduler(QueueAction_1.QueueAction);
        exports22.queue = exports22.queueScheduler;
      }
    });
    var require_AnimationFrameAction = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/AnimationFrameAction.js"(exports22) {
        "use strict";
        var __extends2 = exports22 && exports22.__extends || /* @__PURE__ */ (function() {
          var extendStatics2 = function(d, b) {
            extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
              d2.__proto__ = b2;
            } || function(d2, b2) {
              for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
            };
            return extendStatics2(d, b);
          };
          return function(d, b) {
            if (typeof b !== "function" && b !== null)
              throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
            extendStatics2(d, b);
            function __() {
              this.constructor = d;
            }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
        })();
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.AnimationFrameAction = void 0;
        var AsyncAction_1 = require_AsyncAction();
        var animationFrameProvider_1 = require_animationFrameProvider();
        var AnimationFrameAction = (function(_super) {
          __extends2(AnimationFrameAction2, _super);
          function AnimationFrameAction2(scheduler, work) {
            var _this = _super.call(this, scheduler, work) || this;
            _this.scheduler = scheduler;
            _this.work = work;
            return _this;
          }
          AnimationFrameAction2.prototype.requestAsyncId = function(scheduler, id, delay) {
            if (delay === void 0) {
              delay = 0;
            }
            if (delay !== null && delay > 0) {
              return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
            }
            scheduler.actions.push(this);
            return scheduler._scheduled || (scheduler._scheduled = animationFrameProvider_1.animationFrameProvider.requestAnimationFrame(function() {
              return scheduler.flush(void 0);
            }));
          };
          AnimationFrameAction2.prototype.recycleAsyncId = function(scheduler, id, delay) {
            var _a2;
            if (delay === void 0) {
              delay = 0;
            }
            if (delay != null ? delay > 0 : this.delay > 0) {
              return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
            }
            var actions = scheduler.actions;
            if (id != null && id === scheduler._scheduled && ((_a2 = actions[actions.length - 1]) === null || _a2 === void 0 ? void 0 : _a2.id) !== id) {
              animationFrameProvider_1.animationFrameProvider.cancelAnimationFrame(id);
              scheduler._scheduled = void 0;
            }
            return void 0;
          };
          return AnimationFrameAction2;
        })(AsyncAction_1.AsyncAction);
        exports22.AnimationFrameAction = AnimationFrameAction;
      }
    });
    var require_AnimationFrameScheduler = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/AnimationFrameScheduler.js"(exports22) {
        "use strict";
        var __extends2 = exports22 && exports22.__extends || /* @__PURE__ */ (function() {
          var extendStatics2 = function(d, b) {
            extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
              d2.__proto__ = b2;
            } || function(d2, b2) {
              for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
            };
            return extendStatics2(d, b);
          };
          return function(d, b) {
            if (typeof b !== "function" && b !== null)
              throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
            extendStatics2(d, b);
            function __() {
              this.constructor = d;
            }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
        })();
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.AnimationFrameScheduler = void 0;
        var AsyncScheduler_1 = require_AsyncScheduler();
        var AnimationFrameScheduler = (function(_super) {
          __extends2(AnimationFrameScheduler2, _super);
          function AnimationFrameScheduler2() {
            return _super !== null && _super.apply(this, arguments) || this;
          }
          AnimationFrameScheduler2.prototype.flush = function(action) {
            this._active = true;
            var flushId;
            if (action) {
              flushId = action.id;
            } else {
              flushId = this._scheduled;
              this._scheduled = void 0;
            }
            var actions = this.actions;
            var error;
            action = action || actions.shift();
            do {
              if (error = action.execute(action.state, action.delay)) {
                break;
              }
            } while ((action = actions[0]) && action.id === flushId && actions.shift());
            this._active = false;
            if (error) {
              while ((action = actions[0]) && action.id === flushId && actions.shift()) {
                action.unsubscribe();
              }
              throw error;
            }
          };
          return AnimationFrameScheduler2;
        })(AsyncScheduler_1.AsyncScheduler);
        exports22.AnimationFrameScheduler = AnimationFrameScheduler;
      }
    });
    var require_animationFrame = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/animationFrame.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.animationFrame = exports22.animationFrameScheduler = void 0;
        var AnimationFrameAction_1 = require_AnimationFrameAction();
        var AnimationFrameScheduler_1 = require_AnimationFrameScheduler();
        exports22.animationFrameScheduler = new AnimationFrameScheduler_1.AnimationFrameScheduler(AnimationFrameAction_1.AnimationFrameAction);
        exports22.animationFrame = exports22.animationFrameScheduler;
      }
    });
    var require_VirtualTimeScheduler = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduler/VirtualTimeScheduler.js"(exports22) {
        "use strict";
        var __extends2 = exports22 && exports22.__extends || /* @__PURE__ */ (function() {
          var extendStatics2 = function(d, b) {
            extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
              d2.__proto__ = b2;
            } || function(d2, b2) {
              for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
            };
            return extendStatics2(d, b);
          };
          return function(d, b) {
            if (typeof b !== "function" && b !== null)
              throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
            extendStatics2(d, b);
            function __() {
              this.constructor = d;
            }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
          };
        })();
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.VirtualAction = exports22.VirtualTimeScheduler = void 0;
        var AsyncAction_1 = require_AsyncAction();
        var Subscription_1 = require_Subscription();
        var AsyncScheduler_1 = require_AsyncScheduler();
        var VirtualTimeScheduler = (function(_super) {
          __extends2(VirtualTimeScheduler2, _super);
          function VirtualTimeScheduler2(schedulerActionCtor, maxFrames) {
            if (schedulerActionCtor === void 0) {
              schedulerActionCtor = VirtualAction;
            }
            if (maxFrames === void 0) {
              maxFrames = Infinity;
            }
            var _this = _super.call(this, schedulerActionCtor, function() {
              return _this.frame;
            }) || this;
            _this.maxFrames = maxFrames;
            _this.frame = 0;
            _this.index = -1;
            return _this;
          }
          VirtualTimeScheduler2.prototype.flush = function() {
            var _a2 = this, actions = _a2.actions, maxFrames = _a2.maxFrames;
            var error;
            var action;
            while ((action = actions[0]) && action.delay <= maxFrames) {
              actions.shift();
              this.frame = action.delay;
              if (error = action.execute(action.state, action.delay)) {
                break;
              }
            }
            if (error) {
              while (action = actions.shift()) {
                action.unsubscribe();
              }
              throw error;
            }
          };
          VirtualTimeScheduler2.frameTimeFactor = 10;
          return VirtualTimeScheduler2;
        })(AsyncScheduler_1.AsyncScheduler);
        exports22.VirtualTimeScheduler = VirtualTimeScheduler;
        var VirtualAction = (function(_super) {
          __extends2(VirtualAction2, _super);
          function VirtualAction2(scheduler, work, index) {
            if (index === void 0) {
              index = scheduler.index += 1;
            }
            var _this = _super.call(this, scheduler, work) || this;
            _this.scheduler = scheduler;
            _this.work = work;
            _this.index = index;
            _this.active = true;
            _this.index = scheduler.index = index;
            return _this;
          }
          VirtualAction2.prototype.schedule = function(state, delay) {
            if (delay === void 0) {
              delay = 0;
            }
            if (Number.isFinite(delay)) {
              if (!this.id) {
                return _super.prototype.schedule.call(this, state, delay);
              }
              this.active = false;
              var action = new VirtualAction2(this.scheduler, this.work);
              this.add(action);
              return action.schedule(state, delay);
            } else {
              return Subscription_1.Subscription.EMPTY;
            }
          };
          VirtualAction2.prototype.requestAsyncId = function(scheduler, id, delay) {
            if (delay === void 0) {
              delay = 0;
            }
            this.delay = scheduler.frame + delay;
            var actions = scheduler.actions;
            actions.push(this);
            actions.sort(VirtualAction2.sortActions);
            return 1;
          };
          VirtualAction2.prototype.recycleAsyncId = function(scheduler, id, delay) {
            if (delay === void 0) {
              delay = 0;
            }
            return void 0;
          };
          VirtualAction2.prototype._execute = function(state, delay) {
            if (this.active === true) {
              return _super.prototype._execute.call(this, state, delay);
            }
          };
          VirtualAction2.sortActions = function(a, b) {
            if (a.delay === b.delay) {
              if (a.index === b.index) {
                return 0;
              } else if (a.index > b.index) {
                return 1;
              } else {
                return -1;
              }
            } else if (a.delay > b.delay) {
              return 1;
            } else {
              return -1;
            }
          };
          return VirtualAction2;
        })(AsyncAction_1.AsyncAction);
        exports22.VirtualAction = VirtualAction;
      }
    });
    var require_empty = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/empty.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.empty = exports22.EMPTY = void 0;
        var Observable_1 = require_Observable();
        exports22.EMPTY = new Observable_1.Observable(function(subscriber) {
          return subscriber.complete();
        });
        function empty(scheduler) {
          return scheduler ? emptyScheduled(scheduler) : exports22.EMPTY;
        }
        exports22.empty = empty;
        function emptyScheduled(scheduler) {
          return new Observable_1.Observable(function(subscriber) {
            return scheduler.schedule(function() {
              return subscriber.complete();
            });
          });
        }
      }
    });
    var require_isScheduler = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/isScheduler.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.isScheduler = void 0;
        var isFunction_1 = require_isFunction();
        function isScheduler(value) {
          return value && isFunction_1.isFunction(value.schedule);
        }
        exports22.isScheduler = isScheduler;
      }
    });
    var require_args = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/args.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.popNumber = exports22.popScheduler = exports22.popResultSelector = void 0;
        var isFunction_1 = require_isFunction();
        var isScheduler_1 = require_isScheduler();
        function last(arr) {
          return arr[arr.length - 1];
        }
        function popResultSelector(args2) {
          return isFunction_1.isFunction(last(args2)) ? args2.pop() : void 0;
        }
        exports22.popResultSelector = popResultSelector;
        function popScheduler(args2) {
          return isScheduler_1.isScheduler(last(args2)) ? args2.pop() : void 0;
        }
        exports22.popScheduler = popScheduler;
        function popNumber(args2, defaultValue) {
          return typeof last(args2) === "number" ? args2.pop() : defaultValue;
        }
        exports22.popNumber = popNumber;
      }
    });
    var require_isArrayLike = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/isArrayLike.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.isArrayLike = void 0;
        exports22.isArrayLike = (function(x) {
          return x && typeof x.length === "number" && typeof x !== "function";
        });
      }
    });
    var require_isPromise = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/isPromise.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.isPromise = void 0;
        var isFunction_1 = require_isFunction();
        function isPromise2(value) {
          return isFunction_1.isFunction(value === null || value === void 0 ? void 0 : value.then);
        }
        exports22.isPromise = isPromise2;
      }
    });
    var require_isInteropObservable = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/isInteropObservable.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.isInteropObservable = void 0;
        var observable_1 = require_observable();
        var isFunction_1 = require_isFunction();
        function isInteropObservable(input) {
          return isFunction_1.isFunction(input[observable_1.observable]);
        }
        exports22.isInteropObservable = isInteropObservable;
      }
    });
    var require_isAsyncIterable = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/isAsyncIterable.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.isAsyncIterable = void 0;
        var isFunction_1 = require_isFunction();
        function isAsyncIterable(obj) {
          return Symbol.asyncIterator && isFunction_1.isFunction(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]);
        }
        exports22.isAsyncIterable = isAsyncIterable;
      }
    });
    var require_throwUnobservableError = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/throwUnobservableError.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.createInvalidObservableTypeError = void 0;
        function createInvalidObservableTypeError(input) {
          return new TypeError("You provided " + (input !== null && typeof input === "object" ? "an invalid object" : "'" + input + "'") + " where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.");
        }
        exports22.createInvalidObservableTypeError = createInvalidObservableTypeError;
      }
    });
    var require_iterator = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/symbol/iterator.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.iterator = exports22.getSymbolIterator = void 0;
        function getSymbolIterator() {
          if (typeof Symbol !== "function" || !Symbol.iterator) {
            return "@@iterator";
          }
          return Symbol.iterator;
        }
        exports22.getSymbolIterator = getSymbolIterator;
        exports22.iterator = getSymbolIterator();
      }
    });
    var require_isIterable = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/isIterable.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.isIterable = void 0;
        var iterator_1 = require_iterator();
        var isFunction_1 = require_isFunction();
        function isIterable(input) {
          return isFunction_1.isFunction(input === null || input === void 0 ? void 0 : input[iterator_1.iterator]);
        }
        exports22.isIterable = isIterable;
      }
    });
    var require_isReadableStreamLike = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/isReadableStreamLike.js"(exports22) {
        "use strict";
        var __generator2 = exports22 && exports22.__generator || function(thisArg, body) {
          var _ = { label: 0, sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
          }, trys: [], ops: [] }, f, y, t, g;
          return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
            return this;
          }), g;
          function verb(n) {
            return function(v) {
              return step([n, v]);
            };
          }
          function step(op) {
            if (f) throw new TypeError("Generator is already executing.");
            while (_) try {
              if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
              if (y = 0, t) op = [op[0] & 2, t.value];
              switch (op[0]) {
                case 0:
                case 1:
                  t = op;
                  break;
                case 4:
                  _.label++;
                  return { value: op[1], done: false };
                case 5:
                  _.label++;
                  y = op[1];
                  op = [0];
                  continue;
                case 7:
                  op = _.ops.pop();
                  _.trys.pop();
                  continue;
                default:
                  if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                    _ = 0;
                    continue;
                  }
                  if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                    _.label = op[1];
                    break;
                  }
                  if (op[0] === 6 && _.label < t[1]) {
                    _.label = t[1];
                    t = op;
                    break;
                  }
                  if (t && _.label < t[2]) {
                    _.label = t[2];
                    _.ops.push(op);
                    break;
                  }
                  if (t[2]) _.ops.pop();
                  _.trys.pop();
                  continue;
              }
              op = body.call(thisArg, _);
            } catch (e) {
              op = [6, e];
              y = 0;
            } finally {
              f = t = 0;
            }
            if (op[0] & 5) throw op[1];
            return { value: op[0] ? op[1] : void 0, done: true };
          }
        };
        var __await2 = exports22 && exports22.__await || function(v) {
          return this instanceof __await2 ? (this.v = v, this) : new __await2(v);
        };
        var __asyncGenerator2 = exports22 && exports22.__asyncGenerator || function(thisArg, _arguments, generator) {
          if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
          var g = generator.apply(thisArg, _arguments || []), i, q = [];
          return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
            return this;
          }, i;
          function verb(n) {
            if (g[n]) i[n] = function(v) {
              return new Promise(function(a, b) {
                q.push([n, v, a, b]) > 1 || resume(n, v);
              });
            };
          }
          function resume(n, v) {
            try {
              step(g[n](v));
            } catch (e) {
              settle(q[0][3], e);
            }
          }
          function step(r) {
            r.value instanceof __await2 ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
          }
          function fulfill(value) {
            resume("next", value);
          }
          function reject(value) {
            resume("throw", value);
          }
          function settle(f, v) {
            if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
          }
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.isReadableStreamLike = exports22.readableStreamLikeToAsyncGenerator = void 0;
        var isFunction_1 = require_isFunction();
        function readableStreamLikeToAsyncGenerator(readableStream) {
          return __asyncGenerator2(this, arguments, function readableStreamLikeToAsyncGenerator_1() {
            var reader, _a2, value, done;
            return __generator2(this, function(_b2) {
              switch (_b2.label) {
                case 0:
                  reader = readableStream.getReader();
                  _b2.label = 1;
                case 1:
                  _b2.trys.push([1, , 9, 10]);
                  _b2.label = 2;
                case 2:
                  if (false) return [3, 8];
                  return [4, __await2(reader.read())];
                case 3:
                  _a2 = _b2.sent(), value = _a2.value, done = _a2.done;
                  if (!done) return [3, 5];
                  return [4, __await2(void 0)];
                case 4:
                  return [2, _b2.sent()];
                case 5:
                  return [4, __await2(value)];
                case 6:
                  return [4, _b2.sent()];
                case 7:
                  _b2.sent();
                  return [3, 2];
                case 8:
                  return [3, 10];
                case 9:
                  reader.releaseLock();
                  return [7];
                case 10:
                  return [2];
              }
            });
          });
        }
        exports22.readableStreamLikeToAsyncGenerator = readableStreamLikeToAsyncGenerator;
        function isReadableStreamLike(obj) {
          return isFunction_1.isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader);
        }
        exports22.isReadableStreamLike = isReadableStreamLike;
      }
    });
    var require_innerFrom = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/innerFrom.js"(exports22) {
        "use strict";
        var __awaiter2 = exports22 && exports22.__awaiter || function(thisArg, _arguments, P, generator) {
          function adopt(value) {
            return value instanceof P ? value : new P(function(resolve5) {
              resolve5(value);
            });
          }
          return new (P || (P = Promise))(function(resolve5, 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 ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected);
            }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
          });
        };
        var __generator2 = exports22 && exports22.__generator || function(thisArg, body) {
          var _ = { label: 0, sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
          }, trys: [], ops: [] }, f, y, t, g;
          return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
            return this;
          }), g;
          function verb(n) {
            return function(v) {
              return step([n, v]);
            };
          }
          function step(op) {
            if (f) throw new TypeError("Generator is already executing.");
            while (_) try {
              if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
              if (y = 0, t) op = [op[0] & 2, t.value];
              switch (op[0]) {
                case 0:
                case 1:
                  t = op;
                  break;
                case 4:
                  _.label++;
                  return { value: op[1], done: false };
                case 5:
                  _.label++;
                  y = op[1];
                  op = [0];
                  continue;
                case 7:
                  op = _.ops.pop();
                  _.trys.pop();
                  continue;
                default:
                  if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                    _ = 0;
                    continue;
                  }
                  if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                    _.label = op[1];
                    break;
                  }
                  if (op[0] === 6 && _.label < t[1]) {
                    _.label = t[1];
                    t = op;
                    break;
                  }
                  if (t && _.label < t[2]) {
                    _.label = t[2];
                    _.ops.push(op);
                    break;
                  }
                  if (t[2]) _.ops.pop();
                  _.trys.pop();
                  continue;
              }
              op = body.call(thisArg, _);
            } catch (e) {
              op = [6, e];
              y = 0;
            } finally {
              f = t = 0;
            }
            if (op[0] & 5) throw op[1];
            return { value: op[0] ? op[1] : void 0, done: true };
          }
        };
        var __asyncValues2 = exports22 && exports22.__asyncValues || function(o) {
          if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
          var m = o[Symbol.asyncIterator], i;
          return m ? m.call(o) : (o = typeof __values2 === "function" ? __values2(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
            return this;
          }, i);
          function verb(n) {
            i[n] = o[n] && function(v) {
              return new Promise(function(resolve5, reject) {
                v = o[n](v), settle(resolve5, reject, v.done, v.value);
              });
            };
          }
          function settle(resolve5, reject, d, v) {
            Promise.resolve(v).then(function(v2) {
              resolve5({ value: v2, done: d });
            }, reject);
          }
        };
        var __values2 = exports22 && exports22.__values || function(o) {
          var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
          if (m) return m.call(o);
          if (o && typeof o.length === "number") return {
            next: function() {
              if (o && i >= o.length) o = void 0;
              return { value: o && o[i++], done: !o };
            }
          };
          throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.fromReadableStreamLike = exports22.fromAsyncIterable = exports22.fromIterable = exports22.fromPromise = exports22.fromArrayLike = exports22.fromInteropObservable = exports22.innerFrom = void 0;
        var isArrayLike_1 = require_isArrayLike();
        var isPromise_1 = require_isPromise();
        var Observable_1 = require_Observable();
        var isInteropObservable_1 = require_isInteropObservable();
        var isAsyncIterable_1 = require_isAsyncIterable();
        var throwUnobservableError_1 = require_throwUnobservableError();
        var isIterable_1 = require_isIterable();
        var isReadableStreamLike_1 = require_isReadableStreamLike();
        var isFunction_1 = require_isFunction();
        var reportUnhandledError_1 = require_reportUnhandledError();
        var observable_1 = require_observable();
        function innerFrom(input) {
          if (input instanceof Observable_1.Observable) {
            return input;
          }
          if (input != null) {
            if (isInteropObservable_1.isInteropObservable(input)) {
              return fromInteropObservable(input);
            }
            if (isArrayLike_1.isArrayLike(input)) {
              return fromArrayLike(input);
            }
            if (isPromise_1.isPromise(input)) {
              return fromPromise(input);
            }
            if (isAsyncIterable_1.isAsyncIterable(input)) {
              return fromAsyncIterable(input);
            }
            if (isIterable_1.isIterable(input)) {
              return fromIterable(input);
            }
            if (isReadableStreamLike_1.isReadableStreamLike(input)) {
              return fromReadableStreamLike(input);
            }
          }
          throw throwUnobservableError_1.createInvalidObservableTypeError(input);
        }
        exports22.innerFrom = innerFrom;
        function fromInteropObservable(obj) {
          return new Observable_1.Observable(function(subscriber) {
            var obs = obj[observable_1.observable]();
            if (isFunction_1.isFunction(obs.subscribe)) {
              return obs.subscribe(subscriber);
            }
            throw new TypeError("Provided object does not correctly implement Symbol.observable");
          });
        }
        exports22.fromInteropObservable = fromInteropObservable;
        function fromArrayLike(array) {
          return new Observable_1.Observable(function(subscriber) {
            for (var i = 0; i < array.length && !subscriber.closed; i++) {
              subscriber.next(array[i]);
            }
            subscriber.complete();
          });
        }
        exports22.fromArrayLike = fromArrayLike;
        function fromPromise(promise) {
          return new Observable_1.Observable(function(subscriber) {
            promise.then(function(value) {
              if (!subscriber.closed) {
                subscriber.next(value);
                subscriber.complete();
              }
            }, function(err) {
              return subscriber.error(err);
            }).then(null, reportUnhandledError_1.reportUnhandledError);
          });
        }
        exports22.fromPromise = fromPromise;
        function fromIterable(iterable) {
          return new Observable_1.Observable(function(subscriber) {
            var e_1, _a2;
            try {
              for (var iterable_1 = __values2(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) {
                var value = iterable_1_1.value;
                subscriber.next(value);
                if (subscriber.closed) {
                  return;
                }
              }
            } catch (e_1_1) {
              e_1 = { error: e_1_1 };
            } finally {
              try {
                if (iterable_1_1 && !iterable_1_1.done && (_a2 = iterable_1.return)) _a2.call(iterable_1);
              } finally {
                if (e_1) throw e_1.error;
              }
            }
            subscriber.complete();
          });
        }
        exports22.fromIterable = fromIterable;
        function fromAsyncIterable(asyncIterable) {
          return new Observable_1.Observable(function(subscriber) {
            process2(asyncIterable, subscriber).catch(function(err) {
              return subscriber.error(err);
            });
          });
        }
        exports22.fromAsyncIterable = fromAsyncIterable;
        function fromReadableStreamLike(readableStream) {
          return fromAsyncIterable(isReadableStreamLike_1.readableStreamLikeToAsyncGenerator(readableStream));
        }
        exports22.fromReadableStreamLike = fromReadableStreamLike;
        function process2(asyncIterable, subscriber) {
          var asyncIterable_1, asyncIterable_1_1;
          var e_2, _a2;
          return __awaiter2(this, void 0, void 0, function() {
            var value, e_2_1;
            return __generator2(this, function(_b2) {
              switch (_b2.label) {
                case 0:
                  _b2.trys.push([0, 5, 6, 11]);
                  asyncIterable_1 = __asyncValues2(asyncIterable);
                  _b2.label = 1;
                case 1:
                  return [4, asyncIterable_1.next()];
                case 2:
                  if (!(asyncIterable_1_1 = _b2.sent(), !asyncIterable_1_1.done)) return [3, 4];
                  value = asyncIterable_1_1.value;
                  subscriber.next(value);
                  if (subscriber.closed) {
                    return [2];
                  }
                  _b2.label = 3;
                case 3:
                  return [3, 1];
                case 4:
                  return [3, 11];
                case 5:
                  e_2_1 = _b2.sent();
                  e_2 = { error: e_2_1 };
                  return [3, 11];
                case 6:
                  _b2.trys.push([6, , 9, 10]);
                  if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a2 = asyncIterable_1.return))) return [3, 8];
                  return [4, _a2.call(asyncIterable_1)];
                case 7:
                  _b2.sent();
                  _b2.label = 8;
                case 8:
                  return [3, 10];
                case 9:
                  if (e_2) throw e_2.error;
                  return [7];
                case 10:
                  return [7];
                case 11:
                  subscriber.complete();
                  return [2];
              }
            });
          });
        }
      }
    });
    var require_executeSchedule = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/executeSchedule.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.executeSchedule = void 0;
        function executeSchedule(parentSubscription, scheduler, work, delay, repeat) {
          if (delay === void 0) {
            delay = 0;
          }
          if (repeat === void 0) {
            repeat = false;
          }
          var scheduleSubscription = scheduler.schedule(function() {
            work();
            if (repeat) {
              parentSubscription.add(this.schedule(null, delay));
            } else {
              this.unsubscribe();
            }
          }, delay);
          parentSubscription.add(scheduleSubscription);
          if (!repeat) {
            return scheduleSubscription;
          }
        }
        exports22.executeSchedule = executeSchedule;
      }
    });
    var require_observeOn = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/observeOn.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.observeOn = void 0;
        var executeSchedule_1 = require_executeSchedule();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function observeOn(scheduler, delay) {
          if (delay === void 0) {
            delay = 0;
          }
          return lift_1.operate(function(source, subscriber) {
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              return executeSchedule_1.executeSchedule(subscriber, scheduler, function() {
                return subscriber.next(value);
              }, delay);
            }, function() {
              return executeSchedule_1.executeSchedule(subscriber, scheduler, function() {
                return subscriber.complete();
              }, delay);
            }, function(err) {
              return executeSchedule_1.executeSchedule(subscriber, scheduler, function() {
                return subscriber.error(err);
              }, delay);
            }));
          });
        }
        exports22.observeOn = observeOn;
      }
    });
    var require_subscribeOn = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/subscribeOn.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.subscribeOn = void 0;
        var lift_1 = require_lift();
        function subscribeOn(scheduler, delay) {
          if (delay === void 0) {
            delay = 0;
          }
          return lift_1.operate(function(source, subscriber) {
            subscriber.add(scheduler.schedule(function() {
              return source.subscribe(subscriber);
            }, delay));
          });
        }
        exports22.subscribeOn = subscribeOn;
      }
    });
    var require_scheduleObservable = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduled/scheduleObservable.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.scheduleObservable = void 0;
        var innerFrom_1 = require_innerFrom();
        var observeOn_1 = require_observeOn();
        var subscribeOn_1 = require_subscribeOn();
        function scheduleObservable(input, scheduler) {
          return innerFrom_1.innerFrom(input).pipe(subscribeOn_1.subscribeOn(scheduler), observeOn_1.observeOn(scheduler));
        }
        exports22.scheduleObservable = scheduleObservable;
      }
    });
    var require_schedulePromise = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduled/schedulePromise.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.schedulePromise = void 0;
        var innerFrom_1 = require_innerFrom();
        var observeOn_1 = require_observeOn();
        var subscribeOn_1 = require_subscribeOn();
        function schedulePromise(input, scheduler) {
          return innerFrom_1.innerFrom(input).pipe(subscribeOn_1.subscribeOn(scheduler), observeOn_1.observeOn(scheduler));
        }
        exports22.schedulePromise = schedulePromise;
      }
    });
    var require_scheduleArray = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduled/scheduleArray.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.scheduleArray = void 0;
        var Observable_1 = require_Observable();
        function scheduleArray(input, scheduler) {
          return new Observable_1.Observable(function(subscriber) {
            var i = 0;
            return scheduler.schedule(function() {
              if (i === input.length) {
                subscriber.complete();
              } else {
                subscriber.next(input[i++]);
                if (!subscriber.closed) {
                  this.schedule();
                }
              }
            });
          });
        }
        exports22.scheduleArray = scheduleArray;
      }
    });
    var require_scheduleIterable = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduled/scheduleIterable.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.scheduleIterable = void 0;
        var Observable_1 = require_Observable();
        var iterator_1 = require_iterator();
        var isFunction_1 = require_isFunction();
        var executeSchedule_1 = require_executeSchedule();
        function scheduleIterable(input, scheduler) {
          return new Observable_1.Observable(function(subscriber) {
            var iterator;
            executeSchedule_1.executeSchedule(subscriber, scheduler, function() {
              iterator = input[iterator_1.iterator]();
              executeSchedule_1.executeSchedule(subscriber, scheduler, function() {
                var _a2;
                var value;
                var done;
                try {
                  _a2 = iterator.next(), value = _a2.value, done = _a2.done;
                } catch (err) {
                  subscriber.error(err);
                  return;
                }
                if (done) {
                  subscriber.complete();
                } else {
                  subscriber.next(value);
                }
              }, 0, true);
            });
            return function() {
              return isFunction_1.isFunction(iterator === null || iterator === void 0 ? void 0 : iterator.return) && iterator.return();
            };
          });
        }
        exports22.scheduleIterable = scheduleIterable;
      }
    });
    var require_scheduleAsyncIterable = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduled/scheduleAsyncIterable.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.scheduleAsyncIterable = void 0;
        var Observable_1 = require_Observable();
        var executeSchedule_1 = require_executeSchedule();
        function scheduleAsyncIterable(input, scheduler) {
          if (!input) {
            throw new Error("Iterable cannot be null");
          }
          return new Observable_1.Observable(function(subscriber) {
            executeSchedule_1.executeSchedule(subscriber, scheduler, function() {
              var iterator = input[Symbol.asyncIterator]();
              executeSchedule_1.executeSchedule(subscriber, scheduler, function() {
                iterator.next().then(function(result) {
                  if (result.done) {
                    subscriber.complete();
                  } else {
                    subscriber.next(result.value);
                  }
                });
              }, 0, true);
            });
          });
        }
        exports22.scheduleAsyncIterable = scheduleAsyncIterable;
      }
    });
    var require_scheduleReadableStreamLike = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduled/scheduleReadableStreamLike.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.scheduleReadableStreamLike = void 0;
        var scheduleAsyncIterable_1 = require_scheduleAsyncIterable();
        var isReadableStreamLike_1 = require_isReadableStreamLike();
        function scheduleReadableStreamLike(input, scheduler) {
          return scheduleAsyncIterable_1.scheduleAsyncIterable(isReadableStreamLike_1.readableStreamLikeToAsyncGenerator(input), scheduler);
        }
        exports22.scheduleReadableStreamLike = scheduleReadableStreamLike;
      }
    });
    var require_scheduled = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/scheduled/scheduled.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.scheduled = void 0;
        var scheduleObservable_1 = require_scheduleObservable();
        var schedulePromise_1 = require_schedulePromise();
        var scheduleArray_1 = require_scheduleArray();
        var scheduleIterable_1 = require_scheduleIterable();
        var scheduleAsyncIterable_1 = require_scheduleAsyncIterable();
        var isInteropObservable_1 = require_isInteropObservable();
        var isPromise_1 = require_isPromise();
        var isArrayLike_1 = require_isArrayLike();
        var isIterable_1 = require_isIterable();
        var isAsyncIterable_1 = require_isAsyncIterable();
        var throwUnobservableError_1 = require_throwUnobservableError();
        var isReadableStreamLike_1 = require_isReadableStreamLike();
        var scheduleReadableStreamLike_1 = require_scheduleReadableStreamLike();
        function scheduled(input, scheduler) {
          if (input != null) {
            if (isInteropObservable_1.isInteropObservable(input)) {
              return scheduleObservable_1.scheduleObservable(input, scheduler);
            }
            if (isArrayLike_1.isArrayLike(input)) {
              return scheduleArray_1.scheduleArray(input, scheduler);
            }
            if (isPromise_1.isPromise(input)) {
              return schedulePromise_1.schedulePromise(input, scheduler);
            }
            if (isAsyncIterable_1.isAsyncIterable(input)) {
              return scheduleAsyncIterable_1.scheduleAsyncIterable(input, scheduler);
            }
            if (isIterable_1.isIterable(input)) {
              return scheduleIterable_1.scheduleIterable(input, scheduler);
            }
            if (isReadableStreamLike_1.isReadableStreamLike(input)) {
              return scheduleReadableStreamLike_1.scheduleReadableStreamLike(input, scheduler);
            }
          }
          throw throwUnobservableError_1.createInvalidObservableTypeError(input);
        }
        exports22.scheduled = scheduled;
      }
    });
    var require_from = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/from.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.from = void 0;
        var scheduled_1 = require_scheduled();
        var innerFrom_1 = require_innerFrom();
        function from(input, scheduler) {
          return scheduler ? scheduled_1.scheduled(input, scheduler) : innerFrom_1.innerFrom(input);
        }
        exports22.from = from;
      }
    });
    var require_of = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/of.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.of = void 0;
        var args_1 = require_args();
        var from_1 = require_from();
        function of() {
          var args2 = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args2[_i] = arguments[_i];
          }
          var scheduler = args_1.popScheduler(args2);
          return from_1.from(args2, scheduler);
        }
        exports22.of = of;
      }
    });
    var require_throwError = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/throwError.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.throwError = void 0;
        var Observable_1 = require_Observable();
        var isFunction_1 = require_isFunction();
        function throwError(errorOrErrorFactory, scheduler) {
          var errorFactory = isFunction_1.isFunction(errorOrErrorFactory) ? errorOrErrorFactory : function() {
            return errorOrErrorFactory;
          };
          var init = function(subscriber) {
            return subscriber.error(errorFactory());
          };
          return new Observable_1.Observable(scheduler ? function(subscriber) {
            return scheduler.schedule(init, 0, subscriber);
          } : init);
        }
        exports22.throwError = throwError;
      }
    });
    var require_Notification = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/Notification.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.observeNotification = exports22.Notification = exports22.NotificationKind = void 0;
        var empty_1 = require_empty();
        var of_1 = require_of();
        var throwError_1 = require_throwError();
        var isFunction_1 = require_isFunction();
        var NotificationKind;
        (function(NotificationKind2) {
          NotificationKind2["NEXT"] = "N";
          NotificationKind2["ERROR"] = "E";
          NotificationKind2["COMPLETE"] = "C";
        })(NotificationKind = exports22.NotificationKind || (exports22.NotificationKind = {}));
        var Notification2 = (function() {
          function Notification22(kind, value, error) {
            this.kind = kind;
            this.value = value;
            this.error = error;
            this.hasValue = kind === "N";
          }
          Notification22.prototype.observe = function(observer) {
            return observeNotification(this, observer);
          };
          Notification22.prototype.do = function(nextHandler, errorHandler, completeHandler) {
            var _a2 = this, kind = _a2.kind, value = _a2.value, error = _a2.error;
            return kind === "N" ? nextHandler === null || nextHandler === void 0 ? void 0 : nextHandler(value) : kind === "E" ? errorHandler === null || errorHandler === void 0 ? void 0 : errorHandler(error) : completeHandler === null || completeHandler === void 0 ? void 0 : completeHandler();
          };
          Notification22.prototype.accept = function(nextOrObserver, error, complete) {
            var _a2;
            return isFunction_1.isFunction((_a2 = nextOrObserver) === null || _a2 === void 0 ? void 0 : _a2.next) ? this.observe(nextOrObserver) : this.do(nextOrObserver, error, complete);
          };
          Notification22.prototype.toObservable = function() {
            var _a2 = this, kind = _a2.kind, value = _a2.value, error = _a2.error;
            var result = kind === "N" ? of_1.of(value) : kind === "E" ? throwError_1.throwError(function() {
              return error;
            }) : kind === "C" ? empty_1.EMPTY : 0;
            if (!result) {
              throw new TypeError("Unexpected notification kind " + kind);
            }
            return result;
          };
          Notification22.createNext = function(value) {
            return new Notification22("N", value);
          };
          Notification22.createError = function(err) {
            return new Notification22("E", void 0, err);
          };
          Notification22.createComplete = function() {
            return Notification22.completeNotification;
          };
          Notification22.completeNotification = new Notification22("C");
          return Notification22;
        })();
        exports22.Notification = Notification2;
        function observeNotification(notification, observer) {
          var _a2, _b2, _c2;
          var _d = notification, kind = _d.kind, value = _d.value, error = _d.error;
          if (typeof kind !== "string") {
            throw new TypeError('Invalid notification, missing "kind"');
          }
          kind === "N" ? (_a2 = observer.next) === null || _a2 === void 0 ? void 0 : _a2.call(observer, value) : kind === "E" ? (_b2 = observer.error) === null || _b2 === void 0 ? void 0 : _b2.call(observer, error) : (_c2 = observer.complete) === null || _c2 === void 0 ? void 0 : _c2.call(observer);
        }
        exports22.observeNotification = observeNotification;
      }
    });
    var require_isObservable = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/isObservable.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.isObservable = void 0;
        var Observable_1 = require_Observable();
        var isFunction_1 = require_isFunction();
        function isObservable(obj) {
          return !!obj && (obj instanceof Observable_1.Observable || isFunction_1.isFunction(obj.lift) && isFunction_1.isFunction(obj.subscribe));
        }
        exports22.isObservable = isObservable;
      }
    });
    var require_EmptyError = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/EmptyError.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.EmptyError = void 0;
        var createErrorClass_1 = require_createErrorClass();
        exports22.EmptyError = createErrorClass_1.createErrorClass(function(_super) {
          return function EmptyErrorImpl() {
            _super(this);
            this.name = "EmptyError";
            this.message = "no elements in sequence";
          };
        });
      }
    });
    var require_lastValueFrom = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/lastValueFrom.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.lastValueFrom = void 0;
        var EmptyError_1 = require_EmptyError();
        function lastValueFrom(source, config2) {
          var hasConfig = typeof config2 === "object";
          return new Promise(function(resolve5, reject) {
            var _hasValue = false;
            var _value;
            source.subscribe({
              next: function(value) {
                _value = value;
                _hasValue = true;
              },
              error: reject,
              complete: function() {
                if (_hasValue) {
                  resolve5(_value);
                } else if (hasConfig) {
                  resolve5(config2.defaultValue);
                } else {
                  reject(new EmptyError_1.EmptyError());
                }
              }
            });
          });
        }
        exports22.lastValueFrom = lastValueFrom;
      }
    });
    var require_firstValueFrom = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/firstValueFrom.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.firstValueFrom = void 0;
        var EmptyError_1 = require_EmptyError();
        var Subscriber_1 = require_Subscriber();
        function firstValueFrom(source, config2) {
          var hasConfig = typeof config2 === "object";
          return new Promise(function(resolve5, reject) {
            var subscriber = new Subscriber_1.SafeSubscriber({
              next: function(value) {
                resolve5(value);
                subscriber.unsubscribe();
              },
              error: reject,
              complete: function() {
                if (hasConfig) {
                  resolve5(config2.defaultValue);
                } else {
                  reject(new EmptyError_1.EmptyError());
                }
              }
            });
            source.subscribe(subscriber);
          });
        }
        exports22.firstValueFrom = firstValueFrom;
      }
    });
    var require_ArgumentOutOfRangeError = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/ArgumentOutOfRangeError.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.ArgumentOutOfRangeError = void 0;
        var createErrorClass_1 = require_createErrorClass();
        exports22.ArgumentOutOfRangeError = createErrorClass_1.createErrorClass(function(_super) {
          return function ArgumentOutOfRangeErrorImpl() {
            _super(this);
            this.name = "ArgumentOutOfRangeError";
            this.message = "argument out of range";
          };
        });
      }
    });
    var require_NotFoundError = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/NotFoundError.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.NotFoundError = void 0;
        var createErrorClass_1 = require_createErrorClass();
        exports22.NotFoundError = createErrorClass_1.createErrorClass(function(_super) {
          return function NotFoundErrorImpl(message) {
            _super(this);
            this.name = "NotFoundError";
            this.message = message;
          };
        });
      }
    });
    var require_SequenceError = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/SequenceError.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.SequenceError = void 0;
        var createErrorClass_1 = require_createErrorClass();
        exports22.SequenceError = createErrorClass_1.createErrorClass(function(_super) {
          return function SequenceErrorImpl(message) {
            _super(this);
            this.name = "SequenceError";
            this.message = message;
          };
        });
      }
    });
    var require_isDate = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/isDate.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.isValidDate = void 0;
        function isValidDate(value) {
          return value instanceof Date && !isNaN(value);
        }
        exports22.isValidDate = isValidDate;
      }
    });
    var require_timeout = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/timeout.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.timeout = exports22.TimeoutError = void 0;
        var async_1 = require_async2();
        var isDate_1 = require_isDate();
        var lift_1 = require_lift();
        var innerFrom_1 = require_innerFrom();
        var createErrorClass_1 = require_createErrorClass();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var executeSchedule_1 = require_executeSchedule();
        exports22.TimeoutError = createErrorClass_1.createErrorClass(function(_super) {
          return function TimeoutErrorImpl(info) {
            if (info === void 0) {
              info = null;
            }
            _super(this);
            this.message = "Timeout has occurred";
            this.name = "TimeoutError";
            this.info = info;
          };
        });
        function timeout(config2, schedulerArg) {
          var _a2 = isDate_1.isValidDate(config2) ? { first: config2 } : typeof config2 === "number" ? { each: config2 } : config2, first = _a2.first, each = _a2.each, _b2 = _a2.with, _with = _b2 === void 0 ? timeoutErrorFactory : _b2, _c2 = _a2.scheduler, scheduler = _c2 === void 0 ? schedulerArg !== null && schedulerArg !== void 0 ? schedulerArg : async_1.asyncScheduler : _c2, _d = _a2.meta, meta = _d === void 0 ? null : _d;
          if (first == null && each == null) {
            throw new TypeError("No timeout provided.");
          }
          return lift_1.operate(function(source, subscriber) {
            var originalSourceSubscription;
            var timerSubscription;
            var lastValue = null;
            var seen = 0;
            var startTimer = function(delay) {
              timerSubscription = executeSchedule_1.executeSchedule(subscriber, scheduler, function() {
                try {
                  originalSourceSubscription.unsubscribe();
                  innerFrom_1.innerFrom(_with({
                    meta,
                    lastValue,
                    seen
                  })).subscribe(subscriber);
                } catch (err) {
                  subscriber.error(err);
                }
              }, delay);
            };
            originalSourceSubscription = source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.unsubscribe();
              seen++;
              subscriber.next(lastValue = value);
              each > 0 && startTimer(each);
            }, void 0, void 0, function() {
              if (!(timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.closed)) {
                timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.unsubscribe();
              }
              lastValue = null;
            }));
            !seen && startTimer(first != null ? typeof first === "number" ? first : +first - scheduler.now() : each);
          });
        }
        exports22.timeout = timeout;
        function timeoutErrorFactory(info) {
          throw new exports22.TimeoutError(info);
        }
      }
    });
    var require_map = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/map.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.map = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function map(project, thisArg) {
          return lift_1.operate(function(source, subscriber) {
            var index = 0;
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              subscriber.next(project.call(thisArg, value, index++));
            }));
          });
        }
        exports22.map = map;
      }
    });
    var require_mapOneOrManyArgs = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/mapOneOrManyArgs.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.mapOneOrManyArgs = void 0;
        var map_1 = require_map();
        var isArray = Array.isArray;
        function callOrApply(fn, args2) {
          return isArray(args2) ? fn.apply(void 0, __spreadArray2([], __read2(args2))) : fn(args2);
        }
        function mapOneOrManyArgs(fn) {
          return map_1.map(function(args2) {
            return callOrApply(fn, args2);
          });
        }
        exports22.mapOneOrManyArgs = mapOneOrManyArgs;
      }
    });
    var require_bindCallbackInternals = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/bindCallbackInternals.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.bindCallbackInternals = void 0;
        var isScheduler_1 = require_isScheduler();
        var Observable_1 = require_Observable();
        var subscribeOn_1 = require_subscribeOn();
        var mapOneOrManyArgs_1 = require_mapOneOrManyArgs();
        var observeOn_1 = require_observeOn();
        var AsyncSubject_1 = require_AsyncSubject();
        function bindCallbackInternals(isNodeStyle, callbackFunc, resultSelector, scheduler) {
          if (resultSelector) {
            if (isScheduler_1.isScheduler(resultSelector)) {
              scheduler = resultSelector;
            } else {
              return function() {
                var args2 = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                  args2[_i] = arguments[_i];
                }
                return bindCallbackInternals(isNodeStyle, callbackFunc, scheduler).apply(this, args2).pipe(mapOneOrManyArgs_1.mapOneOrManyArgs(resultSelector));
              };
            }
          }
          if (scheduler) {
            return function() {
              var args2 = [];
              for (var _i = 0; _i < arguments.length; _i++) {
                args2[_i] = arguments[_i];
              }
              return bindCallbackInternals(isNodeStyle, callbackFunc).apply(this, args2).pipe(subscribeOn_1.subscribeOn(scheduler), observeOn_1.observeOn(scheduler));
            };
          }
          return function() {
            var _this = this;
            var args2 = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              args2[_i] = arguments[_i];
            }
            var subject = new AsyncSubject_1.AsyncSubject();
            var uninitialized = true;
            return new Observable_1.Observable(function(subscriber) {
              var subs = subject.subscribe(subscriber);
              if (uninitialized) {
                uninitialized = false;
                var isAsync_1 = false;
                var isComplete_1 = false;
                callbackFunc.apply(_this, __spreadArray2(__spreadArray2([], __read2(args2)), [
                  function() {
                    var results = [];
                    for (var _i2 = 0; _i2 < arguments.length; _i2++) {
                      results[_i2] = arguments[_i2];
                    }
                    if (isNodeStyle) {
                      var err = results.shift();
                      if (err != null) {
                        subject.error(err);
                        return;
                      }
                    }
                    subject.next(1 < results.length ? results : results[0]);
                    isComplete_1 = true;
                    if (isAsync_1) {
                      subject.complete();
                    }
                  }
                ]));
                if (isComplete_1) {
                  subject.complete();
                }
                isAsync_1 = true;
              }
              return subs;
            });
          };
        }
        exports22.bindCallbackInternals = bindCallbackInternals;
      }
    });
    var require_bindCallback = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/bindCallback.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.bindCallback = void 0;
        var bindCallbackInternals_1 = require_bindCallbackInternals();
        function bindCallback(callbackFunc, resultSelector, scheduler) {
          return bindCallbackInternals_1.bindCallbackInternals(false, callbackFunc, resultSelector, scheduler);
        }
        exports22.bindCallback = bindCallback;
      }
    });
    var require_bindNodeCallback = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/bindNodeCallback.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.bindNodeCallback = void 0;
        var bindCallbackInternals_1 = require_bindCallbackInternals();
        function bindNodeCallback(callbackFunc, resultSelector, scheduler) {
          return bindCallbackInternals_1.bindCallbackInternals(true, callbackFunc, resultSelector, scheduler);
        }
        exports22.bindNodeCallback = bindNodeCallback;
      }
    });
    var require_argsArgArrayOrObject = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/argsArgArrayOrObject.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.argsArgArrayOrObject = void 0;
        var isArray = Array.isArray;
        var getPrototypeOf = Object.getPrototypeOf;
        var objectProto = Object.prototype;
        var getKeys = Object.keys;
        function argsArgArrayOrObject(args2) {
          if (args2.length === 1) {
            var first_1 = args2[0];
            if (isArray(first_1)) {
              return { args: first_1, keys: null };
            }
            if (isPOJO(first_1)) {
              var keys = getKeys(first_1);
              return {
                args: keys.map(function(key) {
                  return first_1[key];
                }),
                keys
              };
            }
          }
          return { args: args2, keys: null };
        }
        exports22.argsArgArrayOrObject = argsArgArrayOrObject;
        function isPOJO(obj) {
          return obj && typeof obj === "object" && getPrototypeOf(obj) === objectProto;
        }
      }
    });
    var require_createObject = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/createObject.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.createObject = void 0;
        function createObject(keys, values) {
          return keys.reduce(function(result, key, i) {
            return result[key] = values[i], result;
          }, {});
        }
        exports22.createObject = createObject;
      }
    });
    var require_combineLatest = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/combineLatest.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.combineLatestInit = exports22.combineLatest = void 0;
        var Observable_1 = require_Observable();
        var argsArgArrayOrObject_1 = require_argsArgArrayOrObject();
        var from_1 = require_from();
        var identity_1 = require_identity();
        var mapOneOrManyArgs_1 = require_mapOneOrManyArgs();
        var args_1 = require_args();
        var createObject_1 = require_createObject();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var executeSchedule_1 = require_executeSchedule();
        function combineLatest() {
          var args2 = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args2[_i] = arguments[_i];
          }
          var scheduler = args_1.popScheduler(args2);
          var resultSelector = args_1.popResultSelector(args2);
          var _a2 = argsArgArrayOrObject_1.argsArgArrayOrObject(args2), observables = _a2.args, keys = _a2.keys;
          if (observables.length === 0) {
            return from_1.from([], scheduler);
          }
          var result = new Observable_1.Observable(combineLatestInit(observables, scheduler, keys ? function(values) {
            return createObject_1.createObject(keys, values);
          } : identity_1.identity));
          return resultSelector ? result.pipe(mapOneOrManyArgs_1.mapOneOrManyArgs(resultSelector)) : result;
        }
        exports22.combineLatest = combineLatest;
        function combineLatestInit(observables, scheduler, valueTransform) {
          if (valueTransform === void 0) {
            valueTransform = identity_1.identity;
          }
          return function(subscriber) {
            maybeSchedule(scheduler, function() {
              var length = observables.length;
              var values = new Array(length);
              var active = length;
              var remainingFirstValues = length;
              var _loop_1 = function(i2) {
                maybeSchedule(scheduler, function() {
                  var source = from_1.from(observables[i2], scheduler);
                  var hasFirstValue = false;
                  source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
                    values[i2] = value;
                    if (!hasFirstValue) {
                      hasFirstValue = true;
                      remainingFirstValues--;
                    }
                    if (!remainingFirstValues) {
                      subscriber.next(valueTransform(values.slice()));
                    }
                  }, function() {
                    if (!--active) {
                      subscriber.complete();
                    }
                  }));
                }, subscriber);
              };
              for (var i = 0; i < length; i++) {
                _loop_1(i);
              }
            }, subscriber);
          };
        }
        exports22.combineLatestInit = combineLatestInit;
        function maybeSchedule(scheduler, execute, subscription) {
          if (scheduler) {
            executeSchedule_1.executeSchedule(subscription, scheduler, execute);
          } else {
            execute();
          }
        }
      }
    });
    var require_mergeInternals = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/mergeInternals.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.mergeInternals = void 0;
        var innerFrom_1 = require_innerFrom();
        var executeSchedule_1 = require_executeSchedule();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function mergeInternals(source, subscriber, project, concurrent, onBeforeNext, expand, innerSubScheduler, additionalFinalizer) {
          var buffer = [];
          var active = 0;
          var index = 0;
          var isComplete = false;
          var checkComplete = function() {
            if (isComplete && !buffer.length && !active) {
              subscriber.complete();
            }
          };
          var outerNext = function(value) {
            return active < concurrent ? doInnerSub(value) : buffer.push(value);
          };
          var doInnerSub = function(value) {
            expand && subscriber.next(value);
            active++;
            var innerComplete = false;
            innerFrom_1.innerFrom(project(value, index++)).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(innerValue) {
              onBeforeNext === null || onBeforeNext === void 0 ? void 0 : onBeforeNext(innerValue);
              if (expand) {
                outerNext(innerValue);
              } else {
                subscriber.next(innerValue);
              }
            }, function() {
              innerComplete = true;
            }, void 0, function() {
              if (innerComplete) {
                try {
                  active--;
                  var _loop_1 = function() {
                    var bufferedValue = buffer.shift();
                    if (innerSubScheduler) {
                      executeSchedule_1.executeSchedule(subscriber, innerSubScheduler, function() {
                        return doInnerSub(bufferedValue);
                      });
                    } else {
                      doInnerSub(bufferedValue);
                    }
                  };
                  while (buffer.length && active < concurrent) {
                    _loop_1();
                  }
                  checkComplete();
                } catch (err) {
                  subscriber.error(err);
                }
              }
            }));
          };
          source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, outerNext, function() {
            isComplete = true;
            checkComplete();
          }));
          return function() {
            additionalFinalizer === null || additionalFinalizer === void 0 ? void 0 : additionalFinalizer();
          };
        }
        exports22.mergeInternals = mergeInternals;
      }
    });
    var require_mergeMap = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/mergeMap.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.mergeMap = void 0;
        var map_1 = require_map();
        var innerFrom_1 = require_innerFrom();
        var lift_1 = require_lift();
        var mergeInternals_1 = require_mergeInternals();
        var isFunction_1 = require_isFunction();
        function mergeMap(project, resultSelector, concurrent) {
          if (concurrent === void 0) {
            concurrent = Infinity;
          }
          if (isFunction_1.isFunction(resultSelector)) {
            return mergeMap(function(a, i) {
              return map_1.map(function(b, ii) {
                return resultSelector(a, b, i, ii);
              })(innerFrom_1.innerFrom(project(a, i)));
            }, concurrent);
          } else if (typeof resultSelector === "number") {
            concurrent = resultSelector;
          }
          return lift_1.operate(function(source, subscriber) {
            return mergeInternals_1.mergeInternals(source, subscriber, project, concurrent);
          });
        }
        exports22.mergeMap = mergeMap;
      }
    });
    var require_mergeAll = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/mergeAll.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.mergeAll = void 0;
        var mergeMap_1 = require_mergeMap();
        var identity_1 = require_identity();
        function mergeAll(concurrent) {
          if (concurrent === void 0) {
            concurrent = Infinity;
          }
          return mergeMap_1.mergeMap(identity_1.identity, concurrent);
        }
        exports22.mergeAll = mergeAll;
      }
    });
    var require_concatAll = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/concatAll.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.concatAll = void 0;
        var mergeAll_1 = require_mergeAll();
        function concatAll() {
          return mergeAll_1.mergeAll(1);
        }
        exports22.concatAll = concatAll;
      }
    });
    var require_concat = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/concat.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.concat = void 0;
        var concatAll_1 = require_concatAll();
        var args_1 = require_args();
        var from_1 = require_from();
        function concat() {
          var args2 = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args2[_i] = arguments[_i];
          }
          return concatAll_1.concatAll()(from_1.from(args2, args_1.popScheduler(args2)));
        }
        exports22.concat = concat;
      }
    });
    var require_defer2 = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/defer.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.defer = void 0;
        var Observable_1 = require_Observable();
        var innerFrom_1 = require_innerFrom();
        function defer(observableFactory) {
          return new Observable_1.Observable(function(subscriber) {
            innerFrom_1.innerFrom(observableFactory()).subscribe(subscriber);
          });
        }
        exports22.defer = defer;
      }
    });
    var require_connectable = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/connectable.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.connectable = void 0;
        var Subject_1 = require_Subject();
        var Observable_1 = require_Observable();
        var defer_1 = require_defer2();
        var DEFAULT_CONFIG = {
          connector: function() {
            return new Subject_1.Subject();
          },
          resetOnDisconnect: true
        };
        function connectable(source, config2) {
          if (config2 === void 0) {
            config2 = DEFAULT_CONFIG;
          }
          var connection = null;
          var connector = config2.connector, _a2 = config2.resetOnDisconnect, resetOnDisconnect = _a2 === void 0 ? true : _a2;
          var subject = connector();
          var result = new Observable_1.Observable(function(subscriber) {
            return subject.subscribe(subscriber);
          });
          result.connect = function() {
            if (!connection || connection.closed) {
              connection = defer_1.defer(function() {
                return source;
              }).subscribe(subject);
              if (resetOnDisconnect) {
                connection.add(function() {
                  return subject = connector();
                });
              }
            }
            return connection;
          };
          return result;
        }
        exports22.connectable = connectable;
      }
    });
    var require_forkJoin = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/forkJoin.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.forkJoin = void 0;
        var Observable_1 = require_Observable();
        var argsArgArrayOrObject_1 = require_argsArgArrayOrObject();
        var innerFrom_1 = require_innerFrom();
        var args_1 = require_args();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var mapOneOrManyArgs_1 = require_mapOneOrManyArgs();
        var createObject_1 = require_createObject();
        function forkJoin() {
          var args2 = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args2[_i] = arguments[_i];
          }
          var resultSelector = args_1.popResultSelector(args2);
          var _a2 = argsArgArrayOrObject_1.argsArgArrayOrObject(args2), sources = _a2.args, keys = _a2.keys;
          var result = new Observable_1.Observable(function(subscriber) {
            var length = sources.length;
            if (!length) {
              subscriber.complete();
              return;
            }
            var values = new Array(length);
            var remainingCompletions = length;
            var remainingEmissions = length;
            var _loop_1 = function(sourceIndex2) {
              var hasValue = false;
              innerFrom_1.innerFrom(sources[sourceIndex2]).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
                if (!hasValue) {
                  hasValue = true;
                  remainingEmissions--;
                }
                values[sourceIndex2] = value;
              }, function() {
                return remainingCompletions--;
              }, void 0, function() {
                if (!remainingCompletions || !hasValue) {
                  if (!remainingEmissions) {
                    subscriber.next(keys ? createObject_1.createObject(keys, values) : values);
                  }
                  subscriber.complete();
                }
              }));
            };
            for (var sourceIndex = 0; sourceIndex < length; sourceIndex++) {
              _loop_1(sourceIndex);
            }
          });
          return resultSelector ? result.pipe(mapOneOrManyArgs_1.mapOneOrManyArgs(resultSelector)) : result;
        }
        exports22.forkJoin = forkJoin;
      }
    });
    var require_fromEvent = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/fromEvent.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.fromEvent = void 0;
        var innerFrom_1 = require_innerFrom();
        var Observable_1 = require_Observable();
        var mergeMap_1 = require_mergeMap();
        var isArrayLike_1 = require_isArrayLike();
        var isFunction_1 = require_isFunction();
        var mapOneOrManyArgs_1 = require_mapOneOrManyArgs();
        var nodeEventEmitterMethods = ["addListener", "removeListener"];
        var eventTargetMethods = ["addEventListener", "removeEventListener"];
        var jqueryMethods = ["on", "off"];
        function fromEvent(target, eventName, options, resultSelector) {
          if (isFunction_1.isFunction(options)) {
            resultSelector = options;
            options = void 0;
          }
          if (resultSelector) {
            return fromEvent(target, eventName, options).pipe(mapOneOrManyArgs_1.mapOneOrManyArgs(resultSelector));
          }
          var _a2 = __read2(isEventTarget(target) ? eventTargetMethods.map(function(methodName) {
            return function(handler) {
              return target[methodName](eventName, handler, options);
            };
          }) : isNodeStyleEventEmitter(target) ? nodeEventEmitterMethods.map(toCommonHandlerRegistry(target, eventName)) : isJQueryStyleEventEmitter(target) ? jqueryMethods.map(toCommonHandlerRegistry(target, eventName)) : [], 2), add = _a2[0], remove = _a2[1];
          if (!add) {
            if (isArrayLike_1.isArrayLike(target)) {
              return mergeMap_1.mergeMap(function(subTarget) {
                return fromEvent(subTarget, eventName, options);
              })(innerFrom_1.innerFrom(target));
            }
          }
          if (!add) {
            throw new TypeError("Invalid event target");
          }
          return new Observable_1.Observable(function(subscriber) {
            var handler = function() {
              var args2 = [];
              for (var _i = 0; _i < arguments.length; _i++) {
                args2[_i] = arguments[_i];
              }
              return subscriber.next(1 < args2.length ? args2 : args2[0]);
            };
            add(handler);
            return function() {
              return remove(handler);
            };
          });
        }
        exports22.fromEvent = fromEvent;
        function toCommonHandlerRegistry(target, eventName) {
          return function(methodName) {
            return function(handler) {
              return target[methodName](eventName, handler);
            };
          };
        }
        function isNodeStyleEventEmitter(target) {
          return isFunction_1.isFunction(target.addListener) && isFunction_1.isFunction(target.removeListener);
        }
        function isJQueryStyleEventEmitter(target) {
          return isFunction_1.isFunction(target.on) && isFunction_1.isFunction(target.off);
        }
        function isEventTarget(target) {
          return isFunction_1.isFunction(target.addEventListener) && isFunction_1.isFunction(target.removeEventListener);
        }
      }
    });
    var require_fromEventPattern = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/fromEventPattern.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.fromEventPattern = void 0;
        var Observable_1 = require_Observable();
        var isFunction_1 = require_isFunction();
        var mapOneOrManyArgs_1 = require_mapOneOrManyArgs();
        function fromEventPattern(addHandler, removeHandler, resultSelector) {
          if (resultSelector) {
            return fromEventPattern(addHandler, removeHandler).pipe(mapOneOrManyArgs_1.mapOneOrManyArgs(resultSelector));
          }
          return new Observable_1.Observable(function(subscriber) {
            var handler = function() {
              var e = [];
              for (var _i = 0; _i < arguments.length; _i++) {
                e[_i] = arguments[_i];
              }
              return subscriber.next(e.length === 1 ? e[0] : e);
            };
            var retValue = addHandler(handler);
            return isFunction_1.isFunction(removeHandler) ? function() {
              return removeHandler(handler, retValue);
            } : void 0;
          });
        }
        exports22.fromEventPattern = fromEventPattern;
      }
    });
    var require_generate = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/generate.js"(exports22) {
        "use strict";
        var __generator2 = exports22 && exports22.__generator || function(thisArg, body) {
          var _ = { label: 0, sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
          }, trys: [], ops: [] }, f, y, t, g;
          return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
            return this;
          }), g;
          function verb(n) {
            return function(v) {
              return step([n, v]);
            };
          }
          function step(op) {
            if (f) throw new TypeError("Generator is already executing.");
            while (_) try {
              if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
              if (y = 0, t) op = [op[0] & 2, t.value];
              switch (op[0]) {
                case 0:
                case 1:
                  t = op;
                  break;
                case 4:
                  _.label++;
                  return { value: op[1], done: false };
                case 5:
                  _.label++;
                  y = op[1];
                  op = [0];
                  continue;
                case 7:
                  op = _.ops.pop();
                  _.trys.pop();
                  continue;
                default:
                  if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                    _ = 0;
                    continue;
                  }
                  if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                    _.label = op[1];
                    break;
                  }
                  if (op[0] === 6 && _.label < t[1]) {
                    _.label = t[1];
                    t = op;
                    break;
                  }
                  if (t && _.label < t[2]) {
                    _.label = t[2];
                    _.ops.push(op);
                    break;
                  }
                  if (t[2]) _.ops.pop();
                  _.trys.pop();
                  continue;
              }
              op = body.call(thisArg, _);
            } catch (e) {
              op = [6, e];
              y = 0;
            } finally {
              f = t = 0;
            }
            if (op[0] & 5) throw op[1];
            return { value: op[0] ? op[1] : void 0, done: true };
          }
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.generate = void 0;
        var identity_1 = require_identity();
        var isScheduler_1 = require_isScheduler();
        var defer_1 = require_defer2();
        var scheduleIterable_1 = require_scheduleIterable();
        function generate(initialStateOrOptions, condition, iterate, resultSelectorOrScheduler, scheduler) {
          var _a2, _b2;
          var resultSelector;
          var initialState;
          if (arguments.length === 1) {
            _a2 = initialStateOrOptions, initialState = _a2.initialState, condition = _a2.condition, iterate = _a2.iterate, _b2 = _a2.resultSelector, resultSelector = _b2 === void 0 ? identity_1.identity : _b2, scheduler = _a2.scheduler;
          } else {
            initialState = initialStateOrOptions;
            if (!resultSelectorOrScheduler || isScheduler_1.isScheduler(resultSelectorOrScheduler)) {
              resultSelector = identity_1.identity;
              scheduler = resultSelectorOrScheduler;
            } else {
              resultSelector = resultSelectorOrScheduler;
            }
          }
          function gen() {
            var state;
            return __generator2(this, function(_a22) {
              switch (_a22.label) {
                case 0:
                  state = initialState;
                  _a22.label = 1;
                case 1:
                  if (!(!condition || condition(state))) return [3, 4];
                  return [4, resultSelector(state)];
                case 2:
                  _a22.sent();
                  _a22.label = 3;
                case 3:
                  state = iterate(state);
                  return [3, 1];
                case 4:
                  return [2];
              }
            });
          }
          return defer_1.defer(scheduler ? function() {
            return scheduleIterable_1.scheduleIterable(gen(), scheduler);
          } : gen);
        }
        exports22.generate = generate;
      }
    });
    var require_iif = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/iif.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.iif = void 0;
        var defer_1 = require_defer2();
        function iif(condition, trueResult, falseResult) {
          return defer_1.defer(function() {
            return condition() ? trueResult : falseResult;
          });
        }
        exports22.iif = iif;
      }
    });
    var require_timer = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/timer.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.timer = void 0;
        var Observable_1 = require_Observable();
        var async_1 = require_async2();
        var isScheduler_1 = require_isScheduler();
        var isDate_1 = require_isDate();
        function timer(dueTime, intervalOrScheduler, scheduler) {
          if (dueTime === void 0) {
            dueTime = 0;
          }
          if (scheduler === void 0) {
            scheduler = async_1.async;
          }
          var intervalDuration = -1;
          if (intervalOrScheduler != null) {
            if (isScheduler_1.isScheduler(intervalOrScheduler)) {
              scheduler = intervalOrScheduler;
            } else {
              intervalDuration = intervalOrScheduler;
            }
          }
          return new Observable_1.Observable(function(subscriber) {
            var due = isDate_1.isValidDate(dueTime) ? +dueTime - scheduler.now() : dueTime;
            if (due < 0) {
              due = 0;
            }
            var n = 0;
            return scheduler.schedule(function() {
              if (!subscriber.closed) {
                subscriber.next(n++);
                if (0 <= intervalDuration) {
                  this.schedule(void 0, intervalDuration);
                } else {
                  subscriber.complete();
                }
              }
            }, due);
          });
        }
        exports22.timer = timer;
      }
    });
    var require_interval = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/interval.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.interval = void 0;
        var async_1 = require_async2();
        var timer_1 = require_timer();
        function interval(period, scheduler) {
          if (period === void 0) {
            period = 0;
          }
          if (scheduler === void 0) {
            scheduler = async_1.asyncScheduler;
          }
          if (period < 0) {
            period = 0;
          }
          return timer_1.timer(period, period, scheduler);
        }
        exports22.interval = interval;
      }
    });
    var require_merge = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/merge.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.merge = void 0;
        var mergeAll_1 = require_mergeAll();
        var innerFrom_1 = require_innerFrom();
        var empty_1 = require_empty();
        var args_1 = require_args();
        var from_1 = require_from();
        function merge() {
          var args2 = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args2[_i] = arguments[_i];
          }
          var scheduler = args_1.popScheduler(args2);
          var concurrent = args_1.popNumber(args2, Infinity);
          var sources = args2;
          return !sources.length ? empty_1.EMPTY : sources.length === 1 ? innerFrom_1.innerFrom(sources[0]) : mergeAll_1.mergeAll(concurrent)(from_1.from(sources, scheduler));
        }
        exports22.merge = merge;
      }
    });
    var require_never = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/never.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.never = exports22.NEVER = void 0;
        var Observable_1 = require_Observable();
        var noop_1 = require_noop();
        exports22.NEVER = new Observable_1.Observable(noop_1.noop);
        function never() {
          return exports22.NEVER;
        }
        exports22.never = never;
      }
    });
    var require_argsOrArgArray = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/argsOrArgArray.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.argsOrArgArray = void 0;
        var isArray = Array.isArray;
        function argsOrArgArray(args2) {
          return args2.length === 1 && isArray(args2[0]) ? args2[0] : args2;
        }
        exports22.argsOrArgArray = argsOrArgArray;
      }
    });
    var require_onErrorResumeNext = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/onErrorResumeNext.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.onErrorResumeNext = void 0;
        var Observable_1 = require_Observable();
        var argsOrArgArray_1 = require_argsOrArgArray();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var noop_1 = require_noop();
        var innerFrom_1 = require_innerFrom();
        function onErrorResumeNext() {
          var sources = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            sources[_i] = arguments[_i];
          }
          var nextSources = argsOrArgArray_1.argsOrArgArray(sources);
          return new Observable_1.Observable(function(subscriber) {
            var sourceIndex = 0;
            var subscribeNext = function() {
              if (sourceIndex < nextSources.length) {
                var nextSource = void 0;
                try {
                  nextSource = innerFrom_1.innerFrom(nextSources[sourceIndex++]);
                } catch (err) {
                  subscribeNext();
                  return;
                }
                var innerSubscriber = new OperatorSubscriber_1.OperatorSubscriber(subscriber, void 0, noop_1.noop, noop_1.noop);
                nextSource.subscribe(innerSubscriber);
                innerSubscriber.add(subscribeNext);
              } else {
                subscriber.complete();
              }
            };
            subscribeNext();
          });
        }
        exports22.onErrorResumeNext = onErrorResumeNext;
      }
    });
    var require_pairs = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/pairs.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.pairs = void 0;
        var from_1 = require_from();
        function pairs(obj, scheduler) {
          return from_1.from(Object.entries(obj), scheduler);
        }
        exports22.pairs = pairs;
      }
    });
    var require_not = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/util/not.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.not = void 0;
        function not(pred, thisArg) {
          return function(value, index) {
            return !pred.call(thisArg, value, index);
          };
        }
        exports22.not = not;
      }
    });
    var require_filter = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/filter.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.filter = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function filter(predicate, thisArg) {
          return lift_1.operate(function(source, subscriber) {
            var index = 0;
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              return predicate.call(thisArg, value, index++) && subscriber.next(value);
            }));
          });
        }
        exports22.filter = filter;
      }
    });
    var require_partition = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/partition.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.partition = void 0;
        var not_1 = require_not();
        var filter_1 = require_filter();
        var innerFrom_1 = require_innerFrom();
        function partition(source, predicate, thisArg) {
          return [filter_1.filter(predicate, thisArg)(innerFrom_1.innerFrom(source)), filter_1.filter(not_1.not(predicate, thisArg))(innerFrom_1.innerFrom(source))];
        }
        exports22.partition = partition;
      }
    });
    var require_race = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/race.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.raceInit = exports22.race = void 0;
        var Observable_1 = require_Observable();
        var innerFrom_1 = require_innerFrom();
        var argsOrArgArray_1 = require_argsOrArgArray();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function race() {
          var sources = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            sources[_i] = arguments[_i];
          }
          sources = argsOrArgArray_1.argsOrArgArray(sources);
          return sources.length === 1 ? innerFrom_1.innerFrom(sources[0]) : new Observable_1.Observable(raceInit(sources));
        }
        exports22.race = race;
        function raceInit(sources) {
          return function(subscriber) {
            var subscriptions = [];
            var _loop_1 = function(i2) {
              subscriptions.push(innerFrom_1.innerFrom(sources[i2]).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
                if (subscriptions) {
                  for (var s = 0; s < subscriptions.length; s++) {
                    s !== i2 && subscriptions[s].unsubscribe();
                  }
                  subscriptions = null;
                }
                subscriber.next(value);
              })));
            };
            for (var i = 0; subscriptions && !subscriber.closed && i < sources.length; i++) {
              _loop_1(i);
            }
          };
        }
        exports22.raceInit = raceInit;
      }
    });
    var require_range3 = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/range.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.range = void 0;
        var Observable_1 = require_Observable();
        var empty_1 = require_empty();
        function range(start, count, scheduler) {
          if (count == null) {
            count = start;
            start = 0;
          }
          if (count <= 0) {
            return empty_1.EMPTY;
          }
          var end = count + start;
          return new Observable_1.Observable(scheduler ? function(subscriber) {
            var n = start;
            return scheduler.schedule(function() {
              if (n < end) {
                subscriber.next(n++);
                this.schedule();
              } else {
                subscriber.complete();
              }
            });
          } : function(subscriber) {
            var n = start;
            while (n < end && !subscriber.closed) {
              subscriber.next(n++);
            }
            subscriber.complete();
          });
        }
        exports22.range = range;
      }
    });
    var require_using = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/using.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.using = void 0;
        var Observable_1 = require_Observable();
        var innerFrom_1 = require_innerFrom();
        var empty_1 = require_empty();
        function using(resourceFactory, observableFactory) {
          return new Observable_1.Observable(function(subscriber) {
            var resource = resourceFactory();
            var result = observableFactory(resource);
            var source = result ? innerFrom_1.innerFrom(result) : empty_1.EMPTY;
            source.subscribe(subscriber);
            return function() {
              if (resource) {
                resource.unsubscribe();
              }
            };
          });
        }
        exports22.using = using;
      }
    });
    var require_zip = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/zip.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.zip = void 0;
        var Observable_1 = require_Observable();
        var innerFrom_1 = require_innerFrom();
        var argsOrArgArray_1 = require_argsOrArgArray();
        var empty_1 = require_empty();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var args_1 = require_args();
        function zip() {
          var args2 = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args2[_i] = arguments[_i];
          }
          var resultSelector = args_1.popResultSelector(args2);
          var sources = argsOrArgArray_1.argsOrArgArray(args2);
          return sources.length ? new Observable_1.Observable(function(subscriber) {
            var buffers = sources.map(function() {
              return [];
            });
            var completed = sources.map(function() {
              return false;
            });
            subscriber.add(function() {
              buffers = completed = null;
            });
            var _loop_1 = function(sourceIndex2) {
              innerFrom_1.innerFrom(sources[sourceIndex2]).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
                buffers[sourceIndex2].push(value);
                if (buffers.every(function(buffer) {
                  return buffer.length;
                })) {
                  var result = buffers.map(function(buffer) {
                    return buffer.shift();
                  });
                  subscriber.next(resultSelector ? resultSelector.apply(void 0, __spreadArray2([], __read2(result))) : result);
                  if (buffers.some(function(buffer, i) {
                    return !buffer.length && completed[i];
                  })) {
                    subscriber.complete();
                  }
                }
              }, function() {
                completed[sourceIndex2] = true;
                !buffers[sourceIndex2].length && subscriber.complete();
              }));
            };
            for (var sourceIndex = 0; !subscriber.closed && sourceIndex < sources.length; sourceIndex++) {
              _loop_1(sourceIndex);
            }
            return function() {
              buffers = completed = null;
            };
          }) : empty_1.EMPTY;
        }
        exports22.zip = zip;
      }
    });
    var require_types4 = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/types.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
      }
    });
    var require_audit = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/audit.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.audit = void 0;
        var lift_1 = require_lift();
        var innerFrom_1 = require_innerFrom();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function audit(durationSelector) {
          return lift_1.operate(function(source, subscriber) {
            var hasValue = false;
            var lastValue = null;
            var durationSubscriber = null;
            var isComplete = false;
            var endDuration = function() {
              durationSubscriber === null || durationSubscriber === void 0 ? void 0 : durationSubscriber.unsubscribe();
              durationSubscriber = null;
              if (hasValue) {
                hasValue = false;
                var value = lastValue;
                lastValue = null;
                subscriber.next(value);
              }
              isComplete && subscriber.complete();
            };
            var cleanupDuration = function() {
              durationSubscriber = null;
              isComplete && subscriber.complete();
            };
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              hasValue = true;
              lastValue = value;
              if (!durationSubscriber) {
                innerFrom_1.innerFrom(durationSelector(value)).subscribe(durationSubscriber = OperatorSubscriber_1.createOperatorSubscriber(subscriber, endDuration, cleanupDuration));
              }
            }, function() {
              isComplete = true;
              (!hasValue || !durationSubscriber || durationSubscriber.closed) && subscriber.complete();
            }));
          });
        }
        exports22.audit = audit;
      }
    });
    var require_auditTime = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/auditTime.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.auditTime = void 0;
        var async_1 = require_async2();
        var audit_1 = require_audit();
        var timer_1 = require_timer();
        function auditTime(duration, scheduler) {
          if (scheduler === void 0) {
            scheduler = async_1.asyncScheduler;
          }
          return audit_1.audit(function() {
            return timer_1.timer(duration, scheduler);
          });
        }
        exports22.auditTime = auditTime;
      }
    });
    var require_buffer = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/buffer.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.buffer = void 0;
        var lift_1 = require_lift();
        var noop_1 = require_noop();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var innerFrom_1 = require_innerFrom();
        function buffer(closingNotifier) {
          return lift_1.operate(function(source, subscriber) {
            var currentBuffer = [];
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              return currentBuffer.push(value);
            }, function() {
              subscriber.next(currentBuffer);
              subscriber.complete();
            }));
            innerFrom_1.innerFrom(closingNotifier).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function() {
              var b = currentBuffer;
              currentBuffer = [];
              subscriber.next(b);
            }, noop_1.noop));
            return function() {
              currentBuffer = null;
            };
          });
        }
        exports22.buffer = buffer;
      }
    });
    var require_bufferCount = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/bufferCount.js"(exports22) {
        "use strict";
        var __values2 = exports22 && exports22.__values || function(o) {
          var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
          if (m) return m.call(o);
          if (o && typeof o.length === "number") return {
            next: function() {
              if (o && i >= o.length) o = void 0;
              return { value: o && o[i++], done: !o };
            }
          };
          throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.bufferCount = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var arrRemove_1 = require_arrRemove();
        function bufferCount(bufferSize, startBufferEvery) {
          if (startBufferEvery === void 0) {
            startBufferEvery = null;
          }
          startBufferEvery = startBufferEvery !== null && startBufferEvery !== void 0 ? startBufferEvery : bufferSize;
          return lift_1.operate(function(source, subscriber) {
            var buffers = [];
            var count = 0;
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              var e_1, _a2, e_2, _b2;
              var toEmit = null;
              if (count++ % startBufferEvery === 0) {
                buffers.push([]);
              }
              try {
                for (var buffers_1 = __values2(buffers), buffers_1_1 = buffers_1.next(); !buffers_1_1.done; buffers_1_1 = buffers_1.next()) {
                  var buffer = buffers_1_1.value;
                  buffer.push(value);
                  if (bufferSize <= buffer.length) {
                    toEmit = toEmit !== null && toEmit !== void 0 ? toEmit : [];
                    toEmit.push(buffer);
                  }
                }
              } catch (e_1_1) {
                e_1 = { error: e_1_1 };
              } finally {
                try {
                  if (buffers_1_1 && !buffers_1_1.done && (_a2 = buffers_1.return)) _a2.call(buffers_1);
                } finally {
                  if (e_1) throw e_1.error;
                }
              }
              if (toEmit) {
                try {
                  for (var toEmit_1 = __values2(toEmit), toEmit_1_1 = toEmit_1.next(); !toEmit_1_1.done; toEmit_1_1 = toEmit_1.next()) {
                    var buffer = toEmit_1_1.value;
                    arrRemove_1.arrRemove(buffers, buffer);
                    subscriber.next(buffer);
                  }
                } catch (e_2_1) {
                  e_2 = { error: e_2_1 };
                } finally {
                  try {
                    if (toEmit_1_1 && !toEmit_1_1.done && (_b2 = toEmit_1.return)) _b2.call(toEmit_1);
                  } finally {
                    if (e_2) throw e_2.error;
                  }
                }
              }
            }, function() {
              var e_3, _a2;
              try {
                for (var buffers_2 = __values2(buffers), buffers_2_1 = buffers_2.next(); !buffers_2_1.done; buffers_2_1 = buffers_2.next()) {
                  var buffer = buffers_2_1.value;
                  subscriber.next(buffer);
                }
              } catch (e_3_1) {
                e_3 = { error: e_3_1 };
              } finally {
                try {
                  if (buffers_2_1 && !buffers_2_1.done && (_a2 = buffers_2.return)) _a2.call(buffers_2);
                } finally {
                  if (e_3) throw e_3.error;
                }
              }
              subscriber.complete();
            }, void 0, function() {
              buffers = null;
            }));
          });
        }
        exports22.bufferCount = bufferCount;
      }
    });
    var require_bufferTime = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/bufferTime.js"(exports22) {
        "use strict";
        var __values2 = exports22 && exports22.__values || function(o) {
          var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
          if (m) return m.call(o);
          if (o && typeof o.length === "number") return {
            next: function() {
              if (o && i >= o.length) o = void 0;
              return { value: o && o[i++], done: !o };
            }
          };
          throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.bufferTime = void 0;
        var Subscription_1 = require_Subscription();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var arrRemove_1 = require_arrRemove();
        var async_1 = require_async2();
        var args_1 = require_args();
        var executeSchedule_1 = require_executeSchedule();
        function bufferTime(bufferTimeSpan) {
          var _a2, _b2;
          var otherArgs = [];
          for (var _i = 1; _i < arguments.length; _i++) {
            otherArgs[_i - 1] = arguments[_i];
          }
          var scheduler = (_a2 = args_1.popScheduler(otherArgs)) !== null && _a2 !== void 0 ? _a2 : async_1.asyncScheduler;
          var bufferCreationInterval = (_b2 = otherArgs[0]) !== null && _b2 !== void 0 ? _b2 : null;
          var maxBufferSize = otherArgs[1] || Infinity;
          return lift_1.operate(function(source, subscriber) {
            var bufferRecords = [];
            var restartOnEmit = false;
            var emit = function(record) {
              var buffer = record.buffer, subs = record.subs;
              subs.unsubscribe();
              arrRemove_1.arrRemove(bufferRecords, record);
              subscriber.next(buffer);
              restartOnEmit && startBuffer();
            };
            var startBuffer = function() {
              if (bufferRecords) {
                var subs = new Subscription_1.Subscription();
                subscriber.add(subs);
                var buffer = [];
                var record_1 = {
                  buffer,
                  subs
                };
                bufferRecords.push(record_1);
                executeSchedule_1.executeSchedule(subs, scheduler, function() {
                  return emit(record_1);
                }, bufferTimeSpan);
              }
            };
            if (bufferCreationInterval !== null && bufferCreationInterval >= 0) {
              executeSchedule_1.executeSchedule(subscriber, scheduler, startBuffer, bufferCreationInterval, true);
            } else {
              restartOnEmit = true;
            }
            startBuffer();
            var bufferTimeSubscriber = OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              var e_1, _a22;
              var recordsCopy = bufferRecords.slice();
              try {
                for (var recordsCopy_1 = __values2(recordsCopy), recordsCopy_1_1 = recordsCopy_1.next(); !recordsCopy_1_1.done; recordsCopy_1_1 = recordsCopy_1.next()) {
                  var record = recordsCopy_1_1.value;
                  var buffer = record.buffer;
                  buffer.push(value);
                  maxBufferSize <= buffer.length && emit(record);
                }
              } catch (e_1_1) {
                e_1 = { error: e_1_1 };
              } finally {
                try {
                  if (recordsCopy_1_1 && !recordsCopy_1_1.done && (_a22 = recordsCopy_1.return)) _a22.call(recordsCopy_1);
                } finally {
                  if (e_1) throw e_1.error;
                }
              }
            }, function() {
              while (bufferRecords === null || bufferRecords === void 0 ? void 0 : bufferRecords.length) {
                subscriber.next(bufferRecords.shift().buffer);
              }
              bufferTimeSubscriber === null || bufferTimeSubscriber === void 0 ? void 0 : bufferTimeSubscriber.unsubscribe();
              subscriber.complete();
              subscriber.unsubscribe();
            }, void 0, function() {
              return bufferRecords = null;
            });
            source.subscribe(bufferTimeSubscriber);
          });
        }
        exports22.bufferTime = bufferTime;
      }
    });
    var require_bufferToggle = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/bufferToggle.js"(exports22) {
        "use strict";
        var __values2 = exports22 && exports22.__values || function(o) {
          var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
          if (m) return m.call(o);
          if (o && typeof o.length === "number") return {
            next: function() {
              if (o && i >= o.length) o = void 0;
              return { value: o && o[i++], done: !o };
            }
          };
          throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.bufferToggle = void 0;
        var Subscription_1 = require_Subscription();
        var lift_1 = require_lift();
        var innerFrom_1 = require_innerFrom();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var noop_1 = require_noop();
        var arrRemove_1 = require_arrRemove();
        function bufferToggle(openings, closingSelector) {
          return lift_1.operate(function(source, subscriber) {
            var buffers = [];
            innerFrom_1.innerFrom(openings).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(openValue) {
              var buffer = [];
              buffers.push(buffer);
              var closingSubscription = new Subscription_1.Subscription();
              var emitBuffer = function() {
                arrRemove_1.arrRemove(buffers, buffer);
                subscriber.next(buffer);
                closingSubscription.unsubscribe();
              };
              closingSubscription.add(innerFrom_1.innerFrom(closingSelector(openValue)).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, emitBuffer, noop_1.noop)));
            }, noop_1.noop));
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              var e_1, _a2;
              try {
                for (var buffers_1 = __values2(buffers), buffers_1_1 = buffers_1.next(); !buffers_1_1.done; buffers_1_1 = buffers_1.next()) {
                  var buffer = buffers_1_1.value;
                  buffer.push(value);
                }
              } catch (e_1_1) {
                e_1 = { error: e_1_1 };
              } finally {
                try {
                  if (buffers_1_1 && !buffers_1_1.done && (_a2 = buffers_1.return)) _a2.call(buffers_1);
                } finally {
                  if (e_1) throw e_1.error;
                }
              }
            }, function() {
              while (buffers.length > 0) {
                subscriber.next(buffers.shift());
              }
              subscriber.complete();
            }));
          });
        }
        exports22.bufferToggle = bufferToggle;
      }
    });
    var require_bufferWhen = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/bufferWhen.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.bufferWhen = void 0;
        var lift_1 = require_lift();
        var noop_1 = require_noop();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var innerFrom_1 = require_innerFrom();
        function bufferWhen(closingSelector) {
          return lift_1.operate(function(source, subscriber) {
            var buffer = null;
            var closingSubscriber = null;
            var openBuffer = function() {
              closingSubscriber === null || closingSubscriber === void 0 ? void 0 : closingSubscriber.unsubscribe();
              var b = buffer;
              buffer = [];
              b && subscriber.next(b);
              innerFrom_1.innerFrom(closingSelector()).subscribe(closingSubscriber = OperatorSubscriber_1.createOperatorSubscriber(subscriber, openBuffer, noop_1.noop));
            };
            openBuffer();
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              return buffer === null || buffer === void 0 ? void 0 : buffer.push(value);
            }, function() {
              buffer && subscriber.next(buffer);
              subscriber.complete();
            }, void 0, function() {
              return buffer = closingSubscriber = null;
            }));
          });
        }
        exports22.bufferWhen = bufferWhen;
      }
    });
    var require_catchError = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/catchError.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.catchError = void 0;
        var innerFrom_1 = require_innerFrom();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var lift_1 = require_lift();
        function catchError(selector) {
          return lift_1.operate(function(source, subscriber) {
            var innerSub = null;
            var syncUnsub = false;
            var handledResult;
            innerSub = source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, void 0, void 0, function(err) {
              handledResult = innerFrom_1.innerFrom(selector(err, catchError(selector)(source)));
              if (innerSub) {
                innerSub.unsubscribe();
                innerSub = null;
                handledResult.subscribe(subscriber);
              } else {
                syncUnsub = true;
              }
            }));
            if (syncUnsub) {
              innerSub.unsubscribe();
              innerSub = null;
              handledResult.subscribe(subscriber);
            }
          });
        }
        exports22.catchError = catchError;
      }
    });
    var require_scanInternals = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/scanInternals.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.scanInternals = void 0;
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function scanInternals(accumulator, seed, hasSeed, emitOnNext, emitBeforeComplete) {
          return function(source, subscriber) {
            var hasState = hasSeed;
            var state = seed;
            var index = 0;
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              var i = index++;
              state = hasState ? accumulator(state, value, i) : (hasState = true, value);
              emitOnNext && subscriber.next(state);
            }, emitBeforeComplete && (function() {
              hasState && subscriber.next(state);
              subscriber.complete();
            })));
          };
        }
        exports22.scanInternals = scanInternals;
      }
    });
    var require_reduce = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/reduce.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.reduce = void 0;
        var scanInternals_1 = require_scanInternals();
        var lift_1 = require_lift();
        function reduce(accumulator, seed) {
          return lift_1.operate(scanInternals_1.scanInternals(accumulator, seed, arguments.length >= 2, false, true));
        }
        exports22.reduce = reduce;
      }
    });
    var require_toArray = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/toArray.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.toArray = void 0;
        var reduce_1 = require_reduce();
        var lift_1 = require_lift();
        var arrReducer = function(arr, value) {
          return arr.push(value), arr;
        };
        function toArray() {
          return lift_1.operate(function(source, subscriber) {
            reduce_1.reduce(arrReducer, [])(source).subscribe(subscriber);
          });
        }
        exports22.toArray = toArray;
      }
    });
    var require_joinAllInternals = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/joinAllInternals.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.joinAllInternals = void 0;
        var identity_1 = require_identity();
        var mapOneOrManyArgs_1 = require_mapOneOrManyArgs();
        var pipe_1 = require_pipe();
        var mergeMap_1 = require_mergeMap();
        var toArray_1 = require_toArray();
        function joinAllInternals(joinFn, project) {
          return pipe_1.pipe(toArray_1.toArray(), mergeMap_1.mergeMap(function(sources) {
            return joinFn(sources);
          }), project ? mapOneOrManyArgs_1.mapOneOrManyArgs(project) : identity_1.identity);
        }
        exports22.joinAllInternals = joinAllInternals;
      }
    });
    var require_combineLatestAll = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/combineLatestAll.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.combineLatestAll = void 0;
        var combineLatest_1 = require_combineLatest();
        var joinAllInternals_1 = require_joinAllInternals();
        function combineLatestAll(project) {
          return joinAllInternals_1.joinAllInternals(combineLatest_1.combineLatest, project);
        }
        exports22.combineLatestAll = combineLatestAll;
      }
    });
    var require_combineAll = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/combineAll.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.combineAll = void 0;
        var combineLatestAll_1 = require_combineLatestAll();
        exports22.combineAll = combineLatestAll_1.combineLatestAll;
      }
    });
    var require_combineLatest2 = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/combineLatest.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.combineLatest = void 0;
        var combineLatest_1 = require_combineLatest();
        var lift_1 = require_lift();
        var argsOrArgArray_1 = require_argsOrArgArray();
        var mapOneOrManyArgs_1 = require_mapOneOrManyArgs();
        var pipe_1 = require_pipe();
        var args_1 = require_args();
        function combineLatest() {
          var args2 = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args2[_i] = arguments[_i];
          }
          var resultSelector = args_1.popResultSelector(args2);
          return resultSelector ? pipe_1.pipe(combineLatest.apply(void 0, __spreadArray2([], __read2(args2))), mapOneOrManyArgs_1.mapOneOrManyArgs(resultSelector)) : lift_1.operate(function(source, subscriber) {
            combineLatest_1.combineLatestInit(__spreadArray2([source], __read2(argsOrArgArray_1.argsOrArgArray(args2))))(subscriber);
          });
        }
        exports22.combineLatest = combineLatest;
      }
    });
    var require_combineLatestWith = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/combineLatestWith.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.combineLatestWith = void 0;
        var combineLatest_1 = require_combineLatest2();
        function combineLatestWith() {
          var otherSources = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            otherSources[_i] = arguments[_i];
          }
          return combineLatest_1.combineLatest.apply(void 0, __spreadArray2([], __read2(otherSources)));
        }
        exports22.combineLatestWith = combineLatestWith;
      }
    });
    var require_concatMap = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/concatMap.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.concatMap = void 0;
        var mergeMap_1 = require_mergeMap();
        var isFunction_1 = require_isFunction();
        function concatMap(project, resultSelector) {
          return isFunction_1.isFunction(resultSelector) ? mergeMap_1.mergeMap(project, resultSelector, 1) : mergeMap_1.mergeMap(project, 1);
        }
        exports22.concatMap = concatMap;
      }
    });
    var require_concatMapTo = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/concatMapTo.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.concatMapTo = void 0;
        var concatMap_1 = require_concatMap();
        var isFunction_1 = require_isFunction();
        function concatMapTo(innerObservable, resultSelector) {
          return isFunction_1.isFunction(resultSelector) ? concatMap_1.concatMap(function() {
            return innerObservable;
          }, resultSelector) : concatMap_1.concatMap(function() {
            return innerObservable;
          });
        }
        exports22.concatMapTo = concatMapTo;
      }
    });
    var require_concat2 = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/concat.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.concat = void 0;
        var lift_1 = require_lift();
        var concatAll_1 = require_concatAll();
        var args_1 = require_args();
        var from_1 = require_from();
        function concat() {
          var args2 = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args2[_i] = arguments[_i];
          }
          var scheduler = args_1.popScheduler(args2);
          return lift_1.operate(function(source, subscriber) {
            concatAll_1.concatAll()(from_1.from(__spreadArray2([source], __read2(args2)), scheduler)).subscribe(subscriber);
          });
        }
        exports22.concat = concat;
      }
    });
    var require_concatWith = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/concatWith.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.concatWith = void 0;
        var concat_1 = require_concat2();
        function concatWith() {
          var otherSources = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            otherSources[_i] = arguments[_i];
          }
          return concat_1.concat.apply(void 0, __spreadArray2([], __read2(otherSources)));
        }
        exports22.concatWith = concatWith;
      }
    });
    var require_fromSubscribable = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/observable/fromSubscribable.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.fromSubscribable = void 0;
        var Observable_1 = require_Observable();
        function fromSubscribable(subscribable) {
          return new Observable_1.Observable(function(subscriber) {
            return subscribable.subscribe(subscriber);
          });
        }
        exports22.fromSubscribable = fromSubscribable;
      }
    });
    var require_connect = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/connect.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.connect = void 0;
        var Subject_1 = require_Subject();
        var innerFrom_1 = require_innerFrom();
        var lift_1 = require_lift();
        var fromSubscribable_1 = require_fromSubscribable();
        var DEFAULT_CONFIG = {
          connector: function() {
            return new Subject_1.Subject();
          }
        };
        function connect(selector, config2) {
          if (config2 === void 0) {
            config2 = DEFAULT_CONFIG;
          }
          var connector = config2.connector;
          return lift_1.operate(function(source, subscriber) {
            var subject = connector();
            innerFrom_1.innerFrom(selector(fromSubscribable_1.fromSubscribable(subject))).subscribe(subscriber);
            subscriber.add(source.subscribe(subject));
          });
        }
        exports22.connect = connect;
      }
    });
    var require_count = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/count.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.count = void 0;
        var reduce_1 = require_reduce();
        function count(predicate) {
          return reduce_1.reduce(function(total, value, i) {
            return !predicate || predicate(value, i) ? total + 1 : total;
          }, 0);
        }
        exports22.count = count;
      }
    });
    var require_debounce = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/debounce.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.debounce = void 0;
        var lift_1 = require_lift();
        var noop_1 = require_noop();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var innerFrom_1 = require_innerFrom();
        function debounce(durationSelector) {
          return lift_1.operate(function(source, subscriber) {
            var hasValue = false;
            var lastValue = null;
            var durationSubscriber = null;
            var emit = function() {
              durationSubscriber === null || durationSubscriber === void 0 ? void 0 : durationSubscriber.unsubscribe();
              durationSubscriber = null;
              if (hasValue) {
                hasValue = false;
                var value = lastValue;
                lastValue = null;
                subscriber.next(value);
              }
            };
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              durationSubscriber === null || durationSubscriber === void 0 ? void 0 : durationSubscriber.unsubscribe();
              hasValue = true;
              lastValue = value;
              durationSubscriber = OperatorSubscriber_1.createOperatorSubscriber(subscriber, emit, noop_1.noop);
              innerFrom_1.innerFrom(durationSelector(value)).subscribe(durationSubscriber);
            }, function() {
              emit();
              subscriber.complete();
            }, void 0, function() {
              lastValue = durationSubscriber = null;
            }));
          });
        }
        exports22.debounce = debounce;
      }
    });
    var require_debounceTime = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/debounceTime.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.debounceTime = void 0;
        var async_1 = require_async2();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function debounceTime(dueTime, scheduler) {
          if (scheduler === void 0) {
            scheduler = async_1.asyncScheduler;
          }
          return lift_1.operate(function(source, subscriber) {
            var activeTask = null;
            var lastValue = null;
            var lastTime = null;
            var emit = function() {
              if (activeTask) {
                activeTask.unsubscribe();
                activeTask = null;
                var value = lastValue;
                lastValue = null;
                subscriber.next(value);
              }
            };
            function emitWhenIdle() {
              var targetTime = lastTime + dueTime;
              var now = scheduler.now();
              if (now < targetTime) {
                activeTask = this.schedule(void 0, targetTime - now);
                subscriber.add(activeTask);
                return;
              }
              emit();
            }
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              lastValue = value;
              lastTime = scheduler.now();
              if (!activeTask) {
                activeTask = scheduler.schedule(emitWhenIdle, dueTime);
                subscriber.add(activeTask);
              }
            }, function() {
              emit();
              subscriber.complete();
            }, void 0, function() {
              lastValue = activeTask = null;
            }));
          });
        }
        exports22.debounceTime = debounceTime;
      }
    });
    var require_defaultIfEmpty = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/defaultIfEmpty.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.defaultIfEmpty = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function defaultIfEmpty(defaultValue) {
          return lift_1.operate(function(source, subscriber) {
            var hasValue = false;
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              hasValue = true;
              subscriber.next(value);
            }, function() {
              if (!hasValue) {
                subscriber.next(defaultValue);
              }
              subscriber.complete();
            }));
          });
        }
        exports22.defaultIfEmpty = defaultIfEmpty;
      }
    });
    var require_take = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/take.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.take = void 0;
        var empty_1 = require_empty();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function take(count) {
          return count <= 0 ? function() {
            return empty_1.EMPTY;
          } : lift_1.operate(function(source, subscriber) {
            var seen = 0;
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              if (++seen <= count) {
                subscriber.next(value);
                if (count <= seen) {
                  subscriber.complete();
                }
              }
            }));
          });
        }
        exports22.take = take;
      }
    });
    var require_ignoreElements = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/ignoreElements.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.ignoreElements = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var noop_1 = require_noop();
        function ignoreElements() {
          return lift_1.operate(function(source, subscriber) {
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, noop_1.noop));
          });
        }
        exports22.ignoreElements = ignoreElements;
      }
    });
    var require_mapTo = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/mapTo.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.mapTo = void 0;
        var map_1 = require_map();
        function mapTo(value) {
          return map_1.map(function() {
            return value;
          });
        }
        exports22.mapTo = mapTo;
      }
    });
    var require_delayWhen = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/delayWhen.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.delayWhen = void 0;
        var concat_1 = require_concat();
        var take_1 = require_take();
        var ignoreElements_1 = require_ignoreElements();
        var mapTo_1 = require_mapTo();
        var mergeMap_1 = require_mergeMap();
        var innerFrom_1 = require_innerFrom();
        function delayWhen(delayDurationSelector, subscriptionDelay) {
          if (subscriptionDelay) {
            return function(source) {
              return concat_1.concat(subscriptionDelay.pipe(take_1.take(1), ignoreElements_1.ignoreElements()), source.pipe(delayWhen(delayDurationSelector)));
            };
          }
          return mergeMap_1.mergeMap(function(value, index) {
            return innerFrom_1.innerFrom(delayDurationSelector(value, index)).pipe(take_1.take(1), mapTo_1.mapTo(value));
          });
        }
        exports22.delayWhen = delayWhen;
      }
    });
    var require_delay = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/delay.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.delay = void 0;
        var async_1 = require_async2();
        var delayWhen_1 = require_delayWhen();
        var timer_1 = require_timer();
        function delay(due, scheduler) {
          if (scheduler === void 0) {
            scheduler = async_1.asyncScheduler;
          }
          var duration = timer_1.timer(due, scheduler);
          return delayWhen_1.delayWhen(function() {
            return duration;
          });
        }
        exports22.delay = delay;
      }
    });
    var require_dematerialize = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/dematerialize.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.dematerialize = void 0;
        var Notification_1 = require_Notification();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function dematerialize() {
          return lift_1.operate(function(source, subscriber) {
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(notification) {
              return Notification_1.observeNotification(notification, subscriber);
            }));
          });
        }
        exports22.dematerialize = dematerialize;
      }
    });
    var require_distinct = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/distinct.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.distinct = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var noop_1 = require_noop();
        var innerFrom_1 = require_innerFrom();
        function distinct(keySelector, flushes) {
          return lift_1.operate(function(source, subscriber) {
            var distinctKeys = /* @__PURE__ */ new Set();
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              var key = keySelector ? keySelector(value) : value;
              if (!distinctKeys.has(key)) {
                distinctKeys.add(key);
                subscriber.next(value);
              }
            }));
            flushes && innerFrom_1.innerFrom(flushes).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function() {
              return distinctKeys.clear();
            }, noop_1.noop));
          });
        }
        exports22.distinct = distinct;
      }
    });
    var require_distinctUntilChanged = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/distinctUntilChanged.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.distinctUntilChanged = void 0;
        var identity_1 = require_identity();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function distinctUntilChanged(comparator, keySelector) {
          if (keySelector === void 0) {
            keySelector = identity_1.identity;
          }
          comparator = comparator !== null && comparator !== void 0 ? comparator : defaultCompare;
          return lift_1.operate(function(source, subscriber) {
            var previousKey;
            var first = true;
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              var currentKey = keySelector(value);
              if (first || !comparator(previousKey, currentKey)) {
                first = false;
                previousKey = currentKey;
                subscriber.next(value);
              }
            }));
          });
        }
        exports22.distinctUntilChanged = distinctUntilChanged;
        function defaultCompare(a, b) {
          return a === b;
        }
      }
    });
    var require_distinctUntilKeyChanged = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/distinctUntilKeyChanged.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.distinctUntilKeyChanged = void 0;
        var distinctUntilChanged_1 = require_distinctUntilChanged();
        function distinctUntilKeyChanged(key, compare) {
          return distinctUntilChanged_1.distinctUntilChanged(function(x, y) {
            return compare ? compare(x[key], y[key]) : x[key] === y[key];
          });
        }
        exports22.distinctUntilKeyChanged = distinctUntilKeyChanged;
      }
    });
    var require_throwIfEmpty = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/throwIfEmpty.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.throwIfEmpty = void 0;
        var EmptyError_1 = require_EmptyError();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function throwIfEmpty(errorFactory) {
          if (errorFactory === void 0) {
            errorFactory = defaultErrorFactory;
          }
          return lift_1.operate(function(source, subscriber) {
            var hasValue = false;
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              hasValue = true;
              subscriber.next(value);
            }, function() {
              return hasValue ? subscriber.complete() : subscriber.error(errorFactory());
            }));
          });
        }
        exports22.throwIfEmpty = throwIfEmpty;
        function defaultErrorFactory() {
          return new EmptyError_1.EmptyError();
        }
      }
    });
    var require_elementAt = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/elementAt.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.elementAt = void 0;
        var ArgumentOutOfRangeError_1 = require_ArgumentOutOfRangeError();
        var filter_1 = require_filter();
        var throwIfEmpty_1 = require_throwIfEmpty();
        var defaultIfEmpty_1 = require_defaultIfEmpty();
        var take_1 = require_take();
        function elementAt(index, defaultValue) {
          if (index < 0) {
            throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError();
          }
          var hasDefaultValue = arguments.length >= 2;
          return function(source) {
            return source.pipe(filter_1.filter(function(v, i) {
              return i === index;
            }), take_1.take(1), hasDefaultValue ? defaultIfEmpty_1.defaultIfEmpty(defaultValue) : throwIfEmpty_1.throwIfEmpty(function() {
              return new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError();
            }));
          };
        }
        exports22.elementAt = elementAt;
      }
    });
    var require_endWith = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/endWith.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.endWith = void 0;
        var concat_1 = require_concat();
        var of_1 = require_of();
        function endWith() {
          var values = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            values[_i] = arguments[_i];
          }
          return function(source) {
            return concat_1.concat(source, of_1.of.apply(void 0, __spreadArray2([], __read2(values))));
          };
        }
        exports22.endWith = endWith;
      }
    });
    var require_every = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/every.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.every = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function every(predicate, thisArg) {
          return lift_1.operate(function(source, subscriber) {
            var index = 0;
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              if (!predicate.call(thisArg, value, index++, source)) {
                subscriber.next(false);
                subscriber.complete();
              }
            }, function() {
              subscriber.next(true);
              subscriber.complete();
            }));
          });
        }
        exports22.every = every;
      }
    });
    var require_exhaustMap = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/exhaustMap.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.exhaustMap = void 0;
        var map_1 = require_map();
        var innerFrom_1 = require_innerFrom();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function exhaustMap(project, resultSelector) {
          if (resultSelector) {
            return function(source) {
              return source.pipe(exhaustMap(function(a, i) {
                return innerFrom_1.innerFrom(project(a, i)).pipe(map_1.map(function(b, ii) {
                  return resultSelector(a, b, i, ii);
                }));
              }));
            };
          }
          return lift_1.operate(function(source, subscriber) {
            var index = 0;
            var innerSub = null;
            var isComplete = false;
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(outerValue) {
              if (!innerSub) {
                innerSub = OperatorSubscriber_1.createOperatorSubscriber(subscriber, void 0, function() {
                  innerSub = null;
                  isComplete && subscriber.complete();
                });
                innerFrom_1.innerFrom(project(outerValue, index++)).subscribe(innerSub);
              }
            }, function() {
              isComplete = true;
              !innerSub && subscriber.complete();
            }));
          });
        }
        exports22.exhaustMap = exhaustMap;
      }
    });
    var require_exhaustAll = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/exhaustAll.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.exhaustAll = void 0;
        var exhaustMap_1 = require_exhaustMap();
        var identity_1 = require_identity();
        function exhaustAll() {
          return exhaustMap_1.exhaustMap(identity_1.identity);
        }
        exports22.exhaustAll = exhaustAll;
      }
    });
    var require_exhaust = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/exhaust.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.exhaust = void 0;
        var exhaustAll_1 = require_exhaustAll();
        exports22.exhaust = exhaustAll_1.exhaustAll;
      }
    });
    var require_expand = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/expand.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.expand = void 0;
        var lift_1 = require_lift();
        var mergeInternals_1 = require_mergeInternals();
        function expand(project, concurrent, scheduler) {
          if (concurrent === void 0) {
            concurrent = Infinity;
          }
          concurrent = (concurrent || 0) < 1 ? Infinity : concurrent;
          return lift_1.operate(function(source, subscriber) {
            return mergeInternals_1.mergeInternals(source, subscriber, project, concurrent, void 0, true, scheduler);
          });
        }
        exports22.expand = expand;
      }
    });
    var require_finalize = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/finalize.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.finalize = void 0;
        var lift_1 = require_lift();
        function finalize(callback) {
          return lift_1.operate(function(source, subscriber) {
            try {
              source.subscribe(subscriber);
            } finally {
              subscriber.add(callback);
            }
          });
        }
        exports22.finalize = finalize;
      }
    });
    var require_find = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/find.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.createFind = exports22.find = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function find(predicate, thisArg) {
          return lift_1.operate(createFind(predicate, thisArg, "value"));
        }
        exports22.find = find;
        function createFind(predicate, thisArg, emit) {
          var findIndex = emit === "index";
          return function(source, subscriber) {
            var index = 0;
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              var i = index++;
              if (predicate.call(thisArg, value, i, source)) {
                subscriber.next(findIndex ? i : value);
                subscriber.complete();
              }
            }, function() {
              subscriber.next(findIndex ? -1 : void 0);
              subscriber.complete();
            }));
          };
        }
        exports22.createFind = createFind;
      }
    });
    var require_findIndex = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/findIndex.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.findIndex = void 0;
        var lift_1 = require_lift();
        var find_1 = require_find();
        function findIndex(predicate, thisArg) {
          return lift_1.operate(find_1.createFind(predicate, thisArg, "index"));
        }
        exports22.findIndex = findIndex;
      }
    });
    var require_first = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/first.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.first = void 0;
        var EmptyError_1 = require_EmptyError();
        var filter_1 = require_filter();
        var take_1 = require_take();
        var defaultIfEmpty_1 = require_defaultIfEmpty();
        var throwIfEmpty_1 = require_throwIfEmpty();
        var identity_1 = require_identity();
        function first(predicate, defaultValue) {
          var hasDefaultValue = arguments.length >= 2;
          return function(source) {
            return source.pipe(predicate ? filter_1.filter(function(v, i) {
              return predicate(v, i, source);
            }) : identity_1.identity, take_1.take(1), hasDefaultValue ? defaultIfEmpty_1.defaultIfEmpty(defaultValue) : throwIfEmpty_1.throwIfEmpty(function() {
              return new EmptyError_1.EmptyError();
            }));
          };
        }
        exports22.first = first;
      }
    });
    var require_groupBy = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/groupBy.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.groupBy = void 0;
        var Observable_1 = require_Observable();
        var innerFrom_1 = require_innerFrom();
        var Subject_1 = require_Subject();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function groupBy(keySelector, elementOrOptions, duration, connector) {
          return lift_1.operate(function(source, subscriber) {
            var element;
            if (!elementOrOptions || typeof elementOrOptions === "function") {
              element = elementOrOptions;
            } else {
              duration = elementOrOptions.duration, element = elementOrOptions.element, connector = elementOrOptions.connector;
            }
            var groups = /* @__PURE__ */ new Map();
            var notify = function(cb) {
              groups.forEach(cb);
              cb(subscriber);
            };
            var handleError = function(err) {
              return notify(function(consumer) {
                return consumer.error(err);
              });
            };
            var activeGroups = 0;
            var teardownAttempted = false;
            var groupBySourceSubscriber = new OperatorSubscriber_1.OperatorSubscriber(subscriber, function(value) {
              try {
                var key_1 = keySelector(value);
                var group_1 = groups.get(key_1);
                if (!group_1) {
                  groups.set(key_1, group_1 = connector ? connector() : new Subject_1.Subject());
                  var grouped = createGroupedObservable(key_1, group_1);
                  subscriber.next(grouped);
                  if (duration) {
                    var durationSubscriber_1 = OperatorSubscriber_1.createOperatorSubscriber(group_1, function() {
                      group_1.complete();
                      durationSubscriber_1 === null || durationSubscriber_1 === void 0 ? void 0 : durationSubscriber_1.unsubscribe();
                    }, void 0, void 0, function() {
                      return groups.delete(key_1);
                    });
                    groupBySourceSubscriber.add(innerFrom_1.innerFrom(duration(grouped)).subscribe(durationSubscriber_1));
                  }
                }
                group_1.next(element ? element(value) : value);
              } catch (err) {
                handleError(err);
              }
            }, function() {
              return notify(function(consumer) {
                return consumer.complete();
              });
            }, handleError, function() {
              return groups.clear();
            }, function() {
              teardownAttempted = true;
              return activeGroups === 0;
            });
            source.subscribe(groupBySourceSubscriber);
            function createGroupedObservable(key, groupSubject) {
              var result = new Observable_1.Observable(function(groupSubscriber) {
                activeGroups++;
                var innerSub = groupSubject.subscribe(groupSubscriber);
                return function() {
                  innerSub.unsubscribe();
                  --activeGroups === 0 && teardownAttempted && groupBySourceSubscriber.unsubscribe();
                };
              });
              result.key = key;
              return result;
            }
          });
        }
        exports22.groupBy = groupBy;
      }
    });
    var require_isEmpty = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/isEmpty.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.isEmpty = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function isEmpty() {
          return lift_1.operate(function(source, subscriber) {
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function() {
              subscriber.next(false);
              subscriber.complete();
            }, function() {
              subscriber.next(true);
              subscriber.complete();
            }));
          });
        }
        exports22.isEmpty = isEmpty;
      }
    });
    var require_takeLast = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/takeLast.js"(exports22) {
        "use strict";
        var __values2 = exports22 && exports22.__values || function(o) {
          var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
          if (m) return m.call(o);
          if (o && typeof o.length === "number") return {
            next: function() {
              if (o && i >= o.length) o = void 0;
              return { value: o && o[i++], done: !o };
            }
          };
          throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.takeLast = void 0;
        var empty_1 = require_empty();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function takeLast(count) {
          return count <= 0 ? function() {
            return empty_1.EMPTY;
          } : lift_1.operate(function(source, subscriber) {
            var buffer = [];
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              buffer.push(value);
              count < buffer.length && buffer.shift();
            }, function() {
              var e_1, _a2;
              try {
                for (var buffer_1 = __values2(buffer), buffer_1_1 = buffer_1.next(); !buffer_1_1.done; buffer_1_1 = buffer_1.next()) {
                  var value = buffer_1_1.value;
                  subscriber.next(value);
                }
              } catch (e_1_1) {
                e_1 = { error: e_1_1 };
              } finally {
                try {
                  if (buffer_1_1 && !buffer_1_1.done && (_a2 = buffer_1.return)) _a2.call(buffer_1);
                } finally {
                  if (e_1) throw e_1.error;
                }
              }
              subscriber.complete();
            }, void 0, function() {
              buffer = null;
            }));
          });
        }
        exports22.takeLast = takeLast;
      }
    });
    var require_last = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/last.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.last = void 0;
        var EmptyError_1 = require_EmptyError();
        var filter_1 = require_filter();
        var takeLast_1 = require_takeLast();
        var throwIfEmpty_1 = require_throwIfEmpty();
        var defaultIfEmpty_1 = require_defaultIfEmpty();
        var identity_1 = require_identity();
        function last(predicate, defaultValue) {
          var hasDefaultValue = arguments.length >= 2;
          return function(source) {
            return source.pipe(predicate ? filter_1.filter(function(v, i) {
              return predicate(v, i, source);
            }) : identity_1.identity, takeLast_1.takeLast(1), hasDefaultValue ? defaultIfEmpty_1.defaultIfEmpty(defaultValue) : throwIfEmpty_1.throwIfEmpty(function() {
              return new EmptyError_1.EmptyError();
            }));
          };
        }
        exports22.last = last;
      }
    });
    var require_materialize = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/materialize.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.materialize = void 0;
        var Notification_1 = require_Notification();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function materialize() {
          return lift_1.operate(function(source, subscriber) {
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              subscriber.next(Notification_1.Notification.createNext(value));
            }, function() {
              subscriber.next(Notification_1.Notification.createComplete());
              subscriber.complete();
            }, function(err) {
              subscriber.next(Notification_1.Notification.createError(err));
              subscriber.complete();
            }));
          });
        }
        exports22.materialize = materialize;
      }
    });
    var require_max2 = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/max.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.max = void 0;
        var reduce_1 = require_reduce();
        var isFunction_1 = require_isFunction();
        function max(comparer) {
          return reduce_1.reduce(isFunction_1.isFunction(comparer) ? function(x, y) {
            return comparer(x, y) > 0 ? x : y;
          } : function(x, y) {
            return x > y ? x : y;
          });
        }
        exports22.max = max;
      }
    });
    var require_flatMap = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/flatMap.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.flatMap = void 0;
        var mergeMap_1 = require_mergeMap();
        exports22.flatMap = mergeMap_1.mergeMap;
      }
    });
    var require_mergeMapTo = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/mergeMapTo.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.mergeMapTo = void 0;
        var mergeMap_1 = require_mergeMap();
        var isFunction_1 = require_isFunction();
        function mergeMapTo(innerObservable, resultSelector, concurrent) {
          if (concurrent === void 0) {
            concurrent = Infinity;
          }
          if (isFunction_1.isFunction(resultSelector)) {
            return mergeMap_1.mergeMap(function() {
              return innerObservable;
            }, resultSelector, concurrent);
          }
          if (typeof resultSelector === "number") {
            concurrent = resultSelector;
          }
          return mergeMap_1.mergeMap(function() {
            return innerObservable;
          }, concurrent);
        }
        exports22.mergeMapTo = mergeMapTo;
      }
    });
    var require_mergeScan = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/mergeScan.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.mergeScan = void 0;
        var lift_1 = require_lift();
        var mergeInternals_1 = require_mergeInternals();
        function mergeScan(accumulator, seed, concurrent) {
          if (concurrent === void 0) {
            concurrent = Infinity;
          }
          return lift_1.operate(function(source, subscriber) {
            var state = seed;
            return mergeInternals_1.mergeInternals(source, subscriber, function(value, index) {
              return accumulator(state, value, index);
            }, concurrent, function(value) {
              state = value;
            }, false, void 0, function() {
              return state = null;
            });
          });
        }
        exports22.mergeScan = mergeScan;
      }
    });
    var require_merge2 = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/merge.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.merge = void 0;
        var lift_1 = require_lift();
        var mergeAll_1 = require_mergeAll();
        var args_1 = require_args();
        var from_1 = require_from();
        function merge() {
          var args2 = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args2[_i] = arguments[_i];
          }
          var scheduler = args_1.popScheduler(args2);
          var concurrent = args_1.popNumber(args2, Infinity);
          return lift_1.operate(function(source, subscriber) {
            mergeAll_1.mergeAll(concurrent)(from_1.from(__spreadArray2([source], __read2(args2)), scheduler)).subscribe(subscriber);
          });
        }
        exports22.merge = merge;
      }
    });
    var require_mergeWith = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/mergeWith.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.mergeWith = void 0;
        var merge_1 = require_merge2();
        function mergeWith() {
          var otherSources = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            otherSources[_i] = arguments[_i];
          }
          return merge_1.merge.apply(void 0, __spreadArray2([], __read2(otherSources)));
        }
        exports22.mergeWith = mergeWith;
      }
    });
    var require_min2 = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/min.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.min = void 0;
        var reduce_1 = require_reduce();
        var isFunction_1 = require_isFunction();
        function min(comparer) {
          return reduce_1.reduce(isFunction_1.isFunction(comparer) ? function(x, y) {
            return comparer(x, y) < 0 ? x : y;
          } : function(x, y) {
            return x < y ? x : y;
          });
        }
        exports22.min = min;
      }
    });
    var require_multicast = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/multicast.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.multicast = void 0;
        var ConnectableObservable_1 = require_ConnectableObservable();
        var isFunction_1 = require_isFunction();
        var connect_1 = require_connect();
        function multicast(subjectOrSubjectFactory, selector) {
          var subjectFactory = isFunction_1.isFunction(subjectOrSubjectFactory) ? subjectOrSubjectFactory : function() {
            return subjectOrSubjectFactory;
          };
          if (isFunction_1.isFunction(selector)) {
            return connect_1.connect(selector, {
              connector: subjectFactory
            });
          }
          return function(source) {
            return new ConnectableObservable_1.ConnectableObservable(source, subjectFactory);
          };
        }
        exports22.multicast = multicast;
      }
    });
    var require_onErrorResumeNextWith = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/onErrorResumeNextWith.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.onErrorResumeNext = exports22.onErrorResumeNextWith = void 0;
        var argsOrArgArray_1 = require_argsOrArgArray();
        var onErrorResumeNext_1 = require_onErrorResumeNext();
        function onErrorResumeNextWith() {
          var sources = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            sources[_i] = arguments[_i];
          }
          var nextSources = argsOrArgArray_1.argsOrArgArray(sources);
          return function(source) {
            return onErrorResumeNext_1.onErrorResumeNext.apply(void 0, __spreadArray2([source], __read2(nextSources)));
          };
        }
        exports22.onErrorResumeNextWith = onErrorResumeNextWith;
        exports22.onErrorResumeNext = onErrorResumeNextWith;
      }
    });
    var require_pairwise = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/pairwise.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.pairwise = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function pairwise() {
          return lift_1.operate(function(source, subscriber) {
            var prev;
            var hasPrev = false;
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              var p = prev;
              prev = value;
              hasPrev && subscriber.next([p, value]);
              hasPrev = true;
            }));
          });
        }
        exports22.pairwise = pairwise;
      }
    });
    var require_pluck = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/pluck.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.pluck = void 0;
        var map_1 = require_map();
        function pluck() {
          var properties = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            properties[_i] = arguments[_i];
          }
          var length = properties.length;
          if (length === 0) {
            throw new Error("list of properties cannot be empty.");
          }
          return map_1.map(function(x) {
            var currentProp = x;
            for (var i = 0; i < length; i++) {
              var p = currentProp === null || currentProp === void 0 ? void 0 : currentProp[properties[i]];
              if (typeof p !== "undefined") {
                currentProp = p;
              } else {
                return void 0;
              }
            }
            return currentProp;
          });
        }
        exports22.pluck = pluck;
      }
    });
    var require_publish = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/publish.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.publish = void 0;
        var Subject_1 = require_Subject();
        var multicast_1 = require_multicast();
        var connect_1 = require_connect();
        function publish(selector) {
          return selector ? function(source) {
            return connect_1.connect(selector)(source);
          } : function(source) {
            return multicast_1.multicast(new Subject_1.Subject())(source);
          };
        }
        exports22.publish = publish;
      }
    });
    var require_publishBehavior = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/publishBehavior.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.publishBehavior = void 0;
        var BehaviorSubject_1 = require_BehaviorSubject();
        var ConnectableObservable_1 = require_ConnectableObservable();
        function publishBehavior(initialValue) {
          return function(source) {
            var subject = new BehaviorSubject_1.BehaviorSubject(initialValue);
            return new ConnectableObservable_1.ConnectableObservable(source, function() {
              return subject;
            });
          };
        }
        exports22.publishBehavior = publishBehavior;
      }
    });
    var require_publishLast = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/publishLast.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.publishLast = void 0;
        var AsyncSubject_1 = require_AsyncSubject();
        var ConnectableObservable_1 = require_ConnectableObservable();
        function publishLast() {
          return function(source) {
            var subject = new AsyncSubject_1.AsyncSubject();
            return new ConnectableObservable_1.ConnectableObservable(source, function() {
              return subject;
            });
          };
        }
        exports22.publishLast = publishLast;
      }
    });
    var require_publishReplay = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/publishReplay.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.publishReplay = void 0;
        var ReplaySubject_1 = require_ReplaySubject();
        var multicast_1 = require_multicast();
        var isFunction_1 = require_isFunction();
        function publishReplay(bufferSize, windowTime, selectorOrScheduler, timestampProvider) {
          if (selectorOrScheduler && !isFunction_1.isFunction(selectorOrScheduler)) {
            timestampProvider = selectorOrScheduler;
          }
          var selector = isFunction_1.isFunction(selectorOrScheduler) ? selectorOrScheduler : void 0;
          return function(source) {
            return multicast_1.multicast(new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, timestampProvider), selector)(source);
          };
        }
        exports22.publishReplay = publishReplay;
      }
    });
    var require_raceWith = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/raceWith.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.raceWith = void 0;
        var race_1 = require_race();
        var lift_1 = require_lift();
        var identity_1 = require_identity();
        function raceWith() {
          var otherSources = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            otherSources[_i] = arguments[_i];
          }
          return !otherSources.length ? identity_1.identity : lift_1.operate(function(source, subscriber) {
            race_1.raceInit(__spreadArray2([source], __read2(otherSources)))(subscriber);
          });
        }
        exports22.raceWith = raceWith;
      }
    });
    var require_repeat = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/repeat.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.repeat = void 0;
        var empty_1 = require_empty();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var innerFrom_1 = require_innerFrom();
        var timer_1 = require_timer();
        function repeat(countOrConfig) {
          var _a2;
          var count = Infinity;
          var delay;
          if (countOrConfig != null) {
            if (typeof countOrConfig === "object") {
              _a2 = countOrConfig.count, count = _a2 === void 0 ? Infinity : _a2, delay = countOrConfig.delay;
            } else {
              count = countOrConfig;
            }
          }
          return count <= 0 ? function() {
            return empty_1.EMPTY;
          } : lift_1.operate(function(source, subscriber) {
            var soFar = 0;
            var sourceSub;
            var resubscribe = function() {
              sourceSub === null || sourceSub === void 0 ? void 0 : sourceSub.unsubscribe();
              sourceSub = null;
              if (delay != null) {
                var notifier = typeof delay === "number" ? timer_1.timer(delay) : innerFrom_1.innerFrom(delay(soFar));
                var notifierSubscriber_1 = OperatorSubscriber_1.createOperatorSubscriber(subscriber, function() {
                  notifierSubscriber_1.unsubscribe();
                  subscribeToSource();
                });
                notifier.subscribe(notifierSubscriber_1);
              } else {
                subscribeToSource();
              }
            };
            var subscribeToSource = function() {
              var syncUnsub = false;
              sourceSub = source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, void 0, function() {
                if (++soFar < count) {
                  if (sourceSub) {
                    resubscribe();
                  } else {
                    syncUnsub = true;
                  }
                } else {
                  subscriber.complete();
                }
              }));
              if (syncUnsub) {
                resubscribe();
              }
            };
            subscribeToSource();
          });
        }
        exports22.repeat = repeat;
      }
    });
    var require_repeatWhen = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/repeatWhen.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.repeatWhen = void 0;
        var innerFrom_1 = require_innerFrom();
        var Subject_1 = require_Subject();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function repeatWhen(notifier) {
          return lift_1.operate(function(source, subscriber) {
            var innerSub;
            var syncResub = false;
            var completions$;
            var isNotifierComplete = false;
            var isMainComplete = false;
            var checkComplete = function() {
              return isMainComplete && isNotifierComplete && (subscriber.complete(), true);
            };
            var getCompletionSubject = function() {
              if (!completions$) {
                completions$ = new Subject_1.Subject();
                innerFrom_1.innerFrom(notifier(completions$)).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function() {
                  if (innerSub) {
                    subscribeForRepeatWhen();
                  } else {
                    syncResub = true;
                  }
                }, function() {
                  isNotifierComplete = true;
                  checkComplete();
                }));
              }
              return completions$;
            };
            var subscribeForRepeatWhen = function() {
              isMainComplete = false;
              innerSub = source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, void 0, function() {
                isMainComplete = true;
                !checkComplete() && getCompletionSubject().next();
              }));
              if (syncResub) {
                innerSub.unsubscribe();
                innerSub = null;
                syncResub = false;
                subscribeForRepeatWhen();
              }
            };
            subscribeForRepeatWhen();
          });
        }
        exports22.repeatWhen = repeatWhen;
      }
    });
    var require_retry = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/retry.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.retry = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var identity_1 = require_identity();
        var timer_1 = require_timer();
        var innerFrom_1 = require_innerFrom();
        function retry(configOrCount) {
          if (configOrCount === void 0) {
            configOrCount = Infinity;
          }
          var config2;
          if (configOrCount && typeof configOrCount === "object") {
            config2 = configOrCount;
          } else {
            config2 = {
              count: configOrCount
            };
          }
          var _a2 = config2.count, count = _a2 === void 0 ? Infinity : _a2, delay = config2.delay, _b2 = config2.resetOnSuccess, resetOnSuccess = _b2 === void 0 ? false : _b2;
          return count <= 0 ? identity_1.identity : lift_1.operate(function(source, subscriber) {
            var soFar = 0;
            var innerSub;
            var subscribeForRetry = function() {
              var syncUnsub = false;
              innerSub = source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
                if (resetOnSuccess) {
                  soFar = 0;
                }
                subscriber.next(value);
              }, void 0, function(err) {
                if (soFar++ < count) {
                  var resub_1 = function() {
                    if (innerSub) {
                      innerSub.unsubscribe();
                      innerSub = null;
                      subscribeForRetry();
                    } else {
                      syncUnsub = true;
                    }
                  };
                  if (delay != null) {
                    var notifier = typeof delay === "number" ? timer_1.timer(delay) : innerFrom_1.innerFrom(delay(err, soFar));
                    var notifierSubscriber_1 = OperatorSubscriber_1.createOperatorSubscriber(subscriber, function() {
                      notifierSubscriber_1.unsubscribe();
                      resub_1();
                    }, function() {
                      subscriber.complete();
                    });
                    notifier.subscribe(notifierSubscriber_1);
                  } else {
                    resub_1();
                  }
                } else {
                  subscriber.error(err);
                }
              }));
              if (syncUnsub) {
                innerSub.unsubscribe();
                innerSub = null;
                subscribeForRetry();
              }
            };
            subscribeForRetry();
          });
        }
        exports22.retry = retry;
      }
    });
    var require_retryWhen = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/retryWhen.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.retryWhen = void 0;
        var innerFrom_1 = require_innerFrom();
        var Subject_1 = require_Subject();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function retryWhen(notifier) {
          return lift_1.operate(function(source, subscriber) {
            var innerSub;
            var syncResub = false;
            var errors$;
            var subscribeForRetryWhen = function() {
              innerSub = source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, void 0, void 0, function(err) {
                if (!errors$) {
                  errors$ = new Subject_1.Subject();
                  innerFrom_1.innerFrom(notifier(errors$)).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function() {
                    return innerSub ? subscribeForRetryWhen() : syncResub = true;
                  }));
                }
                if (errors$) {
                  errors$.next(err);
                }
              }));
              if (syncResub) {
                innerSub.unsubscribe();
                innerSub = null;
                syncResub = false;
                subscribeForRetryWhen();
              }
            };
            subscribeForRetryWhen();
          });
        }
        exports22.retryWhen = retryWhen;
      }
    });
    var require_sample = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/sample.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.sample = void 0;
        var innerFrom_1 = require_innerFrom();
        var lift_1 = require_lift();
        var noop_1 = require_noop();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function sample(notifier) {
          return lift_1.operate(function(source, subscriber) {
            var hasValue = false;
            var lastValue = null;
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              hasValue = true;
              lastValue = value;
            }));
            innerFrom_1.innerFrom(notifier).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function() {
              if (hasValue) {
                hasValue = false;
                var value = lastValue;
                lastValue = null;
                subscriber.next(value);
              }
            }, noop_1.noop));
          });
        }
        exports22.sample = sample;
      }
    });
    var require_sampleTime = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/sampleTime.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.sampleTime = void 0;
        var async_1 = require_async2();
        var sample_1 = require_sample();
        var interval_1 = require_interval();
        function sampleTime(period, scheduler) {
          if (scheduler === void 0) {
            scheduler = async_1.asyncScheduler;
          }
          return sample_1.sample(interval_1.interval(period, scheduler));
        }
        exports22.sampleTime = sampleTime;
      }
    });
    var require_scan = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/scan.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.scan = void 0;
        var lift_1 = require_lift();
        var scanInternals_1 = require_scanInternals();
        function scan(accumulator, seed) {
          return lift_1.operate(scanInternals_1.scanInternals(accumulator, seed, arguments.length >= 2, true));
        }
        exports22.scan = scan;
      }
    });
    var require_sequenceEqual = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/sequenceEqual.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.sequenceEqual = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var innerFrom_1 = require_innerFrom();
        function sequenceEqual(compareTo, comparator) {
          if (comparator === void 0) {
            comparator = function(a, b) {
              return a === b;
            };
          }
          return lift_1.operate(function(source, subscriber) {
            var aState = createState();
            var bState = createState();
            var emit = function(isEqual) {
              subscriber.next(isEqual);
              subscriber.complete();
            };
            var createSubscriber = function(selfState, otherState) {
              var sequenceEqualSubscriber = OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(a) {
                var buffer = otherState.buffer, complete = otherState.complete;
                if (buffer.length === 0) {
                  complete ? emit(false) : selfState.buffer.push(a);
                } else {
                  !comparator(a, buffer.shift()) && emit(false);
                }
              }, function() {
                selfState.complete = true;
                var complete = otherState.complete, buffer = otherState.buffer;
                complete && emit(buffer.length === 0);
                sequenceEqualSubscriber === null || sequenceEqualSubscriber === void 0 ? void 0 : sequenceEqualSubscriber.unsubscribe();
              });
              return sequenceEqualSubscriber;
            };
            source.subscribe(createSubscriber(aState, bState));
            innerFrom_1.innerFrom(compareTo).subscribe(createSubscriber(bState, aState));
          });
        }
        exports22.sequenceEqual = sequenceEqual;
        function createState() {
          return {
            buffer: [],
            complete: false
          };
        }
      }
    });
    var require_share = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/share.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.share = void 0;
        var innerFrom_1 = require_innerFrom();
        var Subject_1 = require_Subject();
        var Subscriber_1 = require_Subscriber();
        var lift_1 = require_lift();
        function share(options) {
          if (options === void 0) {
            options = {};
          }
          var _a2 = options.connector, connector = _a2 === void 0 ? function() {
            return new Subject_1.Subject();
          } : _a2, _b2 = options.resetOnError, resetOnError = _b2 === void 0 ? true : _b2, _c2 = options.resetOnComplete, resetOnComplete = _c2 === void 0 ? true : _c2, _d = options.resetOnRefCountZero, resetOnRefCountZero = _d === void 0 ? true : _d;
          return function(wrapperSource) {
            var connection;
            var resetConnection;
            var subject;
            var refCount = 0;
            var hasCompleted = false;
            var hasErrored = false;
            var cancelReset = function() {
              resetConnection === null || resetConnection === void 0 ? void 0 : resetConnection.unsubscribe();
              resetConnection = void 0;
            };
            var reset = function() {
              cancelReset();
              connection = subject = void 0;
              hasCompleted = hasErrored = false;
            };
            var resetAndUnsubscribe = function() {
              var conn = connection;
              reset();
              conn === null || conn === void 0 ? void 0 : conn.unsubscribe();
            };
            return lift_1.operate(function(source, subscriber) {
              refCount++;
              if (!hasErrored && !hasCompleted) {
                cancelReset();
              }
              var dest = subject = subject !== null && subject !== void 0 ? subject : connector();
              subscriber.add(function() {
                refCount--;
                if (refCount === 0 && !hasErrored && !hasCompleted) {
                  resetConnection = handleReset(resetAndUnsubscribe, resetOnRefCountZero);
                }
              });
              dest.subscribe(subscriber);
              if (!connection && refCount > 0) {
                connection = new Subscriber_1.SafeSubscriber({
                  next: function(value) {
                    return dest.next(value);
                  },
                  error: function(err) {
                    hasErrored = true;
                    cancelReset();
                    resetConnection = handleReset(reset, resetOnError, err);
                    dest.error(err);
                  },
                  complete: function() {
                    hasCompleted = true;
                    cancelReset();
                    resetConnection = handleReset(reset, resetOnComplete);
                    dest.complete();
                  }
                });
                innerFrom_1.innerFrom(source).subscribe(connection);
              }
            })(wrapperSource);
          };
        }
        exports22.share = share;
        function handleReset(reset, on) {
          var args2 = [];
          for (var _i = 2; _i < arguments.length; _i++) {
            args2[_i - 2] = arguments[_i];
          }
          if (on === true) {
            reset();
            return;
          }
          if (on === false) {
            return;
          }
          var onSubscriber = new Subscriber_1.SafeSubscriber({
            next: function() {
              onSubscriber.unsubscribe();
              reset();
            }
          });
          return innerFrom_1.innerFrom(on.apply(void 0, __spreadArray2([], __read2(args2)))).subscribe(onSubscriber);
        }
      }
    });
    var require_shareReplay = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/shareReplay.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.shareReplay = void 0;
        var ReplaySubject_1 = require_ReplaySubject();
        var share_1 = require_share();
        function shareReplay(configOrBufferSize, windowTime, scheduler) {
          var _a2, _b2, _c2;
          var bufferSize;
          var refCount = false;
          if (configOrBufferSize && typeof configOrBufferSize === "object") {
            _a2 = configOrBufferSize.bufferSize, bufferSize = _a2 === void 0 ? Infinity : _a2, _b2 = configOrBufferSize.windowTime, windowTime = _b2 === void 0 ? Infinity : _b2, _c2 = configOrBufferSize.refCount, refCount = _c2 === void 0 ? false : _c2, scheduler = configOrBufferSize.scheduler;
          } else {
            bufferSize = configOrBufferSize !== null && configOrBufferSize !== void 0 ? configOrBufferSize : Infinity;
          }
          return share_1.share({
            connector: function() {
              return new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler);
            },
            resetOnError: true,
            resetOnComplete: false,
            resetOnRefCountZero: refCount
          });
        }
        exports22.shareReplay = shareReplay;
      }
    });
    var require_single = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/single.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.single = void 0;
        var EmptyError_1 = require_EmptyError();
        var SequenceError_1 = require_SequenceError();
        var NotFoundError_1 = require_NotFoundError();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function single(predicate) {
          return lift_1.operate(function(source, subscriber) {
            var hasValue = false;
            var singleValue;
            var seenValue = false;
            var index = 0;
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              seenValue = true;
              if (!predicate || predicate(value, index++, source)) {
                hasValue && subscriber.error(new SequenceError_1.SequenceError("Too many matching values"));
                hasValue = true;
                singleValue = value;
              }
            }, function() {
              if (hasValue) {
                subscriber.next(singleValue);
                subscriber.complete();
              } else {
                subscriber.error(seenValue ? new NotFoundError_1.NotFoundError("No matching values") : new EmptyError_1.EmptyError());
              }
            }));
          });
        }
        exports22.single = single;
      }
    });
    var require_skip = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/skip.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.skip = void 0;
        var filter_1 = require_filter();
        function skip(count) {
          return filter_1.filter(function(_, index) {
            return count <= index;
          });
        }
        exports22.skip = skip;
      }
    });
    var require_skipLast = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/skipLast.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.skipLast = void 0;
        var identity_1 = require_identity();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function skipLast(skipCount) {
          return skipCount <= 0 ? identity_1.identity : lift_1.operate(function(source, subscriber) {
            var ring = new Array(skipCount);
            var seen = 0;
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              var valueIndex = seen++;
              if (valueIndex < skipCount) {
                ring[valueIndex] = value;
              } else {
                var index = valueIndex % skipCount;
                var oldValue = ring[index];
                ring[index] = value;
                subscriber.next(oldValue);
              }
            }));
            return function() {
              ring = null;
            };
          });
        }
        exports22.skipLast = skipLast;
      }
    });
    var require_skipUntil = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/skipUntil.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.skipUntil = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var innerFrom_1 = require_innerFrom();
        var noop_1 = require_noop();
        function skipUntil(notifier) {
          return lift_1.operate(function(source, subscriber) {
            var taking = false;
            var skipSubscriber = OperatorSubscriber_1.createOperatorSubscriber(subscriber, function() {
              skipSubscriber === null || skipSubscriber === void 0 ? void 0 : skipSubscriber.unsubscribe();
              taking = true;
            }, noop_1.noop);
            innerFrom_1.innerFrom(notifier).subscribe(skipSubscriber);
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              return taking && subscriber.next(value);
            }));
          });
        }
        exports22.skipUntil = skipUntil;
      }
    });
    var require_skipWhile = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/skipWhile.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.skipWhile = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function skipWhile(predicate) {
          return lift_1.operate(function(source, subscriber) {
            var taking = false;
            var index = 0;
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              return (taking || (taking = !predicate(value, index++))) && subscriber.next(value);
            }));
          });
        }
        exports22.skipWhile = skipWhile;
      }
    });
    var require_startWith = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/startWith.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.startWith = void 0;
        var concat_1 = require_concat();
        var args_1 = require_args();
        var lift_1 = require_lift();
        function startWith() {
          var values = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            values[_i] = arguments[_i];
          }
          var scheduler = args_1.popScheduler(values);
          return lift_1.operate(function(source, subscriber) {
            (scheduler ? concat_1.concat(values, source, scheduler) : concat_1.concat(values, source)).subscribe(subscriber);
          });
        }
        exports22.startWith = startWith;
      }
    });
    var require_switchMap = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/switchMap.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.switchMap = void 0;
        var innerFrom_1 = require_innerFrom();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function switchMap(project, resultSelector) {
          return lift_1.operate(function(source, subscriber) {
            var innerSubscriber = null;
            var index = 0;
            var isComplete = false;
            var checkComplete = function() {
              return isComplete && !innerSubscriber && subscriber.complete();
            };
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              innerSubscriber === null || innerSubscriber === void 0 ? void 0 : innerSubscriber.unsubscribe();
              var innerIndex = 0;
              var outerIndex = index++;
              innerFrom_1.innerFrom(project(value, outerIndex)).subscribe(innerSubscriber = OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(innerValue) {
                return subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue);
              }, function() {
                innerSubscriber = null;
                checkComplete();
              }));
            }, function() {
              isComplete = true;
              checkComplete();
            }));
          });
        }
        exports22.switchMap = switchMap;
      }
    });
    var require_switchAll = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/switchAll.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.switchAll = void 0;
        var switchMap_1 = require_switchMap();
        var identity_1 = require_identity();
        function switchAll() {
          return switchMap_1.switchMap(identity_1.identity);
        }
        exports22.switchAll = switchAll;
      }
    });
    var require_switchMapTo = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/switchMapTo.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.switchMapTo = void 0;
        var switchMap_1 = require_switchMap();
        var isFunction_1 = require_isFunction();
        function switchMapTo(innerObservable, resultSelector) {
          return isFunction_1.isFunction(resultSelector) ? switchMap_1.switchMap(function() {
            return innerObservable;
          }, resultSelector) : switchMap_1.switchMap(function() {
            return innerObservable;
          });
        }
        exports22.switchMapTo = switchMapTo;
      }
    });
    var require_switchScan = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/switchScan.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.switchScan = void 0;
        var switchMap_1 = require_switchMap();
        var lift_1 = require_lift();
        function switchScan(accumulator, seed) {
          return lift_1.operate(function(source, subscriber) {
            var state = seed;
            switchMap_1.switchMap(function(value, index) {
              return accumulator(state, value, index);
            }, function(_, innerValue) {
              return state = innerValue, innerValue;
            })(source).subscribe(subscriber);
            return function() {
              state = null;
            };
          });
        }
        exports22.switchScan = switchScan;
      }
    });
    var require_takeUntil = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/takeUntil.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.takeUntil = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var innerFrom_1 = require_innerFrom();
        var noop_1 = require_noop();
        function takeUntil(notifier) {
          return lift_1.operate(function(source, subscriber) {
            innerFrom_1.innerFrom(notifier).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function() {
              return subscriber.complete();
            }, noop_1.noop));
            !subscriber.closed && source.subscribe(subscriber);
          });
        }
        exports22.takeUntil = takeUntil;
      }
    });
    var require_takeWhile = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/takeWhile.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.takeWhile = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function takeWhile(predicate, inclusive) {
          if (inclusive === void 0) {
            inclusive = false;
          }
          return lift_1.operate(function(source, subscriber) {
            var index = 0;
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              var result = predicate(value, index++);
              (result || inclusive) && subscriber.next(value);
              !result && subscriber.complete();
            }));
          });
        }
        exports22.takeWhile = takeWhile;
      }
    });
    var require_tap = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/tap.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.tap = void 0;
        var isFunction_1 = require_isFunction();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var identity_1 = require_identity();
        function tap(observerOrNext, error, complete) {
          var tapObserver = isFunction_1.isFunction(observerOrNext) || error || complete ? { next: observerOrNext, error, complete } : observerOrNext;
          return tapObserver ? lift_1.operate(function(source, subscriber) {
            var _a2;
            (_a2 = tapObserver.subscribe) === null || _a2 === void 0 ? void 0 : _a2.call(tapObserver);
            var isUnsub = true;
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              var _a22;
              (_a22 = tapObserver.next) === null || _a22 === void 0 ? void 0 : _a22.call(tapObserver, value);
              subscriber.next(value);
            }, function() {
              var _a22;
              isUnsub = false;
              (_a22 = tapObserver.complete) === null || _a22 === void 0 ? void 0 : _a22.call(tapObserver);
              subscriber.complete();
            }, function(err) {
              var _a22;
              isUnsub = false;
              (_a22 = tapObserver.error) === null || _a22 === void 0 ? void 0 : _a22.call(tapObserver, err);
              subscriber.error(err);
            }, function() {
              var _a22, _b2;
              if (isUnsub) {
                (_a22 = tapObserver.unsubscribe) === null || _a22 === void 0 ? void 0 : _a22.call(tapObserver);
              }
              (_b2 = tapObserver.finalize) === null || _b2 === void 0 ? void 0 : _b2.call(tapObserver);
            }));
          }) : identity_1.identity;
        }
        exports22.tap = tap;
      }
    });
    var require_throttle = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/throttle.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.throttle = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var innerFrom_1 = require_innerFrom();
        function throttle(durationSelector, config2) {
          return lift_1.operate(function(source, subscriber) {
            var _a2 = config2 !== null && config2 !== void 0 ? config2 : {}, _b2 = _a2.leading, leading = _b2 === void 0 ? true : _b2, _c2 = _a2.trailing, trailing = _c2 === void 0 ? false : _c2;
            var hasValue = false;
            var sendValue = null;
            var throttled = null;
            var isComplete = false;
            var endThrottling = function() {
              throttled === null || throttled === void 0 ? void 0 : throttled.unsubscribe();
              throttled = null;
              if (trailing) {
                send();
                isComplete && subscriber.complete();
              }
            };
            var cleanupThrottling = function() {
              throttled = null;
              isComplete && subscriber.complete();
            };
            var startThrottle = function(value) {
              return throttled = innerFrom_1.innerFrom(durationSelector(value)).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, endThrottling, cleanupThrottling));
            };
            var send = function() {
              if (hasValue) {
                hasValue = false;
                var value = sendValue;
                sendValue = null;
                subscriber.next(value);
                !isComplete && startThrottle(value);
              }
            };
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              hasValue = true;
              sendValue = value;
              !(throttled && !throttled.closed) && (leading ? send() : startThrottle(value));
            }, function() {
              isComplete = true;
              !(trailing && hasValue && throttled && !throttled.closed) && subscriber.complete();
            }));
          });
        }
        exports22.throttle = throttle;
      }
    });
    var require_throttleTime = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/throttleTime.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.throttleTime = void 0;
        var async_1 = require_async2();
        var throttle_1 = require_throttle();
        var timer_1 = require_timer();
        function throttleTime(duration, scheduler, config2) {
          if (scheduler === void 0) {
            scheduler = async_1.asyncScheduler;
          }
          var duration$ = timer_1.timer(duration, scheduler);
          return throttle_1.throttle(function() {
            return duration$;
          }, config2);
        }
        exports22.throttleTime = throttleTime;
      }
    });
    var require_timeInterval = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/timeInterval.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.TimeInterval = exports22.timeInterval = void 0;
        var async_1 = require_async2();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function timeInterval(scheduler) {
          if (scheduler === void 0) {
            scheduler = async_1.asyncScheduler;
          }
          return lift_1.operate(function(source, subscriber) {
            var last = scheduler.now();
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              var now = scheduler.now();
              var interval = now - last;
              last = now;
              subscriber.next(new TimeInterval(value, interval));
            }));
          });
        }
        exports22.timeInterval = timeInterval;
        var TimeInterval = /* @__PURE__ */ (function() {
          function TimeInterval2(value, interval) {
            this.value = value;
            this.interval = interval;
          }
          return TimeInterval2;
        })();
        exports22.TimeInterval = TimeInterval;
      }
    });
    var require_timeoutWith = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/timeoutWith.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.timeoutWith = void 0;
        var async_1 = require_async2();
        var isDate_1 = require_isDate();
        var timeout_1 = require_timeout();
        function timeoutWith(due, withObservable, scheduler) {
          var first;
          var each;
          var _with;
          scheduler = scheduler !== null && scheduler !== void 0 ? scheduler : async_1.async;
          if (isDate_1.isValidDate(due)) {
            first = due;
          } else if (typeof due === "number") {
            each = due;
          }
          if (withObservable) {
            _with = function() {
              return withObservable;
            };
          } else {
            throw new TypeError("No observable provided to switch to");
          }
          if (first == null && each == null) {
            throw new TypeError("No timeout provided.");
          }
          return timeout_1.timeout({
            first,
            each,
            scheduler,
            with: _with
          });
        }
        exports22.timeoutWith = timeoutWith;
      }
    });
    var require_timestamp = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/timestamp.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.timestamp = void 0;
        var dateTimestampProvider_1 = require_dateTimestampProvider();
        var map_1 = require_map();
        function timestamp(timestampProvider) {
          if (timestampProvider === void 0) {
            timestampProvider = dateTimestampProvider_1.dateTimestampProvider;
          }
          return map_1.map(function(value) {
            return { value, timestamp: timestampProvider.now() };
          });
        }
        exports22.timestamp = timestamp;
      }
    });
    var require_window = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/window.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.window = void 0;
        var Subject_1 = require_Subject();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var noop_1 = require_noop();
        var innerFrom_1 = require_innerFrom();
        function window2(windowBoundaries) {
          return lift_1.operate(function(source, subscriber) {
            var windowSubject = new Subject_1.Subject();
            subscriber.next(windowSubject.asObservable());
            var errorHandler = function(err) {
              windowSubject.error(err);
              subscriber.error(err);
            };
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              return windowSubject === null || windowSubject === void 0 ? void 0 : windowSubject.next(value);
            }, function() {
              windowSubject.complete();
              subscriber.complete();
            }, errorHandler));
            innerFrom_1.innerFrom(windowBoundaries).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function() {
              windowSubject.complete();
              subscriber.next(windowSubject = new Subject_1.Subject());
            }, noop_1.noop, errorHandler));
            return function() {
              windowSubject === null || windowSubject === void 0 ? void 0 : windowSubject.unsubscribe();
              windowSubject = null;
            };
          });
        }
        exports22.window = window2;
      }
    });
    var require_windowCount = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/windowCount.js"(exports22) {
        "use strict";
        var __values2 = exports22 && exports22.__values || function(o) {
          var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
          if (m) return m.call(o);
          if (o && typeof o.length === "number") return {
            next: function() {
              if (o && i >= o.length) o = void 0;
              return { value: o && o[i++], done: !o };
            }
          };
          throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.windowCount = void 0;
        var Subject_1 = require_Subject();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        function windowCount(windowSize, startWindowEvery) {
          if (startWindowEvery === void 0) {
            startWindowEvery = 0;
          }
          var startEvery = startWindowEvery > 0 ? startWindowEvery : windowSize;
          return lift_1.operate(function(source, subscriber) {
            var windows = [new Subject_1.Subject()];
            var starts = [];
            var count = 0;
            subscriber.next(windows[0].asObservable());
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              var e_1, _a2;
              try {
                for (var windows_1 = __values2(windows), windows_1_1 = windows_1.next(); !windows_1_1.done; windows_1_1 = windows_1.next()) {
                  var window_1 = windows_1_1.value;
                  window_1.next(value);
                }
              } catch (e_1_1) {
                e_1 = { error: e_1_1 };
              } finally {
                try {
                  if (windows_1_1 && !windows_1_1.done && (_a2 = windows_1.return)) _a2.call(windows_1);
                } finally {
                  if (e_1) throw e_1.error;
                }
              }
              var c = count - windowSize + 1;
              if (c >= 0 && c % startEvery === 0) {
                windows.shift().complete();
              }
              if (++count % startEvery === 0) {
                var window_2 = new Subject_1.Subject();
                windows.push(window_2);
                subscriber.next(window_2.asObservable());
              }
            }, function() {
              while (windows.length > 0) {
                windows.shift().complete();
              }
              subscriber.complete();
            }, function(err) {
              while (windows.length > 0) {
                windows.shift().error(err);
              }
              subscriber.error(err);
            }, function() {
              starts = null;
              windows = null;
            }));
          });
        }
        exports22.windowCount = windowCount;
      }
    });
    var require_windowTime = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/windowTime.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.windowTime = void 0;
        var Subject_1 = require_Subject();
        var async_1 = require_async2();
        var Subscription_1 = require_Subscription();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var arrRemove_1 = require_arrRemove();
        var args_1 = require_args();
        var executeSchedule_1 = require_executeSchedule();
        function windowTime(windowTimeSpan) {
          var _a2, _b2;
          var otherArgs = [];
          for (var _i = 1; _i < arguments.length; _i++) {
            otherArgs[_i - 1] = arguments[_i];
          }
          var scheduler = (_a2 = args_1.popScheduler(otherArgs)) !== null && _a2 !== void 0 ? _a2 : async_1.asyncScheduler;
          var windowCreationInterval = (_b2 = otherArgs[0]) !== null && _b2 !== void 0 ? _b2 : null;
          var maxWindowSize = otherArgs[1] || Infinity;
          return lift_1.operate(function(source, subscriber) {
            var windowRecords = [];
            var restartOnClose = false;
            var closeWindow = function(record) {
              var window2 = record.window, subs = record.subs;
              window2.complete();
              subs.unsubscribe();
              arrRemove_1.arrRemove(windowRecords, record);
              restartOnClose && startWindow();
            };
            var startWindow = function() {
              if (windowRecords) {
                var subs = new Subscription_1.Subscription();
                subscriber.add(subs);
                var window_1 = new Subject_1.Subject();
                var record_1 = {
                  window: window_1,
                  subs,
                  seen: 0
                };
                windowRecords.push(record_1);
                subscriber.next(window_1.asObservable());
                executeSchedule_1.executeSchedule(subs, scheduler, function() {
                  return closeWindow(record_1);
                }, windowTimeSpan);
              }
            };
            if (windowCreationInterval !== null && windowCreationInterval >= 0) {
              executeSchedule_1.executeSchedule(subscriber, scheduler, startWindow, windowCreationInterval, true);
            } else {
              restartOnClose = true;
            }
            startWindow();
            var loop = function(cb) {
              return windowRecords.slice().forEach(cb);
            };
            var terminate = function(cb) {
              loop(function(_a22) {
                var window2 = _a22.window;
                return cb(window2);
              });
              cb(subscriber);
              subscriber.unsubscribe();
            };
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              loop(function(record) {
                record.window.next(value);
                maxWindowSize <= ++record.seen && closeWindow(record);
              });
            }, function() {
              return terminate(function(consumer) {
                return consumer.complete();
              });
            }, function(err) {
              return terminate(function(consumer) {
                return consumer.error(err);
              });
            }));
            return function() {
              windowRecords = null;
            };
          });
        }
        exports22.windowTime = windowTime;
      }
    });
    var require_windowToggle = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/windowToggle.js"(exports22) {
        "use strict";
        var __values2 = exports22 && exports22.__values || function(o) {
          var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
          if (m) return m.call(o);
          if (o && typeof o.length === "number") return {
            next: function() {
              if (o && i >= o.length) o = void 0;
              return { value: o && o[i++], done: !o };
            }
          };
          throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.windowToggle = void 0;
        var Subject_1 = require_Subject();
        var Subscription_1 = require_Subscription();
        var lift_1 = require_lift();
        var innerFrom_1 = require_innerFrom();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var noop_1 = require_noop();
        var arrRemove_1 = require_arrRemove();
        function windowToggle(openings, closingSelector) {
          return lift_1.operate(function(source, subscriber) {
            var windows = [];
            var handleError = function(err) {
              while (0 < windows.length) {
                windows.shift().error(err);
              }
              subscriber.error(err);
            };
            innerFrom_1.innerFrom(openings).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(openValue) {
              var window2 = new Subject_1.Subject();
              windows.push(window2);
              var closingSubscription = new Subscription_1.Subscription();
              var closeWindow = function() {
                arrRemove_1.arrRemove(windows, window2);
                window2.complete();
                closingSubscription.unsubscribe();
              };
              var closingNotifier;
              try {
                closingNotifier = innerFrom_1.innerFrom(closingSelector(openValue));
              } catch (err) {
                handleError(err);
                return;
              }
              subscriber.next(window2.asObservable());
              closingSubscription.add(closingNotifier.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, closeWindow, noop_1.noop, handleError)));
            }, noop_1.noop));
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              var e_1, _a2;
              var windowsCopy = windows.slice();
              try {
                for (var windowsCopy_1 = __values2(windowsCopy), windowsCopy_1_1 = windowsCopy_1.next(); !windowsCopy_1_1.done; windowsCopy_1_1 = windowsCopy_1.next()) {
                  var window_1 = windowsCopy_1_1.value;
                  window_1.next(value);
                }
              } catch (e_1_1) {
                e_1 = { error: e_1_1 };
              } finally {
                try {
                  if (windowsCopy_1_1 && !windowsCopy_1_1.done && (_a2 = windowsCopy_1.return)) _a2.call(windowsCopy_1);
                } finally {
                  if (e_1) throw e_1.error;
                }
              }
            }, function() {
              while (0 < windows.length) {
                windows.shift().complete();
              }
              subscriber.complete();
            }, handleError, function() {
              while (0 < windows.length) {
                windows.shift().unsubscribe();
              }
            }));
          });
        }
        exports22.windowToggle = windowToggle;
      }
    });
    var require_windowWhen = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/windowWhen.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.windowWhen = void 0;
        var Subject_1 = require_Subject();
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var innerFrom_1 = require_innerFrom();
        function windowWhen(closingSelector) {
          return lift_1.operate(function(source, subscriber) {
            var window2;
            var closingSubscriber;
            var handleError = function(err) {
              window2.error(err);
              subscriber.error(err);
            };
            var openWindow = function() {
              closingSubscriber === null || closingSubscriber === void 0 ? void 0 : closingSubscriber.unsubscribe();
              window2 === null || window2 === void 0 ? void 0 : window2.complete();
              window2 = new Subject_1.Subject();
              subscriber.next(window2.asObservable());
              var closingNotifier;
              try {
                closingNotifier = innerFrom_1.innerFrom(closingSelector());
              } catch (err) {
                handleError(err);
                return;
              }
              closingNotifier.subscribe(closingSubscriber = OperatorSubscriber_1.createOperatorSubscriber(subscriber, openWindow, openWindow, handleError));
            };
            openWindow();
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              return window2.next(value);
            }, function() {
              window2.complete();
              subscriber.complete();
            }, handleError, function() {
              closingSubscriber === null || closingSubscriber === void 0 ? void 0 : closingSubscriber.unsubscribe();
              window2 = null;
            }));
          });
        }
        exports22.windowWhen = windowWhen;
      }
    });
    var require_withLatestFrom = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/withLatestFrom.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.withLatestFrom = void 0;
        var lift_1 = require_lift();
        var OperatorSubscriber_1 = require_OperatorSubscriber();
        var innerFrom_1 = require_innerFrom();
        var identity_1 = require_identity();
        var noop_1 = require_noop();
        var args_1 = require_args();
        function withLatestFrom() {
          var inputs = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            inputs[_i] = arguments[_i];
          }
          var project = args_1.popResultSelector(inputs);
          return lift_1.operate(function(source, subscriber) {
            var len = inputs.length;
            var otherValues = new Array(len);
            var hasValue = inputs.map(function() {
              return false;
            });
            var ready = false;
            var _loop_1 = function(i2) {
              innerFrom_1.innerFrom(inputs[i2]).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
                otherValues[i2] = value;
                if (!ready && !hasValue[i2]) {
                  hasValue[i2] = true;
                  (ready = hasValue.every(identity_1.identity)) && (hasValue = null);
                }
              }, noop_1.noop));
            };
            for (var i = 0; i < len; i++) {
              _loop_1(i);
            }
            source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function(value) {
              if (ready) {
                var values = __spreadArray2([value], __read2(otherValues));
                subscriber.next(project ? project.apply(void 0, __spreadArray2([], __read2(values))) : values);
              }
            }));
          });
        }
        exports22.withLatestFrom = withLatestFrom;
      }
    });
    var require_zipAll = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/zipAll.js"(exports22) {
        "use strict";
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.zipAll = void 0;
        var zip_1 = require_zip();
        var joinAllInternals_1 = require_joinAllInternals();
        function zipAll(project) {
          return joinAllInternals_1.joinAllInternals(zip_1.zip, project);
        }
        exports22.zipAll = zipAll;
      }
    });
    var require_zip2 = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/zip.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.zip = void 0;
        var zip_1 = require_zip();
        var lift_1 = require_lift();
        function zip() {
          var sources = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            sources[_i] = arguments[_i];
          }
          return lift_1.operate(function(source, subscriber) {
            zip_1.zip.apply(void 0, __spreadArray2([source], __read2(sources))).subscribe(subscriber);
          });
        }
        exports22.zip = zip;
      }
    });
    var require_zipWith = __commonJS2({
      "node_modules/rxjs/dist/cjs/internal/operators/zipWith.js"(exports22) {
        "use strict";
        var __read2 = exports22 && exports22.__read || function(o, n) {
          var m = typeof Symbol === "function" && o[Symbol.iterator];
          if (!m) return o;
          var i = m.call(o), r, ar = [], e;
          try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
          } catch (error) {
            e = { error };
          } finally {
            try {
              if (r && !r.done && (m = i["return"])) m.call(i);
            } finally {
              if (e) throw e.error;
            }
          }
          return ar;
        };
        var __spreadArray2 = exports22 && exports22.__spreadArray || function(to, from) {
          for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
            to[j] = from[i];
          return to;
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.zipWith = void 0;
        var zip_1 = require_zip2();
        function zipWith() {
          var otherInputs = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            otherInputs[_i] = arguments[_i];
          }
          return zip_1.zip.apply(void 0, __spreadArray2([], __read2(otherInputs)));
        }
        exports22.zipWith = zipWith;
      }
    });
    var require_cjs2 = __commonJS2({
      "node_modules/rxjs/dist/cjs/index.js"(exports22) {
        "use strict";
        var __createBinding2 = exports22 && exports22.__createBinding || (Object.create ? (function(o, m, k, k2) {
          if (k2 === void 0) k2 = k;
          Object.defineProperty(o, k2, { enumerable: true, get: function() {
            return m[k];
          } });
        }) : (function(o, m, k, k2) {
          if (k2 === void 0) k2 = k;
          o[k2] = m[k];
        }));
        var __exportStar2 = exports22 && exports22.__exportStar || function(m, exports3) {
          for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, p);
        };
        Object.defineProperty(exports22, "__esModule", { value: true });
        exports22.interval = exports22.iif = exports22.generate = exports22.fromEventPattern = exports22.fromEvent = exports22.from = exports22.forkJoin = exports22.empty = exports22.defer = exports22.connectable = exports22.concat = exports22.combineLatest = exports22.bindNodeCallback = exports22.bindCallback = exports22.UnsubscriptionError = exports22.TimeoutError = exports22.SequenceError = exports22.ObjectUnsubscribedError = exports22.NotFoundError = exports22.EmptyError = exports22.ArgumentOutOfRangeError = exports22.firstValueFrom = exports22.lastValueFrom = exports22.isObservable = exports22.identity = exports22.noop = exports22.pipe = exports22.NotificationKind = exports22.Notification = exports22.Subscriber = exports22.Subscription = exports22.Scheduler = exports22.VirtualAction = exports22.VirtualTimeScheduler = exports22.animationFrameScheduler = exports22.animationFrame = exports22.queueScheduler = exports22.queue = exports22.asyncScheduler = exports22.async = exports22.asapScheduler = exports22.asap = exports22.AsyncSubject = exports22.ReplaySubject = exports22.BehaviorSubject = exports22.Subject = exports22.animationFrames = exports22.observable = exports22.ConnectableObservable = exports22.Observable = void 0;
        exports22.filter = exports22.expand = exports22.exhaustMap = exports22.exhaustAll = exports22.exhaust = exports22.every = exports22.endWith = exports22.elementAt = exports22.distinctUntilKeyChanged = exports22.distinctUntilChanged = exports22.distinct = exports22.dematerialize = exports22.delayWhen = exports22.delay = exports22.defaultIfEmpty = exports22.debounceTime = exports22.debounce = exports22.count = exports22.connect = exports22.concatWith = exports22.concatMapTo = exports22.concatMap = exports22.concatAll = exports22.combineLatestWith = exports22.combineLatestAll = exports22.combineAll = exports22.catchError = exports22.bufferWhen = exports22.bufferToggle = exports22.bufferTime = exports22.bufferCount = exports22.buffer = exports22.auditTime = exports22.audit = exports22.config = exports22.NEVER = exports22.EMPTY = exports22.scheduled = exports22.zip = exports22.using = exports22.timer = exports22.throwError = exports22.range = exports22.race = exports22.partition = exports22.pairs = exports22.onErrorResumeNext = exports22.of = exports22.never = exports22.merge = void 0;
        exports22.switchMap = exports22.switchAll = exports22.subscribeOn = exports22.startWith = exports22.skipWhile = exports22.skipUntil = exports22.skipLast = exports22.skip = exports22.single = exports22.shareReplay = exports22.share = exports22.sequenceEqual = exports22.scan = exports22.sampleTime = exports22.sample = exports22.refCount = exports22.retryWhen = exports22.retry = exports22.repeatWhen = exports22.repeat = exports22.reduce = exports22.raceWith = exports22.publishReplay = exports22.publishLast = exports22.publishBehavior = exports22.publish = exports22.pluck = exports22.pairwise = exports22.onErrorResumeNextWith = exports22.observeOn = exports22.multicast = exports22.min = exports22.mergeWith = exports22.mergeScan = exports22.mergeMapTo = exports22.mergeMap = exports22.flatMap = exports22.mergeAll = exports22.max = exports22.materialize = exports22.mapTo = exports22.map = exports22.last = exports22.isEmpty = exports22.ignoreElements = exports22.groupBy = exports22.first = exports22.findIndex = exports22.find = exports22.finalize = void 0;
        exports22.zipWith = exports22.zipAll = exports22.withLatestFrom = exports22.windowWhen = exports22.windowToggle = exports22.windowTime = exports22.windowCount = exports22.window = exports22.toArray = exports22.timestamp = exports22.timeoutWith = exports22.timeout = exports22.timeInterval = exports22.throwIfEmpty = exports22.throttleTime = exports22.throttle = exports22.tap = exports22.takeWhile = exports22.takeUntil = exports22.takeLast = exports22.take = exports22.switchScan = exports22.switchMapTo = void 0;
        var Observable_1 = require_Observable();
        Object.defineProperty(exports22, "Observable", { enumerable: true, get: function() {
          return Observable_1.Observable;
        } });
        var ConnectableObservable_1 = require_ConnectableObservable();
        Object.defineProperty(exports22, "ConnectableObservable", { enumerable: true, get: function() {
          return ConnectableObservable_1.ConnectableObservable;
        } });
        var observable_1 = require_observable();
        Object.defineProperty(exports22, "observable", { enumerable: true, get: function() {
          return observable_1.observable;
        } });
        var animationFrames_1 = require_animationFrames();
        Object.defineProperty(exports22, "animationFrames", { enumerable: true, get: function() {
          return animationFrames_1.animationFrames;
        } });
        var Subject_1 = require_Subject();
        Object.defineProperty(exports22, "Subject", { enumerable: true, get: function() {
          return Subject_1.Subject;
        } });
        var BehaviorSubject_1 = require_BehaviorSubject();
        Object.defineProperty(exports22, "BehaviorSubject", { enumerable: true, get: function() {
          return BehaviorSubject_1.BehaviorSubject;
        } });
        var ReplaySubject_1 = require_ReplaySubject();
        Object.defineProperty(exports22, "ReplaySubject", { enumerable: true, get: function() {
          return ReplaySubject_1.ReplaySubject;
        } });
        var AsyncSubject_1 = require_AsyncSubject();
        Object.defineProperty(exports22, "AsyncSubject", { enumerable: true, get: function() {
          return AsyncSubject_1.AsyncSubject;
        } });
        var asap_1 = require_asap();
        Object.defineProperty(exports22, "asap", { enumerable: true, get: function() {
          return asap_1.asap;
        } });
        Object.defineProperty(exports22, "asapScheduler", { enumerable: true, get: function() {
          return asap_1.asapScheduler;
        } });
        var async_1 = require_async2();
        Object.defineProperty(exports22, "async", { enumerable: true, get: function() {
          return async_1.async;
        } });
        Object.defineProperty(exports22, "asyncScheduler", { enumerable: true, get: function() {
          return async_1.asyncScheduler;
        } });
        var queue_1 = require_queue();
        Object.defineProperty(exports22, "queue", { enumerable: true, get: function() {
          return queue_1.queue;
        } });
        Object.defineProperty(exports22, "queueScheduler", { enumerable: true, get: function() {
          return queue_1.queueScheduler;
        } });
        var animationFrame_1 = require_animationFrame();
        Object.defineProperty(exports22, "animationFrame", { enumerable: true, get: function() {
          return animationFrame_1.animationFrame;
        } });
        Object.defineProperty(exports22, "animationFrameScheduler", { enumerable: true, get: function() {
          return animationFrame_1.animationFrameScheduler;
        } });
        var VirtualTimeScheduler_1 = require_VirtualTimeScheduler();
        Object.defineProperty(exports22, "VirtualTimeScheduler", { enumerable: true, get: function() {
          return VirtualTimeScheduler_1.VirtualTimeScheduler;
        } });
        Object.defineProperty(exports22, "VirtualAction", { enumerable: true, get: function() {
          return VirtualTimeScheduler_1.VirtualAction;
        } });
        var Scheduler_1 = require_Scheduler();
        Object.defineProperty(exports22, "Scheduler", { enumerable: true, get: function() {
          return Scheduler_1.Scheduler;
        } });
        var Subscription_1 = require_Subscription();
        Object.defineProperty(exports22, "Subscription", { enumerable: true, get: function() {
          return Subscription_1.Subscription;
        } });
        var Subscriber_1 = require_Subscriber();
        Object.defineProperty(exports22, "Subscriber", { enumerable: true, get: function() {
          return Subscriber_1.Subscriber;
        } });
        var Notification_1 = require_Notification();
        Object.defineProperty(exports22, "Notification", { enumerable: true, get: function() {
          return Notification_1.Notification;
        } });
        Object.defineProperty(exports22, "NotificationKind", { enumerable: true, get: function() {
          return Notification_1.NotificationKind;
        } });
        var pipe_1 = require_pipe();
        Object.defineProperty(exports22, "pipe", { enumerable: true, get: function() {
          return pipe_1.pipe;
        } });
        var noop_1 = require_noop();
        Object.defineProperty(exports22, "noop", { enumerable: true, get: function() {
          return noop_1.noop;
        } });
        var identity_1 = require_identity();
        Object.defineProperty(exports22, "identity", { enumerable: true, get: function() {
          return identity_1.identity;
        } });
        var isObservable_1 = require_isObservable();
        Object.defineProperty(exports22, "isObservable", { enumerable: true, get: function() {
          return isObservable_1.isObservable;
        } });
        var lastValueFrom_1 = require_lastValueFrom();
        Object.defineProperty(exports22, "lastValueFrom", { enumerable: true, get: function() {
          return lastValueFrom_1.lastValueFrom;
        } });
        var firstValueFrom_1 = require_firstValueFrom();
        Object.defineProperty(exports22, "firstValueFrom", { enumerable: true, get: function() {
          return firstValueFrom_1.firstValueFrom;
        } });
        var ArgumentOutOfRangeError_1 = require_ArgumentOutOfRangeError();
        Object.defineProperty(exports22, "ArgumentOutOfRangeError", { enumerable: true, get: function() {
          return ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
        } });
        var EmptyError_1 = require_EmptyError();
        Object.defineProperty(exports22, "EmptyError", { enumerable: true, get: function() {
          return EmptyError_1.EmptyError;
        } });
        var NotFoundError_1 = require_NotFoundError();
        Object.defineProperty(exports22, "NotFoundError", { enumerable: true, get: function() {
          return NotFoundError_1.NotFoundError;
        } });
        var ObjectUnsubscribedError_1 = require_ObjectUnsubscribedError();
        Object.defineProperty(exports22, "ObjectUnsubscribedError", { enumerable: true, get: function() {
          return ObjectUnsubscribedError_1.ObjectUnsubscribedError;
        } });
        var SequenceError_1 = require_SequenceError();
        Object.defineProperty(exports22, "SequenceError", { enumerable: true, get: function() {
          return SequenceError_1.SequenceError;
        } });
        var timeout_1 = require_timeout();
        Object.defineProperty(exports22, "TimeoutError", { enumerable: true, get: function() {
          return timeout_1.TimeoutError;
        } });
        var UnsubscriptionError_1 = require_UnsubscriptionError();
        Object.defineProperty(exports22, "UnsubscriptionError", { enumerable: true, get: function() {
          return UnsubscriptionError_1.UnsubscriptionError;
        } });
        var bindCallback_1 = require_bindCallback();
        Object.defineProperty(exports22, "bindCallback", { enumerable: true, get: function() {
          return bindCallback_1.bindCallback;
        } });
        var bindNodeCallback_1 = require_bindNodeCallback();
        Object.defineProperty(exports22, "bindNodeCallback", { enumerable: true, get: function() {
          return bindNodeCallback_1.bindNodeCallback;
        } });
        var combineLatest_1 = require_combineLatest();
        Object.defineProperty(exports22, "combineLatest", { enumerable: true, get: function() {
          return combineLatest_1.combineLatest;
        } });
        var concat_1 = require_concat();
        Object.defineProperty(exports22, "concat", { enumerable: true, get: function() {
          return concat_1.concat;
        } });
        var connectable_1 = require_connectable();
        Object.defineProperty(exports22, "connectable", { enumerable: true, get: function() {
          return connectable_1.connectable;
        } });
        var defer_1 = require_defer2();
        Object.defineProperty(exports22, "defer", { enumerable: true, get: function() {
          return defer_1.defer;
        } });
        var empty_1 = require_empty();
        Object.defineProperty(exports22, "empty", { enumerable: true, get: function() {
          return empty_1.empty;
        } });
        var forkJoin_1 = require_forkJoin();
        Object.defineProperty(exports22, "forkJoin", { enumerable: true, get: function() {
          return forkJoin_1.forkJoin;
        } });
        var from_1 = require_from();
        Object.defineProperty(exports22, "from", { enumerable: true, get: function() {
          return from_1.from;
        } });
        var fromEvent_1 = require_fromEvent();
        Object.defineProperty(exports22, "fromEvent", { enumerable: true, get: function() {
          return fromEvent_1.fromEvent;
        } });
        var fromEventPattern_1 = require_fromEventPattern();
        Object.defineProperty(exports22, "fromEventPattern", { enumerable: true, get: function() {
          return fromEventPattern_1.fromEventPattern;
        } });
        var generate_1 = require_generate();
        Object.defineProperty(exports22, "generate", { enumerable: true, get: function() {
          return generate_1.generate;
        } });
        var iif_1 = require_iif();
        Object.defineProperty(exports22, "iif", { enumerable: true, get: function() {
          return iif_1.iif;
        } });
        var interval_1 = require_interval();
        Object.defineProperty(exports22, "interval", { enumerable: true, get: function() {
          return interval_1.interval;
        } });
        var merge_1 = require_merge();
        Object.defineProperty(exports22, "merge", { enumerable: true, get: function() {
          return merge_1.merge;
        } });
        var never_1 = require_never();
        Object.defineProperty(exports22, "never", { enumerable: true, get: function() {
          return never_1.never;
        } });
        var of_1 = require_of();
        Object.defineProperty(exports22, "of", { enumerable: true, get: function() {
          return of_1.of;
        } });
        var onErrorResumeNext_1 = require_onErrorResumeNext();
        Object.defineProperty(exports22, "onErrorResumeNext", { enumerable: true, get: function() {
          return onErrorResumeNext_1.onErrorResumeNext;
        } });
        var pairs_1 = require_pairs();
        Object.defineProperty(exports22, "pairs", { enumerable: true, get: function() {
          return pairs_1.pairs;
        } });
        var partition_1 = require_partition();
        Object.defineProperty(exports22, "partition", { enumerable: true, get: function() {
          return partition_1.partition;
        } });
        var race_1 = require_race();
        Object.defineProperty(exports22, "race", { enumerable: true, get: function() {
          return race_1.race;
        } });
        var range_1 = require_range3();
        Object.defineProperty(exports22, "range", { enumerable: true, get: function() {
          return range_1.range;
        } });
        var throwError_1 = require_throwError();
        Object.defineProperty(exports22, "throwError", { enumerable: true, get: function() {
          return throwError_1.throwError;
        } });
        var timer_1 = require_timer();
        Object.defineProperty(exports22, "timer", { enumerable: true, get: function() {
          return timer_1.timer;
        } });
        var using_1 = require_using();
        Object.defineProperty(exports22, "using", { enumerable: true, get: function() {
          return using_1.using;
        } });
        var zip_1 = require_zip();
        Object.defineProperty(exports22, "zip", { enumerable: true, get: function() {
          return zip_1.zip;
        } });
        var scheduled_1 = require_scheduled();
        Object.defineProperty(exports22, "scheduled", { enumerable: true, get: function() {
          return scheduled_1.scheduled;
        } });
        var empty_2 = require_empty();
        Object.defineProperty(exports22, "EMPTY", { enumerable: true, get: function() {
          return empty_2.EMPTY;
        } });
        var never_2 = require_never();
        Object.defineProperty(exports22, "NEVER", { enumerable: true, get: function() {
          return never_2.NEVER;
        } });
        __exportStar2(require_types4(), exports22);
        var config_1 = require_config();
        Object.defineProperty(exports22, "config", { enumerable: true, get: function() {
          return config_1.config;
        } });
        var audit_1 = require_audit();
        Object.defineProperty(exports22, "audit", { enumerable: true, get: function() {
          return audit_1.audit;
        } });
        var auditTime_1 = require_auditTime();
        Object.defineProperty(exports22, "auditTime", { enumerable: true, get: function() {
          return auditTime_1.auditTime;
        } });
        var buffer_1 = require_buffer();
        Object.defineProperty(exports22, "buffer", { enumerable: true, get: function() {
          return buffer_1.buffer;
        } });
        var bufferCount_1 = require_bufferCount();
        Object.defineProperty(exports22, "bufferCount", { enumerable: true, get: function() {
          return bufferCount_1.bufferCount;
        } });
        var bufferTime_1 = require_bufferTime();
        Object.defineProperty(exports22, "bufferTime", { enumerable: true, get: function() {
          return bufferTime_1.bufferTime;
        } });
        var bufferToggle_1 = require_bufferToggle();
        Object.defineProperty(exports22, "bufferToggle", { enumerable: true, get: function() {
          return bufferToggle_1.bufferToggle;
        } });
        var bufferWhen_1 = require_bufferWhen();
        Object.defineProperty(exports22, "bufferWhen", { enumerable: true, get: function() {
          return bufferWhen_1.bufferWhen;
        } });
        var catchError_1 = require_catchError();
        Object.defineProperty(exports22, "catchError", { enumerable: true, get: function() {
          return catchError_1.catchError;
        } });
        var combineAll_1 = require_combineAll();
        Object.defineProperty(exports22, "combineAll", { enumerable: true, get: function() {
          return combineAll_1.combineAll;
        } });
        var combineLatestAll_1 = require_combineLatestAll();
        Object.defineProperty(exports22, "combineLatestAll", { enumerable: true, get: function() {
          return combineLatestAll_1.combineLatestAll;
        } });
        var combineLatestWith_1 = require_combineLatestWith();
        Object.defineProperty(exports22, "combineLatestWith", { enumerable: true, get: function() {
          return combineLatestWith_1.combineLatestWith;
        } });
        var concatAll_1 = require_concatAll();
        Object.defineProperty(exports22, "concatAll", { enumerable: true, get: function() {
          return concatAll_1.concatAll;
        } });
        var concatMap_1 = require_concatMap();
        Object.defineProperty(exports22, "concatMap", { enumerable: true, get: function() {
          return concatMap_1.concatMap;
        } });
        var concatMapTo_1 = require_concatMapTo();
        Object.defineProperty(exports22, "concatMapTo", { enumerable: true, get: function() {
          return concatMapTo_1.concatMapTo;
        } });
        var concatWith_1 = require_concatWith();
        Object.defineProperty(exports22, "concatWith", { enumerable: true, get: function() {
          return concatWith_1.concatWith;
        } });
        var connect_1 = require_connect();
        Object.defineProperty(exports22, "connect", { enumerable: true, get: function() {
          return connect_1.connect;
        } });
        var count_1 = require_count();
        Object.defineProperty(exports22, "count", { enumerable: true, get: function() {
          return count_1.count;
        } });
        var debounce_1 = require_debounce();
        Object.defineProperty(exports22, "debounce", { enumerable: true, get: function() {
          return debounce_1.debounce;
        } });
        var debounceTime_1 = require_debounceTime();
        Object.defineProperty(exports22, "debounceTime", { enumerable: true, get: function() {
          return debounceTime_1.debounceTime;
        } });
        var defaultIfEmpty_1 = require_defaultIfEmpty();
        Object.defineProperty(exports22, "defaultIfEmpty", { enumerable: true, get: function() {
          return defaultIfEmpty_1.defaultIfEmpty;
        } });
        var delay_1 = require_delay();
        Object.defineProperty(exports22, "delay", { enumerable: true, get: function() {
          return delay_1.delay;
        } });
        var delayWhen_1 = require_delayWhen();
        Object.defineProperty(exports22, "delayWhen", { enumerable: true, get: function() {
          return delayWhen_1.delayWhen;
        } });
        var dematerialize_1 = require_dematerialize();
        Object.defineProperty(exports22, "dematerialize", { enumerable: true, get: function() {
          return dematerialize_1.dematerialize;
        } });
        var distinct_1 = require_distinct();
        Object.defineProperty(exports22, "distinct", { enumerable: true, get: function() {
          return distinct_1.distinct;
        } });
        var distinctUntilChanged_1 = require_distinctUntilChanged();
        Object.defineProperty(exports22, "distinctUntilChanged", { enumerable: true, get: function() {
          return distinctUntilChanged_1.distinctUntilChanged;
        } });
        var distinctUntilKeyChanged_1 = require_distinctUntilKeyChanged();
        Object.defineProperty(exports22, "distinctUntilKeyChanged", { enumerable: true, get: function() {
          return distinctUntilKeyChanged_1.distinctUntilKeyChanged;
        } });
        var elementAt_1 = require_elementAt();
        Object.defineProperty(exports22, "elementAt", { enumerable: true, get: function() {
          return elementAt_1.elementAt;
        } });
        var endWith_1 = require_endWith();
        Object.defineProperty(exports22, "endWith", { enumerable: true, get: function() {
          return endWith_1.endWith;
        } });
        var every_1 = require_every();
        Object.defineProperty(exports22, "every", { enumerable: true, get: function() {
          return every_1.every;
        } });
        var exhaust_1 = require_exhaust();
        Object.defineProperty(exports22, "exhaust", { enumerable: true, get: function() {
          return exhaust_1.exhaust;
        } });
        var exhaustAll_1 = require_exhaustAll();
        Object.defineProperty(exports22, "exhaustAll", { enumerable: true, get: function() {
          return exhaustAll_1.exhaustAll;
        } });
        var exhaustMap_1 = require_exhaustMap();
        Object.defineProperty(exports22, "exhaustMap", { enumerable: true, get: function() {
          return exhaustMap_1.exhaustMap;
        } });
        var expand_1 = require_expand();
        Object.defineProperty(exports22, "expand", { enumerable: true, get: function() {
          return expand_1.expand;
        } });
        var filter_1 = require_filter();
        Object.defineProperty(exports22, "filter", { enumerable: true, get: function() {
          return filter_1.filter;
        } });
        var finalize_1 = require_finalize();
        Object.defineProperty(exports22, "finalize", { enumerable: true, get: function() {
          return finalize_1.finalize;
        } });
        var find_1 = require_find();
        Object.defineProperty(exports22, "find", { enumerable: true, get: function() {
          return find_1.find;
        } });
        var findIndex_1 = require_findIndex();
        Object.defineProperty(exports22, "findIndex", { enumerable: true, get: function() {
          return findIndex_1.findIndex;
        } });
        var first_1 = require_first();
        Object.defineProperty(exports22, "first", { enumerable: true, get: function() {
          return first_1.first;
        } });
        var groupBy_1 = require_groupBy();
        Object.defineProperty(exports22, "groupBy", { enumerable: true, get: function() {
          return groupBy_1.groupBy;
        } });
        var ignoreElements_1 = require_ignoreElements();
        Object.defineProperty(exports22, "ignoreElements", { enumerable: true, get: function() {
          return ignoreElements_1.ignoreElements;
        } });
        var isEmpty_1 = require_isEmpty();
        Object.defineProperty(exports22, "isEmpty", { enumerable: true, get: function() {
          return isEmpty_1.isEmpty;
        } });
        var last_1 = require_last();
        Object.defineProperty(exports22, "last", { enumerable: true, get: function() {
          return last_1.last;
        } });
        var map_1 = require_map();
        Object.defineProperty(exports22, "map", { enumerable: true, get: function() {
          return map_1.map;
        } });
        var mapTo_1 = require_mapTo();
        Object.defineProperty(exports22, "mapTo", { enumerable: true, get: function() {
          return mapTo_1.mapTo;
        } });
        var materialize_1 = require_materialize();
        Object.defineProperty(exports22, "materialize", { enumerable: true, get: function() {
          return materialize_1.materialize;
        } });
        var max_1 = require_max2();
        Object.defineProperty(exports22, "max", { enumerable: true, get: function() {
          return max_1.max;
        } });
        var mergeAll_1 = require_mergeAll();
        Object.defineProperty(exports22, "mergeAll", { enumerable: true, get: function() {
          return mergeAll_1.mergeAll;
        } });
        var flatMap_1 = require_flatMap();
        Object.defineProperty(exports22, "flatMap", { enumerable: true, get: function() {
          return flatMap_1.flatMap;
        } });
        var mergeMap_1 = require_mergeMap();
        Object.defineProperty(exports22, "mergeMap", { enumerable: true, get: function() {
          return mergeMap_1.mergeMap;
        } });
        var mergeMapTo_1 = require_mergeMapTo();
        Object.defineProperty(exports22, "mergeMapTo", { enumerable: true, get: function() {
          return mergeMapTo_1.mergeMapTo;
        } });
        var mergeScan_1 = require_mergeScan();
        Object.defineProperty(exports22, "mergeScan", { enumerable: true, get: function() {
          return mergeScan_1.mergeScan;
        } });
        var mergeWith_1 = require_mergeWith();
        Object.defineProperty(exports22, "mergeWith", { enumerable: true, get: function() {
          return mergeWith_1.mergeWith;
        } });
        var min_1 = require_min2();
        Object.defineProperty(exports22, "min", { enumerable: true, get: function() {
          return min_1.min;
        } });
        var multicast_1 = require_multicast();
        Object.defineProperty(exports22, "multicast", { enumerable: true, get: function() {
          return multicast_1.multicast;
        } });
        var observeOn_1 = require_observeOn();
        Object.defineProperty(exports22, "observeOn", { enumerable: true, get: function() {
          return observeOn_1.observeOn;
        } });
        var onErrorResumeNextWith_1 = require_onErrorResumeNextWith();
        Object.defineProperty(exports22, "onErrorResumeNextWith", { enumerable: true, get: function() {
          return onErrorResumeNextWith_1.onErrorResumeNextWith;
        } });
        var pairwise_1 = require_pairwise();
        Object.defineProperty(exports22, "pairwise", { enumerable: true, get: function() {
          return pairwise_1.pairwise;
        } });
        var pluck_1 = require_pluck();
        Object.defineProperty(exports22, "pluck", { enumerable: true, get: function() {
          return pluck_1.pluck;
        } });
        var publish_1 = require_publish();
        Object.defineProperty(exports22, "publish", { enumerable: true, get: function() {
          return publish_1.publish;
        } });
        var publishBehavior_1 = require_publishBehavior();
        Object.defineProperty(exports22, "publishBehavior", { enumerable: true, get: function() {
          return publishBehavior_1.publishBehavior;
        } });
        var publishLast_1 = require_publishLast();
        Object.defineProperty(exports22, "publishLast", { enumerable: true, get: function() {
          return publishLast_1.publishLast;
        } });
        var publishReplay_1 = require_publishReplay();
        Object.defineProperty(exports22, "publishReplay", { enumerable: true, get: function() {
          return publishReplay_1.publishReplay;
        } });
        var raceWith_1 = require_raceWith();
        Object.defineProperty(exports22, "raceWith", { enumerable: true, get: function() {
          return raceWith_1.raceWith;
        } });
        var reduce_1 = require_reduce();
        Object.defineProperty(exports22, "reduce", { enumerable: true, get: function() {
          return reduce_1.reduce;
        } });
        var repeat_1 = require_repeat();
        Object.defineProperty(exports22, "repeat", { enumerable: true, get: function() {
          return repeat_1.repeat;
        } });
        var repeatWhen_1 = require_repeatWhen();
        Object.defineProperty(exports22, "repeatWhen", { enumerable: true, get: function() {
          return repeatWhen_1.repeatWhen;
        } });
        var retry_1 = require_retry();
        Object.defineProperty(exports22, "retry", { enumerable: true, get: function() {
          return retry_1.retry;
        } });
        var retryWhen_1 = require_retryWhen();
        Object.defineProperty(exports22, "retryWhen", { enumerable: true, get: function() {
          return retryWhen_1.retryWhen;
        } });
        var refCount_1 = require_refCount();
        Object.defineProperty(exports22, "refCount", { enumerable: true, get: function() {
          return refCount_1.refCount;
        } });
        var sample_1 = require_sample();
        Object.defineProperty(exports22, "sample", { enumerable: true, get: function() {
          return sample_1.sample;
        } });
        var sampleTime_1 = require_sampleTime();
        Object.defineProperty(exports22, "sampleTime", { enumerable: true, get: function() {
          return sampleTime_1.sampleTime;
        } });
        var scan_1 = require_scan();
        Object.defineProperty(exports22, "scan", { enumerable: true, get: function() {
          return scan_1.scan;
        } });
        var sequenceEqual_1 = require_sequenceEqual();
        Object.defineProperty(exports22, "sequenceEqual", { enumerable: true, get: function() {
          return sequenceEqual_1.sequenceEqual;
        } });
        var share_1 = require_share();
        Object.defineProperty(exports22, "share", { enumerable: true, get: function() {
          return share_1.share;
        } });
        var shareReplay_1 = require_shareReplay();
        Object.defineProperty(exports22, "shareReplay", { enumerable: true, get: function() {
          return shareReplay_1.shareReplay;
        } });
        var single_1 = require_single();
        Object.defineProperty(exports22, "single", { enumerable: true, get: function() {
          return single_1.single;
        } });
        var skip_1 = require_skip();
        Object.defineProperty(exports22, "skip", { enumerable: true, get: function() {
          return skip_1.skip;
        } });
        var skipLast_1 = require_skipLast();
        Object.defineProperty(exports22, "skipLast", { enumerable: true, get: function() {
          return skipLast_1.skipLast;
        } });
        var skipUntil_1 = require_skipUntil();
        Object.defineProperty(exports22, "skipUntil", { enumerable: true, get: function() {
          return skipUntil_1.skipUntil;
        } });
        var skipWhile_1 = require_skipWhile();
        Object.defineProperty(exports22, "skipWhile", { enumerable: true, get: function() {
          return skipWhile_1.skipWhile;
        } });
        var startWith_1 = require_startWith();
        Object.defineProperty(exports22, "startWith", { enumerable: true, get: function() {
          return startWith_1.startWith;
        } });
        var subscribeOn_1 = require_subscribeOn();
        Object.defineProperty(exports22, "subscribeOn", { enumerable: true, get: function() {
          return subscribeOn_1.subscribeOn;
        } });
        var switchAll_1 = require_switchAll();
        Object.defineProperty(exports22, "switchAll", { enumerable: true, get: function() {
          return switchAll_1.switchAll;
        } });
        var switchMap_1 = require_switchMap();
        Object.defineProperty(exports22, "switchMap", { enumerable: true, get: function() {
          return switchMap_1.switchMap;
        } });
        var switchMapTo_1 = require_switchMapTo();
        Object.defineProperty(exports22, "switchMapTo", { enumerable: true, get: function() {
          return switchMapTo_1.switchMapTo;
        } });
        var switchScan_1 = require_switchScan();
        Object.defineProperty(exports22, "switchScan", { enumerable: true, get: function() {
          return switchScan_1.switchScan;
        } });
        var take_1 = require_take();
        Object.defineProperty(exports22, "take", { enumerable: true, get: function() {
          return take_1.take;
        } });
        var takeLast_1 = require_takeLast();
        Object.defineProperty(exports22, "takeLast", { enumerable: true, get: function() {
          return takeLast_1.takeLast;
        } });
        var takeUntil_1 = require_takeUntil();
        Object.defineProperty(exports22, "takeUntil", { enumerable: true, get: function() {
          return takeUntil_1.takeUntil;
        } });
        var takeWhile_1 = require_takeWhile();
        Object.defineProperty(exports22, "takeWhile", { enumerable: true, get: function() {
          return takeWhile_1.takeWhile;
        } });
        var tap_1 = require_tap();
        Object.defineProperty(exports22, "tap", { enumerable: true, get: function() {
          return tap_1.tap;
        } });
        var throttle_1 = require_throttle();
        Object.defineProperty(exports22, "throttle", { enumerable: true, get: function() {
          return throttle_1.throttle;
        } });
        var throttleTime_1 = require_throttleTime();
        Object.defineProperty(exports22, "throttleTime", { enumerable: true, get: function() {
          return throttleTime_1.throttleTime;
        } });
        var throwIfEmpty_1 = require_throwIfEmpty();
        Object.defineProperty(exports22, "throwIfEmpty", { enumerable: true, get: function() {
          return throwIfEmpty_1.throwIfEmpty;
        } });
        var timeInterval_1 = require_timeInterval();
        Object.defineProperty(exports22, "timeInterval", { enumerable: true, get: function() {
          return timeInterval_1.timeInterval;
        } });
        var timeout_2 = require_timeout();
        Object.defineProperty(exports22, "timeout", { enumerable: true, get: function() {
          return timeout_2.timeout;
        } });
        var timeoutWith_1 = require_timeoutWith();
        Object.defineProperty(exports22, "timeoutWith", { enumerable: true, get: function() {
          return timeoutWith_1.timeoutWith;
        } });
        var timestamp_1 = require_timestamp();
        Object.defineProperty(exports22, "timestamp", { enumerable: true, get: function() {
          return timestamp_1.timestamp;
        } });
        var toArray_1 = require_toArray();
        Object.defineProperty(exports22, "toArray", { enumerable: true, get: function() {
          return toArray_1.toArray;
        } });
        var window_1 = require_window();
        Object.defineProperty(exports22, "window", { enumerable: true, get: function() {
          return window_1.window;
        } });
        var windowCount_1 = require_windowCount();
        Object.defineProperty(exports22, "windowCount", { enumerable: true, get: function() {
          return windowCount_1.windowCount;
        } });
        var windowTime_1 = require_windowTime();
        Object.defineProperty(exports22, "windowTime", { enumerable: true, get: function() {
          return windowTime_1.windowTime;
        } });
        var windowToggle_1 = require_windowToggle();
        Object.defineProperty(exports22, "windowToggle", { enumerable: true, get: function() {
          return windowToggle_1.windowToggle;
        } });
        var windowWhen_1 = require_windowWhen();
        Object.defineProperty(exports22, "windowWhen", { enumerable: true, get: function() {
          return windowWhen_1.windowWhen;
        } });
        var withLatestFrom_1 = require_withLatestFrom();
        Object.defineProperty(exports22, "withLatestFrom", { enumerable: true, get: function() {
          return withLatestFrom_1.withLatestFrom;
        } });
        var zipAll_1 = require_zipAll();
        Object.defineProperty(exports22, "zipAll", { enumerable: true, get: function() {
          return zipAll_1.zipAll;
        } });
        var zipWith_1 = require_zipWith();
        Object.defineProperty(exports22, "zipWith", { enumerable: true, get: function() {
          return zipWith_1.zipWith;
        } });
      }
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.zip = exports2.timer = exports2.throwIfEmpty = exports2.tap = exports2.takeUntil = exports2.take = exports2.switchMap = exports2.startWith = exports2.retry = exports2.ReplaySubject = exports2.raceWith = exports2.race = exports2.pipe = exports2.of = exports2.Observable = exports2.noop = exports2.NEVER = exports2.mergeScan = exports2.mergeMap = exports2.merge = exports2.map = exports2.lastValueFrom = exports2.ignoreElements = exports2.identity = exports2.fromEvent = exports2.from = exports2.forkJoin = exports2.firstValueFrom = exports2.first = exports2.filter = exports2.EMPTY = exports2.distinctUntilChanged = exports2.delayWhen = exports2.delay = exports2.defer = exports2.defaultIfEmpty = exports2.debounceTime = exports2.concatMap = exports2.concat = exports2.combineLatest = exports2.catchError = exports2.bufferCount = void 0;
    var rxjs_1 = require_cjs2();
    Object.defineProperty(exports2, "bufferCount", { enumerable: true, get: function() {
      return rxjs_1.bufferCount;
    } });
    Object.defineProperty(exports2, "catchError", { enumerable: true, get: function() {
      return rxjs_1.catchError;
    } });
    Object.defineProperty(exports2, "combineLatest", { enumerable: true, get: function() {
      return rxjs_1.combineLatest;
    } });
    Object.defineProperty(exports2, "concat", { enumerable: true, get: function() {
      return rxjs_1.concat;
    } });
    Object.defineProperty(exports2, "concatMap", { enumerable: true, get: function() {
      return rxjs_1.concatMap;
    } });
    Object.defineProperty(exports2, "debounceTime", { enumerable: true, get: function() {
      return rxjs_1.debounceTime;
    } });
    Object.defineProperty(exports2, "defaultIfEmpty", { enumerable: true, get: function() {
      return rxjs_1.defaultIfEmpty;
    } });
    Object.defineProperty(exports2, "defer", { enumerable: true, get: function() {
      return rxjs_1.defer;
    } });
    Object.defineProperty(exports2, "delay", { enumerable: true, get: function() {
      return rxjs_1.delay;
    } });
    Object.defineProperty(exports2, "delayWhen", { enumerable: true, get: function() {
      return rxjs_1.delayWhen;
    } });
    Object.defineProperty(exports2, "distinctUntilChanged", { enumerable: true, get: function() {
      return rxjs_1.distinctUntilChanged;
    } });
    Object.defineProperty(exports2, "EMPTY", { enumerable: true, get: function() {
      return rxjs_1.EMPTY;
    } });
    Object.defineProperty(exports2, "filter", { enumerable: true, get: function() {
      return rxjs_1.filter;
    } });
    Object.defineProperty(exports2, "first", { enumerable: true, get: function() {
      return rxjs_1.first;
    } });
    Object.defineProperty(exports2, "firstValueFrom", { enumerable: true, get: function() {
      return rxjs_1.firstValueFrom;
    } });
    Object.defineProperty(exports2, "forkJoin", { enumerable: true, get: function() {
      return rxjs_1.forkJoin;
    } });
    Object.defineProperty(exports2, "from", { enumerable: true, get: function() {
      return rxjs_1.from;
    } });
    Object.defineProperty(exports2, "fromEvent", { enumerable: true, get: function() {
      return rxjs_1.fromEvent;
    } });
    Object.defineProperty(exports2, "identity", { enumerable: true, get: function() {
      return rxjs_1.identity;
    } });
    Object.defineProperty(exports2, "ignoreElements", { enumerable: true, get: function() {
      return rxjs_1.ignoreElements;
    } });
    Object.defineProperty(exports2, "lastValueFrom", { enumerable: true, get: function() {
      return rxjs_1.lastValueFrom;
    } });
    Object.defineProperty(exports2, "map", { enumerable: true, get: function() {
      return rxjs_1.map;
    } });
    Object.defineProperty(exports2, "merge", { enumerable: true, get: function() {
      return rxjs_1.merge;
    } });
    Object.defineProperty(exports2, "mergeMap", { enumerable: true, get: function() {
      return rxjs_1.mergeMap;
    } });
    Object.defineProperty(exports2, "mergeScan", { enumerable: true, get: function() {
      return rxjs_1.mergeScan;
    } });
    Object.defineProperty(exports2, "NEVER", { enumerable: true, get: function() {
      return rxjs_1.NEVER;
    } });
    Object.defineProperty(exports2, "noop", { enumerable: true, get: function() {
      return rxjs_1.noop;
    } });
    Object.defineProperty(exports2, "Observable", { enumerable: true, get: function() {
      return rxjs_1.Observable;
    } });
    Object.defineProperty(exports2, "of", { enumerable: true, get: function() {
      return rxjs_1.of;
    } });
    Object.defineProperty(exports2, "pipe", { enumerable: true, get: function() {
      return rxjs_1.pipe;
    } });
    Object.defineProperty(exports2, "race", { enumerable: true, get: function() {
      return rxjs_1.race;
    } });
    Object.defineProperty(exports2, "raceWith", { enumerable: true, get: function() {
      return rxjs_1.raceWith;
    } });
    Object.defineProperty(exports2, "ReplaySubject", { enumerable: true, get: function() {
      return rxjs_1.ReplaySubject;
    } });
    Object.defineProperty(exports2, "retry", { enumerable: true, get: function() {
      return rxjs_1.retry;
    } });
    Object.defineProperty(exports2, "startWith", { enumerable: true, get: function() {
      return rxjs_1.startWith;
    } });
    Object.defineProperty(exports2, "switchMap", { enumerable: true, get: function() {
      return rxjs_1.switchMap;
    } });
    Object.defineProperty(exports2, "take", { enumerable: true, get: function() {
      return rxjs_1.take;
    } });
    Object.defineProperty(exports2, "takeUntil", { enumerable: true, get: function() {
      return rxjs_1.takeUntil;
    } });
    Object.defineProperty(exports2, "tap", { enumerable: true, get: function() {
      return rxjs_1.tap;
    } });
    Object.defineProperty(exports2, "throwIfEmpty", { enumerable: true, get: function() {
      return rxjs_1.throwIfEmpty;
    } });
    Object.defineProperty(exports2, "timer", { enumerable: true, get: function() {
      return rxjs_1.timer;
    } });
    Object.defineProperty(exports2, "zip", { enumerable: true, get: function() {
      return rxjs_1.zip;
    } });
  }
});

// node_modules/puppeteer-core/lib/cjs/third_party/mitt/mitt.js
var require_mitt = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/third_party/mitt/mitt.js"(exports2) {
    "use strict";
    init_prefix();
    var __defProp2 = Object.defineProperty;
    var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames2 = Object.getOwnPropertyNames;
    var __hasOwnProp2 = Object.prototype.hasOwnProperty;
    var __esm2 = (fn, res) => function __init() {
      return fn && (res = (0, fn[__getOwnPropNames2(fn)[0]])(fn = 0)), res;
    };
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp2(target, name, { get: all[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 __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
    var mitt_exports2 = {};
    __export2(mitt_exports2, {
      default: () => mitt_default2
    });
    function mitt_default2(n) {
      return { all: n = n || /* @__PURE__ */ new Map(), on: function(t, e) {
        var i = n.get(t);
        i ? i.push(e) : n.set(t, [e]);
      }, off: function(t, e) {
        var i = n.get(t);
        i && (e ? i.splice(i.indexOf(e) >>> 0, 1) : n.set(t, []));
      }, emit: function(t, e) {
        var i = n.get(t);
        i && i.slice().map(function(n2) {
          n2(e);
        }), (i = n.get("*")) && i.slice().map(function(n2) {
          n2(t, e);
        });
      } };
    }
    var init_mitt2 = __esm2({
      "node_modules/mitt/dist/mitt.mjs"() {
      }
    });
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports22) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports22, p)) __createBinding2(exports22, m, p);
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.default = void 0;
    __exportStar2((init_mitt2(), __toCommonJS2(mitt_exports2)), exports2);
    var mitt_1 = (init_mitt2(), __toCommonJS2(mitt_exports2));
    Object.defineProperty(exports2, "default", { enumerable: true, get: function() {
      return __importDefault2(mitt_1).default;
    } });
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/util/disposable.js
var require_disposable = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/util/disposable.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SuppressedError = exports2.AsyncDisposableStack = exports2.AsyncDisposableStackPolyfill = exports2.DisposableStack = exports2.DisposableStackPolyfill = exports2.asyncDisposeSymbol = exports2.disposeSymbol = void 0;
    Symbol.dispose ??= /* @__PURE__ */ Symbol("dispose");
    Symbol.asyncDispose ??= /* @__PURE__ */ Symbol("asyncDispose");
    exports2.disposeSymbol = Symbol.dispose;
    exports2.asyncDisposeSymbol = Symbol.asyncDispose;
    var DisposableStackPolyfill = class _DisposableStackPolyfill {
      #disposed = false;
      #stack = [];
      /**
       * Returns a value indicating whether the stack has been disposed.
       */
      get disposed() {
        return this.#disposed;
      }
      /**
       * Alias for `[Symbol.dispose]()`.
       */
      dispose() {
        this[exports2.disposeSymbol]();
      }
      /**
       * Adds a disposable resource to the top of stack, returning the resource.
       * Has no effect if provided `null` or `undefined`.
       *
       * @param value - A `Disposable` object, `null`, or `undefined`.
       * `null` and `undefined` will not be added, but will be returned.
       * @returns The provided `value`.
       */
      use(value) {
        if (value && typeof value[exports2.disposeSymbol] === "function") {
          this.#stack.push(value);
        }
        return value;
      }
      /**
       * Adds a non-disposable resource and a disposal callback to the top of the stack.
       *
       * @param value - A resource to be disposed.
       * @param onDispose - A callback invoked to dispose the provided value.
       * Will be invoked with `value` as the first parameter.
       * @returns The provided `value`.
       */
      adopt(value, onDispose) {
        this.#stack.push({
          [exports2.disposeSymbol]() {
            onDispose(value);
          }
        });
        return value;
      }
      /**
       * Add a disposal callback to the top of the stack to be invoked when stack is disposed.
       * @param onDispose - A callback to invoke when this object is disposed.
       */
      defer(onDispose) {
        this.#stack.push({
          [exports2.disposeSymbol]() {
            onDispose();
          }
        });
      }
      /**
       * Move all resources out of this stack and into a new `DisposableStack`, and
       * marks this stack as disposed.
       * @returns The new `DisposableStack`.
       *
       * @example
       *
       * ```ts
       * class C {
       *   #res1: Disposable;
       *   #res2: Disposable;
       *   #disposables: DisposableStack;
       *   constructor() {
       *     // stack will be disposed when exiting constructor for any reason
       *     using stack = new DisposableStack();
       *
       *     // get first resource
       *     this.#res1 = stack.use(getResource1());
       *
       *     // get second resource. If this fails, both `stack` and `#res1` will be disposed.
       *     this.#res2 = stack.use(getResource2());
       *
       *     // all operations succeeded, move resources out of `stack` so that
       *     // they aren't disposed when constructor exits
       *     this.#disposables = stack.move();
       *   }
       *
       *   [disposeSymbol]() {
       *     this.#disposables.dispose();
       *   }
       * }
       * ```
       */
      move() {
        if (this.#disposed) {
          throw new ReferenceError("A disposed stack can not use anything new");
        }
        const stack = new _DisposableStackPolyfill();
        stack.#stack = this.#stack;
        this.#stack = [];
        this.#disposed = true;
        return stack;
      }
      /**
       * Disposes each resource in the stack in last-in-first-out (LIFO) manner.
       */
      [exports2.disposeSymbol]() {
        if (this.#disposed) {
          return;
        }
        this.#disposed = true;
        const errors = [];
        for (const resource of this.#stack.reverse()) {
          try {
            resource[exports2.disposeSymbol]();
          } catch (e) {
            errors.push(e);
          }
        }
        if (errors.length === 1) {
          throw errors[0];
        } else if (errors.length > 1) {
          let suppressed = null;
          for (const error of errors) {
            if (suppressed === null) {
              suppressed = error;
            } else {
              suppressed = new SuppressedErrorPolyfill(error, suppressed);
            }
          }
          throw suppressed;
        }
      }
      [Symbol.toStringTag] = "DisposableStack";
    };
    exports2.DisposableStackPolyfill = DisposableStackPolyfill;
    exports2.DisposableStack = globalThis.DisposableStack ?? DisposableStackPolyfill;
    var AsyncDisposableStackPolyfill = class _AsyncDisposableStackPolyfill {
      #disposed = false;
      #stack = [];
      /**
       * Returns a value indicating whether the stack has been disposed.
       */
      get disposed() {
        return this.#disposed;
      }
      /**
       * Alias for `[Symbol.asyncDispose]()`.
       */
      async disposeAsync() {
        await this[exports2.asyncDisposeSymbol]();
      }
      /**
       * Adds a AsyncDisposable resource to the top of stack, returning the resource.
       * Has no effect if provided `null` or `undefined`.
       *
       * @param value - A `AsyncDisposable` object, `null`, or `undefined`.
       * `null` and `undefined` will not be added, but will be returned.
       * @returns The provided `value`.
       */
      use(value) {
        if (value) {
          const asyncDispose = value[exports2.asyncDisposeSymbol];
          const dispose = value[exports2.disposeSymbol];
          if (typeof asyncDispose === "function") {
            this.#stack.push(value);
          } else if (typeof dispose === "function") {
            this.#stack.push({
              [exports2.asyncDisposeSymbol]: async () => {
                value[exports2.disposeSymbol]();
              }
            });
          }
        }
        return value;
      }
      /**
       * Adds a non-disposable resource and a disposal callback to the top of the stack.
       *
       * @param value - A resource to be disposed.
       * @param onDispose - A callback invoked to dispose the provided value.
       * Will be invoked with `value` as the first parameter.
       * @returns The provided `value`.
       */
      adopt(value, onDispose) {
        this.#stack.push({
          [exports2.asyncDisposeSymbol]() {
            return onDispose(value);
          }
        });
        return value;
      }
      /**
       * Add a disposal callback to the top of the stack to be invoked when stack is disposed.
       * @param onDispose - A callback to invoke when this object is disposed.
       */
      defer(onDispose) {
        this.#stack.push({
          [exports2.asyncDisposeSymbol]() {
            return onDispose();
          }
        });
      }
      /**
       * Move all resources out of this stack and into a new `DisposableStack`, and
       * marks this stack as disposed.
       * @returns The new `AsyncDisposableStack`.
       *
       * @example
       *
       * ```ts
       * class C {
       *   #res1: Disposable;
       *   #res2: Disposable;
       *   #disposables: DisposableStack;
       *   constructor() {
       *     // stack will be disposed when exiting constructor for any reason
       *     using stack = new DisposableStack();
       *
       *     // get first resource
       *     this.#res1 = stack.use(getResource1());
       *
       *     // get second resource. If this fails, both `stack` and `#res1` will be disposed.
       *     this.#res2 = stack.use(getResource2());
       *
       *     // all operations succeeded, move resources out of `stack` so that
       *     // they aren't disposed when constructor exits
       *     this.#disposables = stack.move();
       *   }
       *
       *   [disposeSymbol]() {
       *     this.#disposables.dispose();
       *   }
       * }
       * ```
       */
      move() {
        if (this.#disposed) {
          throw new ReferenceError("A disposed stack can not use anything new");
        }
        const stack = new _AsyncDisposableStackPolyfill();
        stack.#stack = this.#stack;
        this.#stack = [];
        this.#disposed = true;
        return stack;
      }
      /**
       * Disposes each resource in the stack in last-in-first-out (LIFO) manner.
       */
      async [exports2.asyncDisposeSymbol]() {
        if (this.#disposed) {
          return;
        }
        this.#disposed = true;
        const errors = [];
        for (const resource of this.#stack.reverse()) {
          try {
            await resource[exports2.asyncDisposeSymbol]();
          } catch (e) {
            errors.push(e);
          }
        }
        if (errors.length === 1) {
          throw errors[0];
        } else if (errors.length > 1) {
          let suppressed = null;
          for (const error of errors) {
            if (suppressed === null) {
              suppressed = error;
            } else {
              suppressed = new SuppressedErrorPolyfill(error, suppressed);
            }
          }
          throw suppressed;
        }
      }
      [Symbol.toStringTag] = "AsyncDisposableStack";
    };
    exports2.AsyncDisposableStackPolyfill = AsyncDisposableStackPolyfill;
    exports2.AsyncDisposableStack = globalThis.AsyncDisposableStack ?? AsyncDisposableStackPolyfill;
    var SuppressedErrorPolyfill = class extends Error {
      #error;
      #suppressed;
      constructor(error, suppressed, message = "An error was suppressed during disposal") {
        super(message);
        this.name = "SuppressedError";
        this.#error = error;
        this.#suppressed = suppressed;
      }
      /**
       * The primary error that occurred during disposal.
       */
      get error() {
        return this.#error;
      }
      /**
       * The suppressed error i.e. the error that was suppressed
       * because it occurred later in the flow after the original error.
       */
      get suppressed() {
        return this.#suppressed;
      }
    };
    exports2.SuppressedError = globalThis.SuppressedError ?? SuppressedErrorPolyfill;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/EventEmitter.js
var require_EventEmitter = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/EventEmitter.js"(exports2) {
    "use strict";
    init_prefix();
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.EventEmitter = void 0;
    var mitt_js_1 = __importDefault2(require_mitt());
    var disposable_js_1 = require_disposable();
    var EventEmitter = class {
      #emitter;
      #handlers = /* @__PURE__ */ new Map();
      /**
       * If you pass an emitter, the returned emitter will wrap the passed emitter.
       *
       * @internal
       */
      constructor(emitter = (0, mitt_js_1.default)(/* @__PURE__ */ new Map())) {
        this.#emitter = emitter;
      }
      /**
       * Bind an event listener to fire when an event occurs.
       * @param type - the event type you'd like to listen to. Can be a string or symbol.
       * @param handler - the function to be called when the event occurs.
       * @returns `this` to enable you to chain method calls.
       */
      on(type, handler) {
        const handlers = this.#handlers.get(type);
        if (handlers === void 0) {
          this.#handlers.set(type, [handler]);
        } else {
          handlers.push(handler);
        }
        this.#emitter.on(type, handler);
        return this;
      }
      /**
       * Remove an event listener from firing.
       * @param type - the event type you'd like to stop listening to.
       * @param handler - the function that should be removed.
       * @returns `this` to enable you to chain method calls.
       */
      off(type, handler) {
        const handlers = this.#handlers.get(type) ?? [];
        if (handler === void 0) {
          for (const handler2 of handlers) {
            this.#emitter.off(type, handler2);
          }
          this.#handlers.delete(type);
          return this;
        }
        const index = handlers.lastIndexOf(handler);
        if (index > -1) {
          this.#emitter.off(type, ...handlers.splice(index, 1));
        }
        return this;
      }
      /**
       * Emit an event and call any associated listeners.
       *
       * @param type - the event you'd like to emit
       * @param eventData - any data you'd like to emit with the event
       * @returns `true` if there are any listeners, `false` if there are not.
       */
      emit(type, event) {
        this.#emitter.emit(type, event);
        return this.listenerCount(type) > 0;
      }
      /**
       * Like `on` but the listener will only be fired once and then it will be removed.
       * @param type - the event you'd like to listen to
       * @param handler - the handler function to run when the event occurs
       * @returns `this` to enable you to chain method calls.
       */
      once(type, handler) {
        const onceHandler = (eventData) => {
          handler(eventData);
          this.off(type, onceHandler);
        };
        return this.on(type, onceHandler);
      }
      /**
       * Gets the number of listeners for a given event.
       *
       * @param type - the event to get the listener count for
       * @returns the number of listeners bound to the given event
       */
      listenerCount(type) {
        return this.#handlers.get(type)?.length || 0;
      }
      /**
       * Removes all listeners. If given an event argument, it will remove only
       * listeners for that event.
       *
       * @param type - the event to remove listeners for.
       * @returns `this` to enable you to chain method calls.
       */
      removeAllListeners(type) {
        if (type !== void 0) {
          return this.off(type);
        }
        this[disposable_js_1.disposeSymbol]();
        return this;
      }
      /**
       * @internal
       */
      [disposable_js_1.disposeSymbol]() {
        for (const [type, handlers] of this.#handlers) {
          for (const handler of handlers) {
            this.#emitter.off(type, handler);
          }
        }
        this.#handlers.clear();
      }
    };
    exports2.EventEmitter = EventEmitter;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/environment.js
var require_environment = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/environment.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.environment = exports2.isNode = void 0;
    exports2.isNode = !!(typeof process !== "undefined" && process.version);
    exports2.environment = {
      value: {
        get fs() {
          throw new Error("fs is not available in this environment");
        },
        get ScreenRecorder() {
          throw new Error("ScreenRecorder is not available in this environment");
        }
      }
    };
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/util/assert.js
var require_assert = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/util/assert.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.assert = void 0;
    var assert = (value, message) => {
      if (!value) {
        throw new Error(message);
      }
    };
    exports2.assert = assert;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/util/encoding.js
var require_encoding = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/util/encoding.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.stringToTypedArray = stringToTypedArray;
    exports2.stringToBase64 = stringToBase64;
    exports2.typedArrayToBase64 = typedArrayToBase64;
    exports2.mergeUint8Arrays = mergeUint8Arrays;
    function stringToTypedArray(string, base64Encoded = false) {
      if (base64Encoded) {
        if ("fromBase64" in Uint8Array) {
          return Uint8Array.fromBase64(string);
        }
        if (typeof Buffer === "function") {
          return Buffer.from(string, "base64");
        }
        return Uint8Array.from(atob(string), (m) => {
          return m.codePointAt(0);
        });
      }
      return new TextEncoder().encode(string);
    }
    function stringToBase64(str) {
      return typedArrayToBase64(new TextEncoder().encode(str));
    }
    function typedArrayToBase64(typedArray) {
      const chunkSize = 65534;
      const chunks = [];
      for (let i = 0; i < typedArray.length; i += chunkSize) {
        const chunk = typedArray.subarray(i, i + chunkSize);
        chunks.push(String.fromCodePoint.apply(null, chunk));
      }
      const binaryString = chunks.join("");
      return btoa(binaryString);
    }
    function mergeUint8Arrays(items) {
      let length = 0;
      for (const item of items) {
        length += item.length;
      }
      const result = new Uint8Array(length);
      let offset = 0;
      for (const item of items) {
        result.set(item, offset);
        offset += item.length;
      }
      return result;
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/util/version.js
var require_version = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/util/version.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.packageVersion = void 0;
    exports2.packageVersion = "24.40.0";
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/Debug.js
var require_Debug = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/Debug.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
      var ownKeys2 = function(o) {
        ownKeys2 = 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 ownKeys2(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]);
        }
        __setModuleDefault2(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.debug = void 0;
    exports2.importDebug = importDebug;
    exports2.setLogCapture = setLogCapture;
    exports2.getCapturedLogs = getCapturedLogs;
    var environment_js_1 = require_environment();
    var debugModule = null;
    async function importDebug() {
      if (!debugModule) {
        debugModule = (await Promise.resolve().then(() => __importStar2(require_src()))).default;
      }
      return debugModule;
    }
    var debug = (prefix) => {
      if (environment_js_1.isNode) {
        return async (...logArgs) => {
          if (captureLogs) {
            capturedLogs.push(prefix + logArgs);
          }
          (await importDebug())(prefix)(logArgs);
        };
      }
      return (...logArgs) => {
        const debugLevel = globalThis.__PUPPETEER_DEBUG;
        if (!debugLevel) {
          return;
        }
        const everythingShouldBeLogged = debugLevel === "*";
        const prefixMatchesDebugLevel = everythingShouldBeLogged || /**
         * If the debug level is `foo*`, that means we match any prefix that
         * starts with `foo`. If the level is `foo`, we match only the prefix
         * `foo`.
         */
        (debugLevel.endsWith("*") ? prefix.startsWith(debugLevel) : prefix === debugLevel);
        if (!prefixMatchesDebugLevel) {
          return;
        }
        console.log(`${prefix}:`, ...logArgs);
      };
    };
    exports2.debug = debug;
    var capturedLogs = [];
    var captureLogs = false;
    function setLogCapture(value) {
      capturedLogs = [];
      captureLogs = value;
    }
    function getCapturedLogs() {
      return capturedLogs;
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/Errors.js
var require_Errors = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/Errors.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ConnectionClosedError = exports2.TargetCloseError = exports2.UnsupportedOperation = exports2.ProtocolError = exports2.TouchError = exports2.TimeoutError = exports2.PuppeteerError = void 0;
    var PuppeteerError = class extends Error {
      /**
       * @internal
       */
      constructor(message, options) {
        super(message, options);
        this.name = this.constructor.name;
      }
      /**
       * @internal
       */
      get [Symbol.toStringTag]() {
        return this.constructor.name;
      }
    };
    exports2.PuppeteerError = PuppeteerError;
    var TimeoutError = class extends PuppeteerError {
    };
    exports2.TimeoutError = TimeoutError;
    var TouchError = class extends PuppeteerError {
    };
    exports2.TouchError = TouchError;
    var ProtocolError = class extends PuppeteerError {
      #code;
      #originalMessage = "";
      set code(code) {
        this.#code = code;
      }
      /**
       * @readonly
       * @public
       */
      get code() {
        return this.#code;
      }
      set originalMessage(originalMessage) {
        this.#originalMessage = originalMessage;
      }
      /**
       * @readonly
       * @public
       */
      get originalMessage() {
        return this.#originalMessage;
      }
    };
    exports2.ProtocolError = ProtocolError;
    var UnsupportedOperation = class extends PuppeteerError {
    };
    exports2.UnsupportedOperation = UnsupportedOperation;
    var TargetCloseError = class extends ProtocolError {
    };
    exports2.TargetCloseError = TargetCloseError;
    var ConnectionClosedError = class extends ProtocolError {
    };
    exports2.ConnectionClosedError = ConnectionClosedError;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/PDFOptions.js
var require_PDFOptions = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/PDFOptions.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.paperFormats = void 0;
    exports2.paperFormats = {
      letter: {
        cm: { width: 21.59, height: 27.94 },
        in: { width: 8.5, height: 11 }
      },
      legal: {
        cm: { width: 21.59, height: 35.56 },
        in: { width: 8.5, height: 14 }
      },
      tabloid: {
        cm: { width: 27.94, height: 43.18 },
        in: { width: 11, height: 17 }
      },
      ledger: {
        cm: { width: 43.18, height: 27.94 },
        in: { width: 17, height: 11 }
      },
      a0: {
        cm: { width: 84.1, height: 118.9 },
        in: { width: 33.1102, height: 46.811 }
      },
      a1: {
        cm: { width: 59.4, height: 84.1 },
        in: { width: 23.3858, height: 33.1102 }
      },
      a2: {
        cm: { width: 42, height: 59.4 },
        in: { width: 16.5354, height: 23.3858 }
      },
      a3: {
        cm: { width: 29.7, height: 42 },
        in: { width: 11.6929, height: 16.5354 }
      },
      a4: {
        cm: { width: 21, height: 29.7 },
        in: { width: 8.2677, height: 11.6929 }
      },
      a5: {
        cm: { width: 14.8, height: 21 },
        in: { width: 5.8268, height: 8.2677 }
      },
      a6: {
        cm: { width: 10.5, height: 14.8 },
        in: { width: 4.1339, height: 5.8268 }
      }
    };
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/util.js
var require_util = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/util.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.unitToPixels = exports2.NETWORK_IDLE_TIME = exports2.SOURCE_URL_REGEX = exports2.UTILITY_WORLD_NAME = exports2.isDate = exports2.isRegExp = exports2.isPlainObject = exports2.isNumber = exports2.isString = exports2.getSourcePuppeteerURLIfAvailable = exports2.withSourcePuppeteerURLIfNone = exports2.PuppeteerURL = exports2.DEFAULT_VIEWPORT = exports2.debugError = void 0;
    exports2.evaluationString = evaluationString;
    exports2.getReadableAsTypedArray = getReadableAsTypedArray;
    exports2.getReadableFromProtocolStream = getReadableFromProtocolStream;
    exports2.validateDialogType = validateDialogType;
    exports2.timeout = timeout;
    exports2.getSourceUrlComment = getSourceUrlComment;
    exports2.parsePDFOptions = parsePDFOptions;
    exports2.fromEmitterEvent = fromEmitterEvent;
    exports2.fromAbortSignal = fromAbortSignal;
    exports2.filterAsync = filterAsync;
    var rxjs_js_1 = require_rxjs();
    var environment_js_1 = require_environment();
    var assert_js_1 = require_assert();
    var encoding_js_1 = require_encoding();
    var version_js_1 = require_version();
    var Debug_js_1 = require_Debug();
    var Errors_js_1 = require_Errors();
    var PDFOptions_js_1 = require_PDFOptions();
    exports2.debugError = (0, Debug_js_1.debug)("puppeteer:error");
    exports2.DEFAULT_VIEWPORT = Object.freeze({ width: 800, height: 600 });
    var SOURCE_URL = /* @__PURE__ */ Symbol("Source URL for Puppeteer evaluation scripts");
    var PuppeteerURL = class _PuppeteerURL {
      static INTERNAL_URL = "pptr:internal";
      static fromCallSite(functionName, site) {
        const url = new _PuppeteerURL();
        url.#functionName = functionName;
        url.#siteString = site.toString();
        return url;
      }
      static parse = (url) => {
        url = url.slice("pptr:".length);
        const [functionName = "", siteString = ""] = url.split(";");
        const puppeteerUrl = new _PuppeteerURL();
        puppeteerUrl.#functionName = functionName;
        puppeteerUrl.#siteString = decodeURIComponent(siteString);
        return puppeteerUrl;
      };
      static isPuppeteerURL = (url) => {
        return url.startsWith("pptr:");
      };
      #functionName;
      #siteString;
      get functionName() {
        return this.#functionName;
      }
      get siteString() {
        return this.#siteString;
      }
      toString() {
        return `pptr:${[
          this.#functionName,
          encodeURIComponent(this.#siteString)
        ].join(";")}`;
      }
    };
    exports2.PuppeteerURL = PuppeteerURL;
    var withSourcePuppeteerURLIfNone = (functionName, object) => {
      if (Object.prototype.hasOwnProperty.call(object, SOURCE_URL)) {
        return object;
      }
      const original = Error.prepareStackTrace;
      Error.prepareStackTrace = (_, stack) => {
        return stack[2];
      };
      const site = new Error().stack;
      Error.prepareStackTrace = original;
      return Object.assign(object, {
        [SOURCE_URL]: PuppeteerURL.fromCallSite(functionName, site)
      });
    };
    exports2.withSourcePuppeteerURLIfNone = withSourcePuppeteerURLIfNone;
    var getSourcePuppeteerURLIfAvailable = (object) => {
      if (Object.prototype.hasOwnProperty.call(object, SOURCE_URL)) {
        return object[SOURCE_URL];
      }
      return void 0;
    };
    exports2.getSourcePuppeteerURLIfAvailable = getSourcePuppeteerURLIfAvailable;
    var isString = (obj) => {
      return typeof obj === "string" || obj instanceof String;
    };
    exports2.isString = isString;
    var isNumber = (obj) => {
      return typeof obj === "number" || obj instanceof Number;
    };
    exports2.isNumber = isNumber;
    var isPlainObject = (obj) => {
      return typeof obj === "object" && obj?.constructor === Object;
    };
    exports2.isPlainObject = isPlainObject;
    var isRegExp = (obj) => {
      return typeof obj === "object" && obj?.constructor === RegExp;
    };
    exports2.isRegExp = isRegExp;
    var isDate = (obj) => {
      return typeof obj === "object" && obj?.constructor === Date;
    };
    exports2.isDate = isDate;
    function evaluationString(fun, ...args2) {
      if ((0, exports2.isString)(fun)) {
        (0, assert_js_1.assert)(args2.length === 0, "Cannot evaluate a string with arguments");
        return fun;
      }
      function serializeArgument(arg) {
        if (Object.is(arg, void 0)) {
          return "undefined";
        }
        return JSON.stringify(arg);
      }
      return `(${fun})(${args2.map(serializeArgument).join(",")})`;
    }
    async function getReadableAsTypedArray(readable, path2) {
      const buffers = [];
      const reader = readable.getReader();
      if (path2) {
        const fileHandle = await environment_js_1.environment.value.fs.promises.open(path2, "w+");
        try {
          while (true) {
            const { done, value } = await reader.read();
            if (done) {
              break;
            }
            buffers.push(value);
            await fileHandle.writeFile(value);
          }
        } finally {
          await fileHandle.close();
        }
      } else {
        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            break;
          }
          buffers.push(value);
        }
      }
      try {
        const concat = (0, encoding_js_1.mergeUint8Arrays)(buffers);
        if (concat.length === 0) {
          return null;
        }
        return concat;
      } catch (error) {
        (0, exports2.debugError)(error);
        return null;
      }
    }
    async function getReadableFromProtocolStream(client2, handle) {
      return new ReadableStream({
        async pull(controller) {
          const { data, base64Encoded, eof } = await client2.send("IO.read", {
            handle
          });
          controller.enqueue((0, encoding_js_1.stringToTypedArray)(data, base64Encoded ?? false));
          if (eof) {
            await client2.send("IO.close", { handle });
            controller.close();
          }
        }
      });
    }
    var VALID_DIALOG_TYPES = /* @__PURE__ */ new Set([
      "alert",
      "confirm",
      "prompt",
      "beforeunload"
    ]);
    function validateDialogType(type) {
      let dialogType = null;
      if (VALID_DIALOG_TYPES.has(type)) {
        dialogType = type;
      }
      (0, assert_js_1.assert)(dialogType, `Unknown javascript dialog type: ${type}`);
      return dialogType;
    }
    function timeout(ms, cause) {
      return ms === 0 ? rxjs_js_1.NEVER : (0, rxjs_js_1.timer)(ms).pipe((0, rxjs_js_1.map)(() => {
        throw new Errors_js_1.TimeoutError(`Timed out after waiting ${ms}ms`, { cause });
      }));
    }
    exports2.UTILITY_WORLD_NAME = "__puppeteer_utility_world__" + version_js_1.packageVersion;
    exports2.SOURCE_URL_REGEX = /^[\x20\t]*\/\/[@#] sourceURL=\s{0,10}(\S*?)\s{0,10}$/m;
    function getSourceUrlComment(url) {
      return `//# sourceURL=${url}`;
    }
    exports2.NETWORK_IDLE_TIME = 500;
    function parsePDFOptions(options = {}, lengthUnit = "in") {
      const defaults = {
        scale: 1,
        displayHeaderFooter: false,
        headerTemplate: "",
        footerTemplate: "",
        printBackground: false,
        landscape: false,
        pageRanges: "",
        preferCSSPageSize: false,
        omitBackground: false,
        outline: false,
        tagged: true,
        waitForFonts: true
      };
      let width = 8.5;
      let height = 11;
      if (options.format) {
        const format3 = PDFOptions_js_1.paperFormats[options.format.toLowerCase()][lengthUnit];
        (0, assert_js_1.assert)(format3, "Unknown paper format: " + options.format);
        width = format3.width;
        height = format3.height;
      } else {
        width = convertPrintParameterToInches(options.width, lengthUnit) ?? width;
        height = convertPrintParameterToInches(options.height, lengthUnit) ?? height;
      }
      const margin = {
        top: convertPrintParameterToInches(options.margin?.top, lengthUnit) || 0,
        left: convertPrintParameterToInches(options.margin?.left, lengthUnit) || 0,
        bottom: convertPrintParameterToInches(options.margin?.bottom, lengthUnit) || 0,
        right: convertPrintParameterToInches(options.margin?.right, lengthUnit) || 0
      };
      if (options.outline) {
        options.tagged = true;
      }
      return {
        ...defaults,
        ...options,
        width,
        height,
        margin
      };
    }
    exports2.unitToPixels = {
      px: 1,
      in: 96,
      cm: 37.8,
      mm: 3.78
    };
    function convertPrintParameterToInches(parameter, lengthUnit = "in") {
      if (typeof parameter === "undefined") {
        return void 0;
      }
      let pixels;
      if ((0, exports2.isNumber)(parameter)) {
        pixels = parameter;
      } else if ((0, exports2.isString)(parameter)) {
        const text = parameter;
        let unit = text.substring(text.length - 2).toLowerCase();
        let valueText = "";
        if (unit in exports2.unitToPixels) {
          valueText = text.substring(0, text.length - 2);
        } else {
          unit = "px";
          valueText = text;
        }
        const value = Number(valueText);
        (0, assert_js_1.assert)(!isNaN(value), "Failed to parse parameter value: " + text);
        pixels = value * exports2.unitToPixels[unit];
      } else {
        throw new Error("page.pdf() Cannot handle parameter type: " + typeof parameter);
      }
      return pixels / exports2.unitToPixels[lengthUnit];
    }
    function fromEmitterEvent(emitter, eventName) {
      return new rxjs_js_1.Observable((subscriber) => {
        const listener = (event) => {
          subscriber.next(event);
        };
        emitter.on(eventName, listener);
        return () => {
          emitter.off(eventName, listener);
        };
      });
    }
    function fromAbortSignal(signal, cause) {
      return signal ? (0, rxjs_js_1.fromEvent)(signal, "abort").pipe((0, rxjs_js_1.map)(() => {
        if (signal.reason instanceof Error) {
          signal.reason.cause = cause;
          throw signal.reason;
        }
        throw new Error(signal.reason, { cause });
      })) : rxjs_js_1.NEVER;
    }
    function filterAsync(predicate) {
      return (0, rxjs_js_1.mergeMap)((value) => {
        return (0, rxjs_js_1.from)(Promise.resolve(predicate(value))).pipe((0, rxjs_js_1.filter)((isMatch) => {
          return isMatch;
        }), (0, rxjs_js_1.map)(() => {
          return value;
        }));
      });
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/api/Browser.js
var require_Browser = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/api/Browser.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Browser = exports2.WEB_PERMISSION_TO_PROTOCOL_PERMISSION = void 0;
    var rxjs_js_1 = require_rxjs();
    var EventEmitter_js_1 = require_EventEmitter();
    var util_js_1 = require_util();
    var disposable_js_1 = require_disposable();
    exports2.WEB_PERMISSION_TO_PROTOCOL_PERMISSION = /* @__PURE__ */ new Map([
      ["accelerometer", "sensors"],
      ["ambient-light-sensor", "sensors"],
      ["background-sync", "backgroundSync"],
      ["camera", "videoCapture"],
      ["clipboard-read", "clipboardReadWrite"],
      ["clipboard-sanitized-write", "clipboardSanitizedWrite"],
      ["clipboard-write", "clipboardReadWrite"],
      ["geolocation", "geolocation"],
      ["gyroscope", "sensors"],
      ["idle-detection", "idleDetection"],
      ["keyboard-lock", "keyboardLock"],
      ["magnetometer", "sensors"],
      ["microphone", "audioCapture"],
      ["midi", "midi"],
      ["notifications", "notifications"],
      ["payment-handler", "paymentHandler"],
      ["persistent-storage", "durableStorage"],
      ["pointer-lock", "pointerLock"],
      // chrome-specific permissions we have.
      ["midi-sysex", "midiSysex"]
    ]);
    var Browser = class extends EventEmitter_js_1.EventEmitter {
      /**
       * @internal
       */
      constructor() {
        super();
      }
      /**
       * Waits until a {@link Target | target} matching the given `predicate`
       * appears and returns it.
       *
       * This will look all open {@link BrowserContext | browser contexts}.
       *
       * @example Finding a target for a page opened via `window.open`:
       *
       * ```ts
       * await page.evaluate(() => window.open('https://www.example.com/'));
       * const newWindowTarget = await browser.waitForTarget(
       *   target => target.url() === 'https://www.example.com/',
       * );
       * ```
       */
      async waitForTarget(predicate, options = {}) {
        const { timeout: ms = 3e4, signal } = options;
        return await (0, rxjs_js_1.firstValueFrom)((0, rxjs_js_1.merge)((0, util_js_1.fromEmitterEvent)(
          this,
          "targetcreated"
          /* BrowserEvent.TargetCreated */
        ), (0, util_js_1.fromEmitterEvent)(
          this,
          "targetchanged"
          /* BrowserEvent.TargetChanged */
        ), (0, rxjs_js_1.from)(this.targets())).pipe((0, util_js_1.filterAsync)(predicate), (0, rxjs_js_1.raceWith)((0, util_js_1.fromAbortSignal)(signal), (0, util_js_1.timeout)(ms))));
      }
      /**
       * Gets a list of all open {@link Page | pages} inside this {@link Browser}.
       *
       * If there are multiple {@link BrowserContext | browser contexts}, this
       * returns all {@link Page | pages} in all
       * {@link BrowserContext | browser contexts}.
       *
       * @param includeAll - experimental, setting to true includes all kinds of pages.
       *
       * @remarks Non-visible {@link Page | pages}, such as `"background_page"`,
       * will not be listed here. You can find them using {@link Target.page}.
       */
      async pages(includeAll = false) {
        const contextPages = await Promise.all(this.browserContexts().map((context) => {
          return context.pages(includeAll);
        }));
        return contextPages.reduce((acc, x) => {
          return acc.concat(x);
        }, []);
      }
      /**
       * Returns all cookies in the default {@link BrowserContext}.
       *
       * @remarks
       *
       * Shortcut for
       * {@link BrowserContext.cookies | browser.defaultBrowserContext().cookies()}.
       */
      async cookies() {
        return await this.defaultBrowserContext().cookies();
      }
      /**
       * Sets cookies in the default {@link BrowserContext}.
       *
       * @remarks
       *
       * Shortcut for
       * {@link BrowserContext.setCookie | browser.defaultBrowserContext().setCookie()}.
       */
      async setCookie(...cookies) {
        return await this.defaultBrowserContext().setCookie(...cookies);
      }
      /**
       * Removes cookies from the default {@link BrowserContext}.
       *
       * @remarks
       *
       * Shortcut for
       * {@link BrowserContext.deleteCookie | browser.defaultBrowserContext().deleteCookie()}.
       */
      async deleteCookie(...cookies) {
        return await this.defaultBrowserContext().deleteCookie(...cookies);
      }
      /**
       * Deletes cookies matching the provided filters from the default
       * {@link BrowserContext}.
       *
       * @remarks
       *
       * Shortcut for
       * {@link BrowserContext.deleteMatchingCookies |
       * browser.defaultBrowserContext().deleteMatchingCookies()}.
       */
      async deleteMatchingCookies(...filters) {
        return await this.defaultBrowserContext().deleteMatchingCookies(...filters);
      }
      /**
       * Sets the permission for a specific origin in the default
       * {@link BrowserContext}.
       *
       * @remarks
       *
       * Shortcut for
       * {@link BrowserContext.setPermission |
       * browser.defaultBrowserContext().setPermission()}.
       *
       * @param origin - The origin to set the permission for.
       * @param permission - The permission descriptor.
       * @param state - The state of the permission.
       *
       * @public
       */
      async setPermission(origin, ...permissions) {
        return await this.defaultBrowserContext().setPermission(origin, ...permissions);
      }
      /**
       * Whether Puppeteer is connected to this {@link Browser | browser}.
       *
       * @deprecated Use {@link Browser | Browser.connected}.
       */
      isConnected() {
        return this.connected;
      }
      /** @internal */
      [disposable_js_1.disposeSymbol]() {
        if (this.process()) {
          return void this.close().catch(util_js_1.debugError);
        }
        return void this.disconnect().catch(util_js_1.debugError);
      }
      /** @internal */
      [disposable_js_1.asyncDisposeSymbol]() {
        if (this.process()) {
          return this.close();
        }
        return this.disconnect();
      }
    };
    exports2.Browser = Browser;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/util/Deferred.js
var require_Deferred = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/util/Deferred.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Deferred = void 0;
    var Errors_js_1 = require_Errors();
    var Deferred = class _Deferred {
      static create(opts) {
        return new _Deferred(opts);
      }
      static async race(awaitables) {
        const deferredWithTimeout = /* @__PURE__ */ new Set();
        try {
          const promises = awaitables.map((value) => {
            if (value instanceof _Deferred) {
              if (value.#timeoutId) {
                deferredWithTimeout.add(value);
              }
              return value.valueOrThrow();
            }
            return value;
          });
          return await Promise.race(promises);
        } finally {
          for (const deferred of deferredWithTimeout) {
            deferred.reject(new Error("Timeout cleared"));
          }
        }
      }
      #isResolved = false;
      #isRejected = false;
      #value;
      // SAFETY: This is ensured by #taskPromise.
      #resolve;
      // TODO: Switch to Promise.withResolvers with Node 22
      #taskPromise = new Promise((resolve5) => {
        this.#resolve = resolve5;
      });
      #timeoutId;
      #timeoutError;
      constructor(opts) {
        if (opts && opts.timeout > 0) {
          this.#timeoutError = new Errors_js_1.TimeoutError(opts.message);
          this.#timeoutId = setTimeout(() => {
            this.reject(this.#timeoutError);
          }, opts.timeout);
        }
      }
      #finish(value) {
        clearTimeout(this.#timeoutId);
        this.#value = value;
        this.#resolve();
      }
      resolve(value) {
        if (this.#isRejected || this.#isResolved) {
          return;
        }
        this.#isResolved = true;
        this.#finish(value);
      }
      reject(error) {
        if (this.#isRejected || this.#isResolved) {
          return;
        }
        this.#isRejected = true;
        this.#finish(error);
      }
      resolved() {
        return this.#isResolved;
      }
      finished() {
        return this.#isResolved || this.#isRejected;
      }
      value() {
        return this.#value;
      }
      #promise;
      valueOrThrow() {
        if (!this.#promise) {
          this.#promise = (async () => {
            await this.#taskPromise;
            if (this.#isRejected) {
              throw this.#value;
            }
            return this.#value;
          })();
        }
        return this.#promise;
      }
    };
    exports2.Deferred = Deferred;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/util/Mutex.js
var require_Mutex = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/util/Mutex.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Mutex = void 0;
    var Deferred_js_1 = require_Deferred();
    var disposable_js_1 = require_disposable();
    var Mutex = class _Mutex {
      static Guard = class Guard {
        #mutex;
        #onRelease;
        constructor(mutex, onRelease) {
          this.#mutex = mutex;
          this.#onRelease = onRelease;
        }
        [disposable_js_1.disposeSymbol]() {
          this.#onRelease?.();
          return this.#mutex.release();
        }
      };
      #locked = false;
      #acquirers = [];
      // This is FIFO.
      async acquire(onRelease) {
        if (!this.#locked) {
          this.#locked = true;
          return new _Mutex.Guard(this);
        }
        const deferred = Deferred_js_1.Deferred.create();
        this.#acquirers.push(deferred.resolve.bind(deferred));
        await deferred.valueOrThrow();
        return new _Mutex.Guard(this, onRelease);
      }
      release() {
        const resolve5 = this.#acquirers.shift();
        if (!resolve5) {
          this.#locked = false;
          return;
        }
        resolve5();
      }
    };
    exports2.Mutex = Mutex;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/api/BrowserContext.js
var require_BrowserContext = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/api/BrowserContext.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BrowserContext = void 0;
    var rxjs_js_1 = require_rxjs();
    var EventEmitter_js_1 = require_EventEmitter();
    var util_js_1 = require_util();
    var disposable_js_1 = require_disposable();
    var Mutex_js_1 = require_Mutex();
    var BrowserContext = class extends EventEmitter_js_1.EventEmitter {
      /**
       * @internal
       */
      constructor() {
        super();
      }
      /**
       * If defined, indicates an ongoing screenshot opereation.
       */
      #pageScreenshotMutex;
      #screenshotOperationsCount = 0;
      /**
       * @internal
       */
      startScreenshot() {
        const mutex = this.#pageScreenshotMutex || new Mutex_js_1.Mutex();
        this.#pageScreenshotMutex = mutex;
        this.#screenshotOperationsCount++;
        return mutex.acquire(() => {
          this.#screenshotOperationsCount--;
          if (this.#screenshotOperationsCount === 0) {
            this.#pageScreenshotMutex = void 0;
          }
        });
      }
      /**
       * @internal
       */
      waitForScreenshotOperations() {
        return this.#pageScreenshotMutex?.acquire();
      }
      /**
       * Waits until a {@link Target | target} matching the given `predicate`
       * appears and returns it.
       *
       * This will look all open {@link BrowserContext | browser contexts}.
       *
       * @example Finding a target for a page opened via `window.open`:
       *
       * ```ts
       * await page.evaluate(() => window.open('https://www.example.com/'));
       * const newWindowTarget = await browserContext.waitForTarget(
       *   target => target.url() === 'https://www.example.com/',
       * );
       * ```
       */
      async waitForTarget(predicate, options = {}) {
        const { timeout: ms = 3e4 } = options;
        return await (0, rxjs_js_1.firstValueFrom)((0, rxjs_js_1.merge)((0, util_js_1.fromEmitterEvent)(
          this,
          "targetcreated"
          /* BrowserContextEvent.TargetCreated */
        ), (0, util_js_1.fromEmitterEvent)(
          this,
          "targetchanged"
          /* BrowserContextEvent.TargetChanged */
        ), (0, rxjs_js_1.from)(this.targets())).pipe((0, util_js_1.filterAsync)(predicate), (0, rxjs_js_1.raceWith)((0, util_js_1.timeout)(ms))));
      }
      /**
       * Removes cookie in this browser context.
       *
       * @param cookies - Complete {@link Cookie | cookie} object to be removed.
       */
      async deleteCookie(...cookies) {
        return await this.setCookie(...cookies.map((cookie) => {
          return {
            ...cookie,
            expires: 1
          };
        }));
      }
      /**
       * Deletes cookies matching the provided filters in this browser context.
       *
       * @param filters - {@link DeleteCookiesRequest}
       */
      async deleteMatchingCookies(...filters) {
        const cookies = await this.cookies();
        const cookiesToDelete = cookies.filter((cookie) => {
          return filters.some((filter) => {
            if (filter.name === cookie.name) {
              if (filter.domain !== void 0 && filter.domain === cookie.domain) {
                return true;
              }
              if (filter.path !== void 0 && filter.path === cookie.path) {
                return true;
              }
              if (filter.partitionKey !== void 0 && cookie.partitionKey !== void 0) {
                if (typeof cookie.partitionKey !== "object") {
                  throw new Error("Unexpected string partition key");
                }
                if (typeof filter.partitionKey === "string") {
                  if (filter.partitionKey === cookie.partitionKey?.sourceOrigin) {
                    return true;
                  }
                } else {
                  if (filter.partitionKey.sourceOrigin === cookie.partitionKey?.sourceOrigin) {
                    return true;
                  }
                }
              }
              if (filter.url !== void 0) {
                const url = new URL(filter.url);
                if (url.hostname === cookie.domain && url.pathname === cookie.path) {
                  return true;
                }
              }
              return true;
            }
            return false;
          });
        });
        await this.deleteCookie(...cookiesToDelete);
      }
      /**
       * Whether this {@link BrowserContext | browser context} is closed.
       */
      get closed() {
        return !this.browser().browserContexts().includes(this);
      }
      /**
       * Identifier for this {@link BrowserContext | browser context}.
       */
      get id() {
        return void 0;
      }
      /** @internal */
      [disposable_js_1.disposeSymbol]() {
        return void this.close().catch(util_js_1.debugError);
      }
      /** @internal */
      [disposable_js_1.asyncDisposeSymbol]() {
        return this.close();
      }
    };
    exports2.BrowserContext = BrowserContext;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/api/CDPSession.js
var require_CDPSession = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/api/CDPSession.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CDPSession = exports2.CDPSessionEvent = void 0;
    var EventEmitter_js_1 = require_EventEmitter();
    var CDPSessionEvent;
    (function(CDPSessionEvent2) {
      CDPSessionEvent2.Disconnected = /* @__PURE__ */ Symbol("CDPSession.Disconnected");
      CDPSessionEvent2.Swapped = /* @__PURE__ */ Symbol("CDPSession.Swapped");
      CDPSessionEvent2.Ready = /* @__PURE__ */ Symbol("CDPSession.Ready");
      CDPSessionEvent2.SessionAttached = "sessionattached";
      CDPSessionEvent2.SessionDetached = "sessiondetached";
    })(CDPSessionEvent || (exports2.CDPSessionEvent = CDPSessionEvent = {}));
    var CDPSession = class extends EventEmitter_js_1.EventEmitter {
      /**
       * @internal
       */
      constructor() {
        super();
      }
      /**
       * Parent session in terms of CDP's auto-attach mechanism.
       *
       * @internal
       */
      parentSession() {
        return void 0;
      }
    };
    exports2.CDPSession = CDPSession;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/api/DeviceRequestPrompt.js
var require_DeviceRequestPrompt = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/api/DeviceRequestPrompt.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DeviceRequestPrompt = void 0;
    var DeviceRequestPrompt = class {
      /**
       * Current list of selectable devices.
       */
      devices = [];
    };
    exports2.DeviceRequestPrompt = DeviceRequestPrompt;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/api/Dialog.js
var require_Dialog = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/api/Dialog.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Dialog = void 0;
    var assert_js_1 = require_assert();
    var Dialog = class {
      #type;
      #message;
      #defaultValue;
      /**
       * @internal
       */
      handled = false;
      /**
       * @internal
       */
      constructor(type, message, defaultValue = "") {
        this.#type = type;
        this.#message = message;
        this.#defaultValue = defaultValue;
      }
      /**
       * The type of the dialog.
       */
      type() {
        return this.#type;
      }
      /**
       * The message displayed in the dialog.
       */
      message() {
        return this.#message;
      }
      /**
       * The default value of the prompt, or an empty string if the dialog
       * is not a `prompt`.
       */
      defaultValue() {
        return this.#defaultValue;
      }
      /**
       * A promise that resolves when the dialog has been accepted.
       *
       * @param promptText - optional text that will be entered in the dialog
       * prompt. Has no effect if the dialog's type is not `prompt`.
       *
       */
      async accept(promptText) {
        (0, assert_js_1.assert)(!this.handled, "Cannot accept dialog which is already handled!");
        this.handled = true;
        await this.handle({
          accept: true,
          text: promptText
        });
      }
      /**
       * A promise which will resolve once the dialog has been dismissed
       */
      async dismiss() {
        (0, assert_js_1.assert)(!this.handled, "Cannot dismiss dialog which is already handled!");
        this.handled = true;
        await this.handle({
          accept: false
        });
      }
    };
    exports2.Dialog = Dialog;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/util/AsyncIterableUtil.js
var require_AsyncIterableUtil = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/util/AsyncIterableUtil.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AsyncIterableUtil = void 0;
    var AsyncIterableUtil = class {
      static async *map(iterable, map) {
        for await (const value of iterable) {
          yield await map(value);
        }
      }
      static async *flatMap(iterable, map) {
        for await (const value of iterable) {
          yield* map(value);
        }
      }
      static async collect(iterable) {
        const result = [];
        for await (const value of iterable) {
          result.push(value);
        }
        return result;
      }
      static async first(iterable) {
        for await (const value of iterable) {
          return value;
        }
        return;
      }
    };
    exports2.AsyncIterableUtil = AsyncIterableUtil;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/api/ElementHandleSymbol.js
var require_ElementHandleSymbol = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/api/ElementHandleSymbol.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2._isElementHandle = void 0;
    exports2._isElementHandle = /* @__PURE__ */ Symbol("_isElementHandle");
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/util/ErrorLike.js
var require_ErrorLike = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/util/ErrorLike.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isErrorLike = isErrorLike;
    exports2.isErrnoException = isErrnoException;
    exports2.rewriteError = rewriteError;
    exports2.createProtocolErrorMessage = createProtocolErrorMessage;
    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);
    }
    function rewriteError(error, message, originalMessage) {
      error.message = message;
      error.originalMessage = originalMessage ?? error.originalMessage;
      return error;
    }
    function createProtocolErrorMessage(object) {
      let message = object.error.message;
      if (object.error && typeof object.error === "object" && "data" in object.error) {
        message += ` ${object.error.data}`;
      }
      return message;
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/util/Function.js
var require_Function = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/util/Function.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.interpolateFunction = exports2.createFunction = void 0;
    exports2.stringifyFunction = stringifyFunction;
    var createdFunctions = /* @__PURE__ */ new Map();
    var createFunction = (functionValue) => {
      let fn = createdFunctions.get(functionValue);
      if (fn) {
        return fn;
      }
      fn = new Function(`return ${functionValue}`)();
      createdFunctions.set(functionValue, fn);
      return fn;
    };
    exports2.createFunction = createFunction;
    function stringifyFunction(fn) {
      let value = fn.toString();
      if (value.match(/^(async )*function(\(|\s)/) || value.match(/^(async )*function\s*\*\s*/)) {
        return value;
      }
      const isArrow = value.startsWith("(") || value.match(/^async\s*\(/) || value.match(/^(async)*\s*(?:[$_\p{ID_Start}])(?:[$\u200C\u200D\p{ID_Continue}])*\s*=>/u);
      if (isArrow) {
        return value;
      }
      let prefix = "function ";
      if (value.startsWith("async ")) {
        prefix = `async ${prefix}`;
        value = value.substring("async ".length);
      }
      return `${prefix}${value}`;
    }
    var interpolateFunction = (fn, replacements) => {
      let value = stringifyFunction(fn);
      for (const [name, jsValue] of Object.entries(replacements)) {
        value = value.replace(
          new RegExp(`PLACEHOLDER\\(\\s*(?:'${name}'|"${name}")\\s*\\)`, "g"),
          // Wrapping this ensures tersers that accidentally inline PLACEHOLDER calls
          // are still valid. Without, we may get calls like ()=>{...}() which is
          // not valid.
          `(${jsValue})`
        );
      }
      return (0, exports2.createFunction)(value);
    };
    exports2.interpolateFunction = interpolateFunction;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/HandleIterator.js
var require_HandleIterator = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/HandleIterator.js"(exports2) {
    "use strict";
    init_prefix();
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.transposeIterableHandle = transposeIterableHandle;
    var disposable_js_1 = require_disposable();
    var DEFAULT_BATCH_SIZE = 20;
    async function* fastTransposeIteratorHandle(iterator, size) {
      const env_1 = { stack: [], error: void 0, hasError: false };
      try {
        const array = __addDisposableResource2(env_1, await iterator.evaluateHandle(async (iterator2, size2) => {
          const results = [];
          while (results.length < size2) {
            const result = await iterator2.next();
            if (result.done) {
              break;
            }
            results.push(result.value);
          }
          return results;
        }, size), false);
        const properties = await array.getProperties();
        const handles = properties.values();
        const stack = __addDisposableResource2(env_1, new disposable_js_1.DisposableStack(), false);
        stack.defer(() => {
          for (const handle_1 of handles) {
            const env_2 = { stack: [], error: void 0, hasError: false };
            try {
              const handle = __addDisposableResource2(env_2, handle_1, false);
              handle[disposable_js_1.disposeSymbol]();
            } catch (e_2) {
              env_2.error = e_2;
              env_2.hasError = true;
            } finally {
              __disposeResources2(env_2);
            }
          }
        });
        yield* handles;
        return properties.size === 0;
      } catch (e_1) {
        env_1.error = e_1;
        env_1.hasError = true;
      } finally {
        __disposeResources2(env_1);
      }
    }
    async function* transposeIteratorHandle(iterator) {
      let size = DEFAULT_BATCH_SIZE;
      while (!(yield* fastTransposeIteratorHandle(iterator, size))) {
        size <<= 1;
      }
    }
    async function* transposeIterableHandle(handle) {
      const env_3 = { stack: [], error: void 0, hasError: false };
      try {
        const generatorHandle = __addDisposableResource2(env_3, await handle.evaluateHandle((iterable) => {
          return (async function* () {
            yield* iterable;
          })();
        }), false);
        yield* transposeIteratorHandle(generatorHandle);
      } catch (e_3) {
        env_3.error = e_3;
        env_3.hasError = true;
      } finally {
        __disposeResources2(env_3);
      }
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/LazyArg.js
var require_LazyArg = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/LazyArg.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LazyArg = void 0;
    var LazyArg = class _LazyArg {
      static create = (get) => {
        return new _LazyArg(get);
      };
      #get;
      constructor(get) {
        this.#get = get;
      }
      async get(context) {
        return await this.#get(context);
      }
    };
    exports2.LazyArg = LazyArg;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/QueryHandler.js
var require_QueryHandler = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/QueryHandler.js"(exports2) {
    "use strict";
    init_prefix();
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.QueryHandler = void 0;
    var ElementHandleSymbol_js_1 = require_ElementHandleSymbol();
    var ErrorLike_js_1 = require_ErrorLike();
    var Function_js_1 = require_Function();
    var Errors_js_1 = require_Errors();
    var HandleIterator_js_1 = require_HandleIterator();
    var LazyArg_js_1 = require_LazyArg();
    var QueryHandler = class {
      // Either one of these may be implemented, but at least one must be.
      static querySelectorAll;
      static querySelector;
      static get _querySelector() {
        if (this.querySelector) {
          return this.querySelector;
        }
        if (!this.querySelectorAll) {
          throw new Error("Cannot create default `querySelector`.");
        }
        return this.querySelector = (0, Function_js_1.interpolateFunction)(async (node, selector, PuppeteerUtil) => {
          const querySelectorAll = PLACEHOLDER("querySelectorAll");
          const results = querySelectorAll(node, selector, PuppeteerUtil);
          for await (const result of results) {
            return result;
          }
          return null;
        }, {
          querySelectorAll: (0, Function_js_1.stringifyFunction)(this.querySelectorAll)
        });
      }
      static get _querySelectorAll() {
        if (this.querySelectorAll) {
          return this.querySelectorAll;
        }
        if (!this.querySelector) {
          throw new Error("Cannot create default `querySelectorAll`.");
        }
        return this.querySelectorAll = (0, Function_js_1.interpolateFunction)(async function* (node, selector, PuppeteerUtil) {
          const querySelector = PLACEHOLDER("querySelector");
          const result = await querySelector(node, selector, PuppeteerUtil);
          if (result) {
            yield result;
          }
        }, {
          querySelector: (0, Function_js_1.stringifyFunction)(this.querySelector)
        });
      }
      /**
       * Queries for multiple nodes given a selector and {@link ElementHandle}.
       *
       * Akin to {@link https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll | Document.querySelectorAll()}.
       */
      static async *queryAll(element, selector) {
        const env_1 = { stack: [], error: void 0, hasError: false };
        try {
          const handle = __addDisposableResource2(env_1, await element.evaluateHandle(this._querySelectorAll, selector, LazyArg_js_1.LazyArg.create((context) => {
            return context.puppeteerUtil;
          })), false);
          yield* (0, HandleIterator_js_1.transposeIterableHandle)(handle);
        } catch (e_1) {
          env_1.error = e_1;
          env_1.hasError = true;
        } finally {
          __disposeResources2(env_1);
        }
      }
      /**
       * Queries for a single node given a selector and {@link ElementHandle}.
       *
       * Akin to {@link https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector}.
       */
      static async queryOne(element, selector) {
        const env_2 = { stack: [], error: void 0, hasError: false };
        try {
          const result = __addDisposableResource2(env_2, await element.evaluateHandle(this._querySelector, selector, LazyArg_js_1.LazyArg.create((context) => {
            return context.puppeteerUtil;
          })), false);
          if (!(ElementHandleSymbol_js_1._isElementHandle in result)) {
            return null;
          }
          return result.move();
        } catch (e_2) {
          env_2.error = e_2;
          env_2.hasError = true;
        } finally {
          __disposeResources2(env_2);
        }
      }
      /**
       * Waits until a single node appears for a given selector and
       * {@link ElementHandle}.
       *
       * This will always query the handle in the Puppeteer world and migrate the
       * result to the main world.
       */
      static async waitFor(elementOrFrame, selector, options) {
        const env_3 = { stack: [], error: void 0, hasError: false };
        try {
          let frame;
          const element = __addDisposableResource2(env_3, await (async () => {
            if (!(ElementHandleSymbol_js_1._isElementHandle in elementOrFrame)) {
              frame = elementOrFrame;
              return;
            }
            frame = elementOrFrame.frame;
            return await frame.isolatedRealm().adoptHandle(elementOrFrame);
          })(), false);
          const { visible = false, hidden = false, timeout, signal } = options;
          const polling = visible || hidden ? "raf" : options.polling;
          try {
            const env_4 = { stack: [], error: void 0, hasError: false };
            try {
              signal?.throwIfAborted();
              const handle = __addDisposableResource2(env_4, await frame.isolatedRealm().waitForFunction(async (PuppeteerUtil, query, selector2, root, visible2) => {
                const querySelector = PuppeteerUtil.createFunction(query);
                const node = await querySelector(root ?? document, selector2, PuppeteerUtil);
                return PuppeteerUtil.checkVisibility(node, visible2);
              }, {
                polling,
                root: element,
                timeout,
                signal
              }, LazyArg_js_1.LazyArg.create((context) => {
                return context.puppeteerUtil;
              }), (0, Function_js_1.stringifyFunction)(this._querySelector), selector, element, visible ? true : hidden ? false : void 0), false);
              if (signal?.aborted) {
                throw signal.reason;
              }
              if (!(ElementHandleSymbol_js_1._isElementHandle in handle)) {
                return null;
              }
              return await frame.mainRealm().transferHandle(handle);
            } catch (e_3) {
              env_4.error = e_3;
              env_4.hasError = true;
            } finally {
              __disposeResources2(env_4);
            }
          } catch (error) {
            if (!(0, ErrorLike_js_1.isErrorLike)(error)) {
              throw error;
            }
            if (error.name === "AbortError") {
              throw error;
            }
            const waitForSelectorError = new (error instanceof Errors_js_1.TimeoutError ? Errors_js_1.TimeoutError : Error)(`Waiting for selector \`${selector}\` failed`);
            waitForSelectorError.cause = error;
            throw waitForSelectorError;
          }
        } catch (e_4) {
          env_3.error = e_4;
          env_3.hasError = true;
        } finally {
          __disposeResources2(env_3);
        }
      }
    };
    exports2.QueryHandler = QueryHandler;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/AriaQueryHandler.js
var require_AriaQueryHandler = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/AriaQueryHandler.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ARIAQueryHandler = void 0;
    var assert_js_1 = require_assert();
    var AsyncIterableUtil_js_1 = require_AsyncIterableUtil();
    var QueryHandler_js_1 = require_QueryHandler();
    var isKnownAttribute = (attribute) => {
      return ["name", "role"].includes(attribute);
    };
    var ATTRIBUTE_REGEXP = /\[\s*(?<attribute>\w+)\s*=\s*(?<quote>"|')(?<value>\\.|.*?(?=\k<quote>))\k<quote>\s*\]/g;
    var parseARIASelector = (selector) => {
      if (selector.length > 1e4) {
        throw new Error(`Selector ${selector} is too long`);
      }
      const queryOptions = {};
      const defaultName = selector.replace(ATTRIBUTE_REGEXP, (_, attribute, __, value) => {
        (0, assert_js_1.assert)(isKnownAttribute(attribute), `Unknown aria attribute "${attribute}" in selector`);
        queryOptions[attribute] = value;
        return "";
      });
      if (defaultName && !queryOptions.name) {
        queryOptions.name = defaultName;
      }
      return queryOptions;
    };
    var ARIAQueryHandler = class extends QueryHandler_js_1.QueryHandler {
      static querySelector = async (node, selector, { ariaQuerySelector }) => {
        return await ariaQuerySelector(node, selector);
      };
      static async *queryAll(element, selector) {
        const { name, role } = parseARIASelector(selector);
        yield* element.queryAXTree(name, role);
      }
      static queryOne = async (element, selector) => {
        return await AsyncIterableUtil_js_1.AsyncIterableUtil.first(this.queryAll(element, selector)) ?? null;
      };
    };
    exports2.ARIAQueryHandler = ARIAQueryHandler;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/CSSQueryHandler.js
var require_CSSQueryHandler = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/CSSQueryHandler.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CSSQueryHandler = void 0;
    var QueryHandler_js_1 = require_QueryHandler();
    var CSSQueryHandler = class extends QueryHandler_js_1.QueryHandler {
      static querySelector = (element, selector, { cssQuerySelector }) => {
        return cssQuerySelector(element, selector);
      };
      static querySelectorAll = (element, selector, { cssQuerySelectorAll }) => {
        return cssQuerySelectorAll(element, selector);
      };
    };
    exports2.CSSQueryHandler = CSSQueryHandler;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/generated/injected.js
var require_injected = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/generated/injected.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.source = void 0;
    exports2.source = '"use strict";var g=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var B=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var l=(t,e)=>{for(var r in e)g(t,r,{get:e[r],enumerable:!0})},G=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of B(e))!Y.call(t,s)&&s!==r&&g(t,s,{get:()=>e[s],enumerable:!(o=X(e,s))||o.enumerable});return t};var J=t=>G(g({},"__esModule",{value:!0}),t);var pe={};l(pe,{default:()=>he});module.exports=J(pe);var N=class extends Error{constructor(e,r){super(e,r),this.name=this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}},p=class extends N{};var c=class t{static create(e){return new t(e)}static async race(e){let r=new Set;try{let o=e.map(s=>s instanceof t?(s.#s&&r.add(s),s.valueOrThrow()):s);return await Promise.race(o)}finally{for(let o of r)o.reject(new Error("Timeout cleared"))}}#e=!1;#r=!1;#o;#t;#a=new Promise(e=>{this.#t=e});#s;#i;constructor(e){e&&e.timeout>0&&(this.#i=new p(e.message),this.#s=setTimeout(()=>{this.reject(this.#i)},e.timeout))}#l(e){clearTimeout(this.#s),this.#o=e,this.#t()}resolve(e){this.#r||this.#e||(this.#e=!0,this.#l(e))}reject(e){this.#r||this.#e||(this.#r=!0,this.#l(e))}resolved(){return this.#e}finished(){return this.#e||this.#r}value(){return this.#o}#n;valueOrThrow(){return this.#n||(this.#n=(async()=>{if(await this.#a,this.#r)throw this.#o;return this.#o})()),this.#n}};var L=new Map,W=t=>{let e=L.get(t);return e||(e=new Function(`return ${t}`)(),L.set(t,e),e)};var b={};l(b,{ariaQuerySelector:()=>z,ariaQuerySelectorAll:()=>x});var z=(t,e)=>globalThis.__ariaQuerySelector(t,e),x=async function*(t,e){yield*await globalThis.__ariaQuerySelectorAll(t,e)};var E={};l(E,{cssQuerySelector:()=>K,cssQuerySelectorAll:()=>Z});var K=(t,e)=>t.querySelector(e),Z=function(t,e){return t.querySelectorAll(e)};var A={};l(A,{customQuerySelectors:()=>P});var v=class{#e=new Map;register(e,r){if(!r.queryOne&&r.queryAll){let o=r.queryAll;r.queryOne=(s,i)=>{for(let n of o(s,i))return n;return null}}else if(r.queryOne&&!r.queryAll){let o=r.queryOne;r.queryAll=(s,i)=>{let n=o(s,i);return n?[n]:[]}}else if(!r.queryOne||!r.queryAll)throw new Error("At least one query method must be defined.");this.#e.set(e,{querySelector:r.queryOne,querySelectorAll:r.queryAll})}unregister(e){this.#e.delete(e)}get(e){return this.#e.get(e)}clear(){this.#e.clear()}},P=new v;var R={};l(R,{pierceQuerySelector:()=>ee,pierceQuerySelectorAll:()=>te});var ee=(t,e)=>{let r=null,o=s=>{let i=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT);do{let n=i.currentNode;n.shadowRoot&&o(n.shadowRoot),!(n instanceof ShadowRoot)&&n!==s&&!r&&n.matches(e)&&(r=n)}while(!r&&i.nextNode())};return t instanceof Document&&(t=t.documentElement),o(t),r},te=(t,e)=>{let r=[],o=s=>{let i=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT);do{let n=i.currentNode;n.shadowRoot&&o(n.shadowRoot),!(n instanceof ShadowRoot)&&n!==s&&n.matches(e)&&r.push(n)}while(i.nextNode())};return t instanceof Document&&(t=t.documentElement),o(t),r};var u=(t,e)=>{if(!t)throw new Error(e)};var y=class{#e;#r;#o;#t;constructor(e,r){this.#e=e,this.#r=r}async start(){let e=this.#t=c.create(),r=await this.#e();if(r){e.resolve(r);return}this.#o=new MutationObserver(async()=>{let o=await this.#e();o&&(e.resolve(o),await this.stop())}),this.#o.observe(this.#r,{childList:!0,subtree:!0,attributes:!0})}async stop(){u(this.#t,"Polling never started."),this.#t.finished()||this.#t.reject(new Error("Polling stopped")),this.#o&&(this.#o.disconnect(),this.#o=void 0)}result(){return u(this.#t,"Polling never started."),this.#t.valueOrThrow()}},w=class{#e;#r;constructor(e){this.#e=e}async start(){let e=this.#r=c.create(),r=await this.#e();if(r){e.resolve(r);return}let o=async()=>{if(e.finished())return;let s=await this.#e();if(!s){window.requestAnimationFrame(o);return}e.resolve(s),await this.stop()};window.requestAnimationFrame(o)}async stop(){u(this.#r,"Polling never started."),this.#r.finished()||this.#r.reject(new Error("Polling stopped"))}result(){return u(this.#r,"Polling never started."),this.#r.valueOrThrow()}},T=class{#e;#r;#o;#t;constructor(e,r){this.#e=e,this.#r=r}async start(){let e=this.#t=c.create(),r=await this.#e();if(r){e.resolve(r);return}this.#o=setInterval(async()=>{let o=await this.#e();o&&(e.resolve(o),await this.stop())},this.#r)}async stop(){u(this.#t,"Polling never started."),this.#t.finished()||this.#t.reject(new Error("Polling stopped")),this.#o&&(clearInterval(this.#o),this.#o=void 0)}result(){return u(this.#t,"Polling never started."),this.#t.valueOrThrow()}};var _={};l(_,{PCombinator:()=>H,pQuerySelector:()=>fe,pQuerySelectorAll:()=>$});var a=class{static async*map(e,r){for await(let o of e)yield await r(o)}static async*flatMap(e,r){for await(let o of e)yield*r(o)}static async collect(e){let r=[];for await(let o of e)r.push(o);return r}static async first(e){for await(let r of e)return r}};var C={};l(C,{textQuerySelectorAll:()=>m});var re=new Set(["checkbox","image","radio"]),oe=t=>t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLInputElement&&!re.has(t.type),se=new Set(["SCRIPT","STYLE"]),f=t=>!se.has(t.nodeName)&&!document.head?.contains(t),I=new WeakMap,F=t=>{for(;t;)I.delete(t),t instanceof ShadowRoot?t=t.host:t=t.parentNode},j=new WeakSet,ne=new MutationObserver(t=>{for(let e of t)F(e.target)}),d=t=>{let e=I.get(t);if(e||(e={full:"",immediate:[]},!f(t)))return e;let r="";if(oe(t))e.full=t.value,e.immediate.push(t.value),t.addEventListener("input",o=>{F(o.target)},{once:!0,capture:!0});else{for(let o=t.firstChild;o;o=o.nextSibling){if(o.nodeType===Node.TEXT_NODE){e.full+=o.nodeValue??"",r+=o.nodeValue??"";continue}r&&e.immediate.push(r),r="",o.nodeType===Node.ELEMENT_NODE&&(e.full+=d(o).full)}r&&e.immediate.push(r),t instanceof Element&&t.shadowRoot&&(e.full+=d(t.shadowRoot).full),j.has(t)||(ne.observe(t,{childList:!0,characterData:!0,subtree:!0}),j.add(t))}return I.set(t,e),e};var m=function*(t,e){let r=!1;for(let o of t.childNodes)if(o instanceof Element&&f(o)){let s;o.shadowRoot?s=m(o.shadowRoot,e):s=m(o,e);for(let i of s)yield i,r=!0}r||t instanceof Element&&f(t)&&d(t).full.includes(e)&&(yield t)};var k={};l(k,{checkVisibility:()=>le,pierce:()=>S,pierceAll:()=>O});var ie=["hidden","collapse"],le=(t,e)=>{if(!t)return e===!1;if(e===void 0)return t;let r=t.nodeType===Node.TEXT_NODE?t.parentElement:t,o=window.getComputedStyle(r),s=o&&!ie.includes(o.visibility)&&!ae(r);return e===s?t:!1};function ae(t){let e=t.getBoundingClientRect();return e.width===0||e.height===0}var ce=t=>"shadowRoot"in t&&t.shadowRoot instanceof ShadowRoot;function*S(t){ce(t)?yield t.shadowRoot:yield t}function*O(t){t=S(t).next().value,yield t;let e=[document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT)];for(let r of e){let o;for(;o=r.nextNode();)o.shadowRoot&&(yield o.shadowRoot,e.push(document.createTreeWalker(o.shadowRoot,NodeFilter.SHOW_ELEMENT)))}}var D={};l(D,{xpathQuerySelectorAll:()=>q});var q=function*(t,e,r=-1){let s=(t.ownerDocument||document).evaluate(e,t,null,XPathResult.ORDERED_NODE_ITERATOR_TYPE),i=[],n;for(;(n=s.iterateNext())&&(i.push(n),!(r&&i.length===r)););for(let h=0;h<i.length;h++)n=i[h],yield n,i[h]=null};var ue=/[-\\w\\P{ASCII}*]/u,H=(r=>(r.Descendent=">>>",r.Child=">>>>",r))(H||{}),V=t=>"querySelectorAll"in t,Q=class{#e;#r=[];#o=void 0;elements;constructor(e,r){this.elements=[e],this.#e=r,this.#t()}async run(){for(typeof this.#o=="string"&&this.#o.trimStart()===":scope"&&this.#t();this.#o!==void 0;this.#t()){let e=this.#o;typeof e=="string"?e[0]&&ue.test(e[0])?this.elements=a.flatMap(this.elements,async function*(r){V(r)&&(yield*r.querySelectorAll(e))}):this.elements=a.flatMap(this.elements,async function*(r){if(!r.parentElement){if(!V(r))return;yield*r.querySelectorAll(e);return}let o=0;for(let s of r.parentElement.children)if(++o,s===r)break;yield*r.parentElement.querySelectorAll(`:scope>:nth-child(${o})${e}`)}):this.elements=a.flatMap(this.elements,async function*(r){switch(e.name){case"text":yield*m(r,e.value);break;case"xpath":yield*q(r,e.value);break;case"aria":yield*x(r,e.value);break;default:let o=P.get(e.name);if(!o)throw new Error(`Unknown selector type: ${e.name}`);yield*o.querySelectorAll(r,e.value)}})}}#t(){if(this.#r.length!==0){this.#o=this.#r.shift();return}if(this.#e.length===0){this.#o=void 0;return}let e=this.#e.shift();switch(e){case">>>>":{this.elements=a.flatMap(this.elements,S),this.#t();break}case">>>":{this.elements=a.flatMap(this.elements,O),this.#t();break}default:this.#r=e,this.#t();break}}},M=class{#e=new WeakMap;calculate(e,r=[]){if(e===null)return r;e instanceof ShadowRoot&&(e=e.host);let o=this.#e.get(e);if(o)return[...o,...r];let s=0;for(let n=e.previousSibling;n;n=n.previousSibling)++s;let i=this.calculate(e.parentNode,[s]);return this.#e.set(e,i),[...i,...r]}},U=(t,e)=>{if(t.length+e.length===0)return 0;let[r=-1,...o]=t,[s=-1,...i]=e;return r===s?U(o,i):r<s?-1:1},de=async function*(t){let e=new Set;for await(let o of t)e.add(o);let r=new M;yield*[...e.values()].map(o=>[o,r.calculate(o)]).sort(([,o],[,s])=>U(o,s)).map(([o])=>o)},$=function(t,e){let r=JSON.parse(e);if(r.some(o=>{let s=0;return o.some(i=>(typeof i=="string"?++s:s=0,s>1))}))throw new Error("Multiple deep combinators found in sequence.");return de(a.flatMap(r,o=>{let s=new Q(t,o);return s.run(),s.elements}))},fe=async function(t,e){for await(let r of $(t,e))return r;return null};var me=Object.freeze({...b,...A,...R,..._,...C,...k,...D,...E,Deferred:c,createFunction:W,createTextContent:d,IntervalPoller:T,isSuitableNodeForTextMatching:f,MutationPoller:y,RAFPoller:w}),he=me;\n';
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/ScriptInjector.js
var require_ScriptInjector = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/ScriptInjector.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.scriptInjector = exports2.ScriptInjector = void 0;
    var injected_js_1 = require_injected();
    var ScriptInjector = class {
      #updated = false;
      #amendments = /* @__PURE__ */ new Set();
      // Appends a statement of the form `(PuppeteerUtil) => {...}`.
      append(statement) {
        this.#update(() => {
          this.#amendments.add(statement);
        });
      }
      pop(statement) {
        this.#update(() => {
          this.#amendments.delete(statement);
        });
      }
      inject(inject, force = false) {
        if (this.#updated || force) {
          inject(this.#get());
        }
        this.#updated = false;
      }
      #update(callback) {
        callback();
        this.#updated = true;
      }
      #get() {
        return `(() => {
      const module = {};
      ${injected_js_1.source}
      ${[...this.#amendments].map((statement) => {
          return `(${statement})(module.exports.default);`;
        }).join("")}
      return module.exports.default;
    })()`;
      }
    };
    exports2.ScriptInjector = ScriptInjector;
    exports2.scriptInjector = new ScriptInjector();
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/CustomQueryHandler.js
var require_CustomQueryHandler = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/CustomQueryHandler.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.customQueryHandlers = exports2.CustomQueryHandlerRegistry = void 0;
    var assert_js_1 = require_assert();
    var Function_js_1 = require_Function();
    var QueryHandler_js_1 = require_QueryHandler();
    var ScriptInjector_js_1 = require_ScriptInjector();
    var CustomQueryHandlerRegistry = class {
      #handlers = /* @__PURE__ */ new Map();
      get(name) {
        const handler = this.#handlers.get(name);
        return handler ? handler[1] : void 0;
      }
      /**
       * Registers a {@link CustomQueryHandler | custom query handler}.
       *
       * @remarks
       * After registration, the handler can be used everywhere where a selector is
       * expected by prepending the selection string with `<name>/`. The name is
       * only allowed to consist of lower- and upper case latin letters.
       *
       * @example
       *
       * ```ts
       * Puppeteer.customQueryHandlers.register('lit', { … });
       * const aHandle = await page.$('lit/…');
       * ```
       *
       * @param name - Name to register under.
       * @param queryHandler - {@link CustomQueryHandler | Custom query handler} to
       * register.
       */
      register(name, handler) {
        (0, assert_js_1.assert)(!this.#handlers.has(name), `Cannot register over existing handler: ${name}`);
        (0, assert_js_1.assert)(/^[a-zA-Z]+$/.test(name), `Custom query handler names may only contain [a-zA-Z]`);
        (0, assert_js_1.assert)(handler.queryAll || handler.queryOne, `At least one query method must be implemented.`);
        const Handler = class extends QueryHandler_js_1.QueryHandler {
          static querySelectorAll = (0, Function_js_1.interpolateFunction)((node, selector, PuppeteerUtil) => {
            return PuppeteerUtil.customQuerySelectors.get(PLACEHOLDER("name")).querySelectorAll(node, selector);
          }, { name: JSON.stringify(name) });
          static querySelector = (0, Function_js_1.interpolateFunction)((node, selector, PuppeteerUtil) => {
            return PuppeteerUtil.customQuerySelectors.get(PLACEHOLDER("name")).querySelector(node, selector);
          }, { name: JSON.stringify(name) });
        };
        const registerScript = (0, Function_js_1.interpolateFunction)((PuppeteerUtil) => {
          PuppeteerUtil.customQuerySelectors.register(PLACEHOLDER("name"), {
            queryAll: PLACEHOLDER("queryAll"),
            queryOne: PLACEHOLDER("queryOne")
          });
        }, {
          name: JSON.stringify(name),
          queryAll: handler.queryAll ? (0, Function_js_1.stringifyFunction)(handler.queryAll) : String(void 0),
          queryOne: handler.queryOne ? (0, Function_js_1.stringifyFunction)(handler.queryOne) : String(void 0)
        }).toString();
        this.#handlers.set(name, [registerScript, Handler]);
        ScriptInjector_js_1.scriptInjector.append(registerScript);
      }
      /**
       * Unregisters the {@link CustomQueryHandler | custom query handler} for the
       * given name.
       *
       * @throws `Error` if there is no handler under the given name.
       */
      unregister(name) {
        const handler = this.#handlers.get(name);
        if (!handler) {
          throw new Error(`Cannot unregister unknown handler: ${name}`);
        }
        ScriptInjector_js_1.scriptInjector.pop(handler[0]);
        this.#handlers.delete(name);
      }
      /**
       * Gets the names of all {@link CustomQueryHandler | custom query handlers}.
       */
      names() {
        return [...this.#handlers.keys()];
      }
      /**
       * Unregisters all custom query handlers.
       */
      clear() {
        for (const [registerScript] of this.#handlers) {
          ScriptInjector_js_1.scriptInjector.pop(registerScript);
        }
        this.#handlers.clear();
      }
    };
    exports2.CustomQueryHandlerRegistry = CustomQueryHandlerRegistry;
    exports2.customQueryHandlers = new CustomQueryHandlerRegistry();
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/PierceQueryHandler.js
var require_PierceQueryHandler = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/PierceQueryHandler.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PierceQueryHandler = void 0;
    var QueryHandler_js_1 = require_QueryHandler();
    var PierceQueryHandler = class extends QueryHandler_js_1.QueryHandler {
      static querySelector = (element, selector, { pierceQuerySelector }) => {
        return pierceQuerySelector(element, selector);
      };
      static querySelectorAll = (element, selector, { pierceQuerySelectorAll }) => {
        return pierceQuerySelectorAll(element, selector);
      };
    };
    exports2.PierceQueryHandler = PierceQueryHandler;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/PQueryHandler.js
var require_PQueryHandler = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/PQueryHandler.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PQueryHandler = void 0;
    var QueryHandler_js_1 = require_QueryHandler();
    var PQueryHandler = class extends QueryHandler_js_1.QueryHandler {
      static querySelectorAll = (element, selector, { pQuerySelectorAll }) => {
        return pQuerySelectorAll(element, selector);
      };
      static querySelector = (element, selector, { pQuerySelector }) => {
        return pQuerySelector(element, selector);
      };
    };
    exports2.PQueryHandler = PQueryHandler;
  }
});

// node_modules/puppeteer-core/lib/cjs/third_party/parsel-js/parsel-js.js
var require_parsel_js = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/third_party/parsel-js/parsel-js.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var __defProp2 = Object.defineProperty;
    var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames2 = Object.getOwnPropertyNames;
    var __hasOwnProp2 = Object.prototype.hasOwnProperty;
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp2(target, name, { get: all[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 __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
    var parsel_js_exports = {};
    __export2(parsel_js_exports, {
      TOKENS: () => TOKENS,
      stringify: () => stringify,
      tokenize: () => tokenize
    });
    module2.exports = __toCommonJS2(parsel_js_exports);
    var TOKENS = {
      attribute: /\[\s*(?:(?<namespace>\*|[-\w\P{ASCII}]*)\|)?(?<name>[-\w\P{ASCII}]+)\s*(?:(?<operator>\W?=)\s*(?<value>.+?)\s*(\s(?<caseSensitive>[iIsS]))?\s*)?\]/gu,
      id: /#(?<name>[-\w\P{ASCII}]+)/gu,
      class: /\.(?<name>[-\w\P{ASCII}]+)/gu,
      comma: /\s*,\s*/g,
      combinator: /\s*[\s>+~]\s*/g,
      "pseudo-element": /::(?<name>[-\w\P{ASCII}]+)(?:\((?<argument>¶*)\))?/gu,
      "pseudo-class": /:(?<name>[-\w\P{ASCII}]+)(?:\((?<argument>¶*)\))?/gu,
      universal: /(?:(?<namespace>\*|[-\w\P{ASCII}]*)\|)?\*/gu,
      type: /(?:(?<namespace>\*|[-\w\P{ASCII}]*)\|)?(?<name>[-\w\P{ASCII}]+)/gu
      // this must be last
    };
    var TRIM_TOKENS = /* @__PURE__ */ new Set(["combinator", "comma"]);
    var getArgumentPatternByType = (type) => {
      switch (type) {
        case "pseudo-element":
        case "pseudo-class":
          return new RegExp(TOKENS[type].source.replace("(?<argument>\xB6*)", "(?<argument>.*)"), "gu");
        default:
          return TOKENS[type];
      }
    };
    function gobbleParens(text, offset) {
      let nesting = 0;
      let result = "";
      for (; offset < text.length; offset++) {
        const char = text[offset];
        switch (char) {
          case "(":
            ++nesting;
            break;
          case ")":
            --nesting;
            break;
        }
        result += char;
        if (nesting === 0) {
          return result;
        }
      }
      return result;
    }
    function tokenizeBy(text, grammar = TOKENS) {
      if (!text) {
        return [];
      }
      const tokens = [text];
      for (const [type, pattern] of Object.entries(grammar)) {
        for (let i = 0; i < tokens.length; i++) {
          const token = tokens[i];
          if (typeof token !== "string") {
            continue;
          }
          pattern.lastIndex = 0;
          const match = pattern.exec(token);
          if (!match) {
            continue;
          }
          const from = match.index - 1;
          const args2 = [];
          const content = match[0];
          const before = token.slice(0, from + 1);
          if (before) {
            args2.push(before);
          }
          args2.push({
            ...match.groups,
            type,
            content
          });
          const after = token.slice(from + content.length + 1);
          if (after) {
            args2.push(after);
          }
          tokens.splice(i, 1, ...args2);
        }
      }
      let offset = 0;
      for (const token of tokens) {
        switch (typeof token) {
          case "string":
            throw new Error(`Unexpected sequence ${token} found at index ${offset}`);
          case "object":
            offset += token.content.length;
            token.pos = [offset - token.content.length, offset];
            if (TRIM_TOKENS.has(token.type)) {
              token.content = token.content.trim() || " ";
            }
            break;
        }
      }
      return tokens;
    }
    var STRING_PATTERN = /(['"])([^\\\n]*?)\1/g;
    var ESCAPE_PATTERN = /\\./g;
    function tokenize(selector, grammar = TOKENS) {
      selector = selector.trim();
      if (selector === "") {
        return [];
      }
      const replacements = [];
      selector = selector.replace(ESCAPE_PATTERN, (value, offset) => {
        replacements.push({ value, offset });
        return "\uE000".repeat(value.length);
      });
      selector = selector.replace(STRING_PATTERN, (value, quote, content, offset) => {
        replacements.push({ value, offset });
        return `${quote}${"\uE001".repeat(content.length)}${quote}`;
      });
      {
        let pos = 0;
        let offset;
        while ((offset = selector.indexOf("(", pos)) > -1) {
          const value = gobbleParens(selector, offset);
          replacements.push({ value, offset });
          selector = `${selector.substring(0, offset)}(${"\xB6".repeat(value.length - 2)})${selector.substring(offset + value.length)}`;
          pos = offset + value.length;
        }
      }
      const tokens = tokenizeBy(selector, grammar);
      const changedTokens = /* @__PURE__ */ new Set();
      for (const replacement of replacements.reverse()) {
        for (const token of tokens) {
          const { offset, value } = replacement;
          if (!(token.pos[0] <= offset && offset + value.length <= token.pos[1])) {
            continue;
          }
          const { content } = token;
          const tokenOffset = offset - token.pos[0];
          token.content = content.slice(0, tokenOffset) + value + content.slice(tokenOffset + value.length);
          if (token.content !== content) {
            changedTokens.add(token);
          }
        }
      }
      for (const token of changedTokens) {
        const pattern = getArgumentPatternByType(token.type);
        if (!pattern) {
          throw new Error(`Unknown token type: ${token.type}`);
        }
        pattern.lastIndex = 0;
        const match = pattern.exec(token.content);
        if (!match) {
          throw new Error(`Unable to parse content for ${token.type}: ${token.content}`);
        }
        Object.assign(token, match.groups);
      }
      return tokens;
    }
    function stringify(listOrNode) {
      if (Array.isArray(listOrNode)) {
        return listOrNode.map((token) => token.content).join("");
      }
      switch (listOrNode.type) {
        case "list":
          return listOrNode.list.map(stringify).join(",");
        case "relative":
          return listOrNode.combinator + stringify(listOrNode.right);
        case "complex":
          return stringify(listOrNode.left) + listOrNode.combinator + stringify(listOrNode.right);
        case "compound":
          return listOrNode.list.map(stringify).join("");
        default:
          return listOrNode.content;
      }
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/PSelectorParser.js
var require_PSelectorParser = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/PSelectorParser.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.parsePSelectors = parsePSelectors;
    var parsel_js_js_1 = require_parsel_js();
    parsel_js_js_1.TOKENS["nesting"] = /&/g;
    parsel_js_js_1.TOKENS["combinator"] = /\s*(>>>>?|[\s>+~])\s*/g;
    var ESCAPE_REGEXP = /\\[\s\S]/g;
    var unquote = (text) => {
      if (text.length <= 1) {
        return text;
      }
      if ((text[0] === '"' || text[0] === "'") && text.endsWith(text[0])) {
        text = text.slice(1, -1);
      }
      return text.replace(ESCAPE_REGEXP, (match) => {
        return match[1];
      });
    };
    function parsePSelectors(selector) {
      let isPureCSS = true;
      let hasAria = false;
      let hasPseudoClasses = false;
      const tokens = (0, parsel_js_js_1.tokenize)(selector);
      if (tokens.length === 0) {
        return [[], isPureCSS, hasPseudoClasses, false];
      }
      let compoundSelector = [];
      let complexSelector = [compoundSelector];
      const selectors = [complexSelector];
      const storage = [];
      for (const token of tokens) {
        switch (token.type) {
          case "combinator":
            switch (token.content) {
              case ">>>":
                isPureCSS = false;
                if (storage.length) {
                  compoundSelector.push((0, parsel_js_js_1.stringify)(storage));
                  storage.splice(0);
                }
                compoundSelector = [];
                complexSelector.push(
                  ">>>"
                  /* PCombinator.Descendent */
                );
                complexSelector.push(compoundSelector);
                continue;
              case ">>>>":
                isPureCSS = false;
                if (storage.length) {
                  compoundSelector.push((0, parsel_js_js_1.stringify)(storage));
                  storage.splice(0);
                }
                compoundSelector = [];
                complexSelector.push(
                  ">>>>"
                  /* PCombinator.Child */
                );
                complexSelector.push(compoundSelector);
                continue;
            }
            break;
          case "pseudo-element":
            if (!token.name.startsWith("-p-")) {
              break;
            }
            isPureCSS = false;
            if (storage.length) {
              compoundSelector.push((0, parsel_js_js_1.stringify)(storage));
              storage.splice(0);
            }
            const name = token.name.slice(3);
            if (name === "aria") {
              hasAria = true;
            }
            compoundSelector.push({
              name,
              value: unquote(token.argument ?? "")
            });
            continue;
          case "pseudo-class":
            hasPseudoClasses = true;
            break;
          case "comma":
            if (storage.length) {
              compoundSelector.push((0, parsel_js_js_1.stringify)(storage));
              storage.splice(0);
            }
            compoundSelector = [];
            complexSelector = [compoundSelector];
            selectors.push(complexSelector);
            continue;
        }
        storage.push(token);
      }
      if (storage.length) {
        compoundSelector.push((0, parsel_js_js_1.stringify)(storage));
      }
      return [selectors, isPureCSS, hasPseudoClasses, hasAria];
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/TextQueryHandler.js
var require_TextQueryHandler = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/TextQueryHandler.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.TextQueryHandler = void 0;
    var QueryHandler_js_1 = require_QueryHandler();
    var TextQueryHandler = class extends QueryHandler_js_1.QueryHandler {
      static querySelectorAll = (element, selector, { textQuerySelectorAll }) => {
        return textQuerySelectorAll(element, selector);
      };
    };
    exports2.TextQueryHandler = TextQueryHandler;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/XPathQueryHandler.js
var require_XPathQueryHandler = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/XPathQueryHandler.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.XPathQueryHandler = void 0;
    var QueryHandler_js_1 = require_QueryHandler();
    var XPathQueryHandler = class extends QueryHandler_js_1.QueryHandler {
      static querySelectorAll = (element, selector, { xpathQuerySelectorAll }) => {
        return xpathQuerySelectorAll(element, selector);
      };
      static querySelector = (element, selector, { xpathQuerySelectorAll }) => {
        for (const result of xpathQuerySelectorAll(element, selector, 1)) {
          return result;
        }
        return null;
      };
    };
    exports2.XPathQueryHandler = XPathQueryHandler;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/GetQueryHandler.js
var require_GetQueryHandler = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/GetQueryHandler.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getQueryHandlerAndSelector = getQueryHandlerAndSelector;
    var AriaQueryHandler_js_1 = require_AriaQueryHandler();
    var CSSQueryHandler_js_1 = require_CSSQueryHandler();
    var CustomQueryHandler_js_1 = require_CustomQueryHandler();
    var PierceQueryHandler_js_1 = require_PierceQueryHandler();
    var PQueryHandler_js_1 = require_PQueryHandler();
    var PSelectorParser_js_1 = require_PSelectorParser();
    var TextQueryHandler_js_1 = require_TextQueryHandler();
    var XPathQueryHandler_js_1 = require_XPathQueryHandler();
    var BUILTIN_QUERY_HANDLERS = {
      aria: AriaQueryHandler_js_1.ARIAQueryHandler,
      pierce: PierceQueryHandler_js_1.PierceQueryHandler,
      xpath: XPathQueryHandler_js_1.XPathQueryHandler,
      text: TextQueryHandler_js_1.TextQueryHandler
    };
    var QUERY_SEPARATORS = ["=", "/"];
    function getQueryHandlerAndSelector(selector) {
      for (const handlerMap of [
        CustomQueryHandler_js_1.customQueryHandlers.names().map((name) => {
          return [name, CustomQueryHandler_js_1.customQueryHandlers.get(name)];
        }),
        Object.entries(BUILTIN_QUERY_HANDLERS)
      ]) {
        for (const [name, QueryHandler] of handlerMap) {
          for (const separator of QUERY_SEPARATORS) {
            const prefix = `${name}${separator}`;
            if (selector.startsWith(prefix)) {
              selector = selector.slice(prefix.length);
              return {
                updatedSelector: selector,
                polling: name === "aria" ? "raf" : "mutation",
                QueryHandler
              };
            }
          }
        }
      }
      try {
        const [pSelector, isPureCSS, hasPseudoClasses, hasAria] = (0, PSelectorParser_js_1.parsePSelectors)(selector);
        if (isPureCSS) {
          return {
            updatedSelector: selector,
            polling: hasPseudoClasses ? "raf" : "mutation",
            QueryHandler: CSSQueryHandler_js_1.CSSQueryHandler
          };
        }
        return {
          updatedSelector: JSON.stringify(pSelector),
          polling: hasAria ? "raf" : "mutation",
          QueryHandler: PQueryHandler_js_1.PQueryHandler
        };
      } catch {
        return {
          updatedSelector: selector,
          polling: "mutation",
          QueryHandler: CSSQueryHandler_js_1.CSSQueryHandler
        };
      }
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/util/decorators.js
var require_decorators = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/util/decorators.js"(exports2) {
    "use strict";
    init_prefix();
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.moveable = moveable;
    exports2.throwIfDisposed = throwIfDisposed;
    exports2.inertIfDisposed = inertIfDisposed;
    exports2.invokeAtMostOnceForArguments = invokeAtMostOnceForArguments;
    exports2.guarded = guarded;
    exports2.bubble = bubble;
    var disposable_js_1 = require_disposable();
    var Mutex_js_1 = require_Mutex();
    var instances = /* @__PURE__ */ new WeakSet();
    function moveable(Class, _) {
      let hasDispose = false;
      if (Class.prototype[disposable_js_1.disposeSymbol]) {
        const dispose = Class.prototype[disposable_js_1.disposeSymbol];
        Class.prototype[disposable_js_1.disposeSymbol] = function() {
          if (instances.has(this)) {
            instances.delete(this);
            return;
          }
          return dispose.call(this);
        };
        hasDispose = true;
      }
      if (Class.prototype[disposable_js_1.asyncDisposeSymbol]) {
        const asyncDispose = Class.prototype[disposable_js_1.asyncDisposeSymbol];
        Class.prototype[disposable_js_1.asyncDisposeSymbol] = function() {
          if (instances.has(this)) {
            instances.delete(this);
            return;
          }
          return asyncDispose.call(this);
        };
        hasDispose = true;
      }
      if (hasDispose) {
        Class.prototype.move = function() {
          instances.add(this);
          return this;
        };
      }
      return Class;
    }
    function throwIfDisposed(message = (value) => {
      return `Attempted to use disposed ${value.constructor.name}.`;
    }) {
      return (target, _) => {
        return function(...args2) {
          if (this.disposed) {
            throw new Error(message(this));
          }
          return target.call(this, ...args2);
        };
      };
    }
    function inertIfDisposed(target, _) {
      return function(...args2) {
        if (this.disposed) {
          return;
        }
        return target.call(this, ...args2);
      };
    }
    function invokeAtMostOnceForArguments(target, _) {
      const cache = /* @__PURE__ */ new WeakMap();
      let cacheDepth = -1;
      return function(...args2) {
        if (cacheDepth === -1) {
          cacheDepth = args2.length;
        }
        if (cacheDepth !== args2.length) {
          throw new Error("Memoized method was called with the wrong number of arguments");
        }
        let freshArguments = false;
        let cacheIterator = cache;
        for (const arg of args2) {
          if (cacheIterator.has(arg)) {
            cacheIterator = cacheIterator.get(arg);
          } else {
            freshArguments = true;
            cacheIterator.set(arg, /* @__PURE__ */ new WeakMap());
            cacheIterator = cacheIterator.get(arg);
          }
        }
        if (!freshArguments) {
          return;
        }
        return target.call(this, ...args2);
      };
    }
    function guarded(getKey = function() {
      return this;
    }) {
      return (target, _) => {
        const mutexes = /* @__PURE__ */ new WeakMap();
        return async function(...args2) {
          const env_1 = { stack: [], error: void 0, hasError: false };
          try {
            const key = getKey.call(this);
            let mutex = mutexes.get(key);
            if (!mutex) {
              mutex = new Mutex_js_1.Mutex();
              mutexes.set(key, mutex);
            }
            const _2 = __addDisposableResource2(env_1, await mutex.acquire(), true);
            return await target.call(this, ...args2);
          } catch (e_1) {
            env_1.error = e_1;
            env_1.hasError = true;
          } finally {
            const result_1 = __disposeResources2(env_1);
            if (result_1)
              await result_1;
          }
        };
      };
    }
    var bubbleHandlers = /* @__PURE__ */ new WeakMap();
    var bubbleInitializer = function(events) {
      const handlers = bubbleHandlers.get(this) ?? /* @__PURE__ */ new Map();
      if (handlers.has(events)) {
        return;
      }
      const handler = events !== void 0 ? (type, event) => {
        if (events.includes(type)) {
          this.emit(type, event);
        }
      } : (type, event) => {
        this.emit(type, event);
      };
      handlers.set(events, handler);
      bubbleHandlers.set(this, handlers);
    };
    function bubble(events) {
      return ({ set, get }, context) => {
        context.addInitializer(function() {
          return bubbleInitializer.apply(this, [events]);
        });
        return {
          set(emitter) {
            const handler = bubbleHandlers.get(this).get(events);
            const oldEmitter = get.call(this);
            if (oldEmitter !== void 0) {
              oldEmitter.off("*", handler);
            }
            if (emitter === void 0) {
              return;
            }
            emitter.on("*", handler);
            set.call(this, emitter);
          },
          init(emitter) {
            if (emitter === void 0) {
              return emitter;
            }
            bubbleInitializer.apply(this, [events]);
            const handler = bubbleHandlers.get(this).get(events);
            emitter.on("*", handler);
            return emitter;
          }
        };
      };
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/api/JSHandle.js
var require_JSHandle = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/api/JSHandle.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.JSHandle = void 0;
    var util_js_1 = require_util();
    var decorators_js_1 = require_decorators();
    var disposable_js_1 = require_disposable();
    var JSHandle = (() => {
      let _classDecorators = [decorators_js_1.moveable];
      let _classDescriptor;
      let _classExtraInitializers = [];
      let _classThis;
      let _instanceExtraInitializers = [];
      let _getProperty_decorators;
      let _getProperties_decorators;
      var JSHandle2 = class {
        static {
          _classThis = this;
        }
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? /* @__PURE__ */ Object.create(null) : void 0;
          __esDecorate2(this, null, _getProperty_decorators, { kind: "method", name: "getProperty", static: false, private: false, access: { has: (obj) => "getProperty" in obj, get: (obj) => obj.getProperty }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _getProperties_decorators, { kind: "method", name: "getProperties", static: false, private: false, access: { has: (obj) => "getProperties" in obj, get: (obj) => obj.getProperties }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
          JSHandle2 = _classThis = _classDescriptor.value;
          if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
          __runInitializers2(_classThis, _classExtraInitializers);
        }
        /**
         * @internal
         */
        constructor() {
          __runInitializers2(this, _instanceExtraInitializers);
        }
        /**
         * Evaluates the given function with the current handle as its first argument.
         */
        async evaluate(pageFunction, ...args2) {
          pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.evaluate.name, pageFunction);
          return await this.realm.evaluate(pageFunction, this, ...args2);
        }
        /**
         * Evaluates the given function with the current handle as its first argument.
         *
         */
        async evaluateHandle(pageFunction, ...args2) {
          pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.evaluateHandle.name, pageFunction);
          return await this.realm.evaluateHandle(pageFunction, this, ...args2);
        }
        /**
         * @internal
         */
        async getProperty(propertyName) {
          return await this.evaluateHandle((object, propertyName2) => {
            return object[propertyName2];
          }, propertyName);
        }
        /**
         * Gets a map of handles representing the properties of the current handle.
         *
         * @example
         *
         * ```ts
         * const listHandle = await page.evaluateHandle(() => document.body.children);
         * const properties = await listHandle.getProperties();
         * const children = [];
         * for (const property of properties.values()) {
         *   const element = property.asElement();
         *   if (element) {
         *     children.push(element);
         *   }
         * }
         * children; // holds elementHandles to all children of document.body
         * ```
         */
        async getProperties() {
          const propertyNames = await this.evaluate((object) => {
            const enumerableProperties = [];
            const descriptors = Object.getOwnPropertyDescriptors(object);
            for (const propertyName in descriptors) {
              if (descriptors[propertyName]?.enumerable) {
                enumerableProperties.push(propertyName);
              }
            }
            return enumerableProperties;
          });
          const map = /* @__PURE__ */ new Map();
          const results = await Promise.all(propertyNames.map((key) => {
            return this.getProperty(key);
          }));
          for (const [key, value] of Object.entries(propertyNames)) {
            const env_1 = { stack: [], error: void 0, hasError: false };
            try {
              const handle = __addDisposableResource2(env_1, results[key], false);
              if (handle) {
                map.set(value, handle.move());
              }
            } catch (e_1) {
              env_1.error = e_1;
              env_1.hasError = true;
            } finally {
              __disposeResources2(env_1);
            }
          }
          return map;
        }
        /** @internal */
        [(_getProperty_decorators = [(0, decorators_js_1.throwIfDisposed)()], _getProperties_decorators = [(0, decorators_js_1.throwIfDisposed)()], disposable_js_1.disposeSymbol)]() {
          return void this.dispose().catch(util_js_1.debugError);
        }
        /** @internal */
        [disposable_js_1.asyncDisposeSymbol]() {
          return this.dispose();
        }
      };
      return JSHandle2 = _classThis;
    })();
    exports2.JSHandle = JSHandle;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/api/locators/locators.js
var require_locators = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/api/locators/locators.js"(exports2) {
    "use strict";
    init_prefix();
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RETRY_DELAY = exports2.RaceLocator = exports2.NodeLocator = exports2.MappedLocator = exports2.FilteredLocator = exports2.DelegatedLocator = exports2.FunctionLocator = exports2.Locator = exports2.LocatorEvent = void 0;
    var rxjs_js_1 = require_rxjs();
    var EventEmitter_js_1 = require_EventEmitter();
    var util_js_1 = require_util();
    var LocatorEvent;
    (function(LocatorEvent2) {
      LocatorEvent2["Action"] = "action";
    })(LocatorEvent || (exports2.LocatorEvent = LocatorEvent = {}));
    var Locator = class extends EventEmitter_js_1.EventEmitter {
      /**
       * Creates a race between multiple locators trying to locate elements in
       * parallel but ensures that only a single element receives the action.
       *
       * @public
       */
      static race(locators) {
        return RaceLocator.create(locators);
      }
      /**
       * @internal
       */
      visibility = null;
      /**
       * @internal
       */
      _timeout = 3e4;
      #ensureElementIsInTheViewport = true;
      #waitForEnabled = true;
      #waitForStableBoundingBox = true;
      /**
       * @internal
       */
      operators = {
        conditions: (conditions, signal) => {
          return (0, rxjs_js_1.mergeMap)((handle) => {
            return (0, rxjs_js_1.merge)(...conditions.map((condition) => {
              return condition(handle, signal);
            })).pipe((0, rxjs_js_1.defaultIfEmpty)(handle));
          });
        },
        retryAndRaceWithSignalAndTimer: (signal, cause) => {
          const candidates = [];
          if (signal) {
            candidates.push((0, util_js_1.fromAbortSignal)(signal, cause));
          }
          candidates.push((0, util_js_1.timeout)(this._timeout, cause));
          return (0, rxjs_js_1.pipe)((0, rxjs_js_1.retry)({ delay: exports2.RETRY_DELAY }), (0, rxjs_js_1.raceWith)(...candidates));
        }
      };
      // Determines when the locator will timeout for actions.
      get timeout() {
        return this._timeout;
      }
      /**
       * Creates a new locator instance by cloning the current locator and setting
       * the total timeout for the locator actions.
       *
       * Pass `0` to disable timeout.
       *
       * @defaultValue `Page.getDefaultTimeout()`
       */
      setTimeout(timeout) {
        const locator = this._clone();
        locator._timeout = timeout;
        return locator;
      }
      /**
       * Creates a new locator instance by cloning the current locator with the
       * visibility property changed to the specified value.
       */
      setVisibility(visibility) {
        const locator = this._clone();
        locator.visibility = visibility;
        return locator;
      }
      /**
       * Creates a new locator instance by cloning the current locator and
       * specifying whether to wait for input elements to become enabled before the
       * action. Applicable to `click` and `fill` actions.
       *
       * @defaultValue `true`
       */
      setWaitForEnabled(value) {
        const locator = this._clone();
        locator.#waitForEnabled = value;
        return locator;
      }
      /**
       * Creates a new locator instance by cloning the current locator and
       * specifying whether the locator should scroll the element into viewport if
       * it is not in the viewport already.
       *
       * @defaultValue `true`
       */
      setEnsureElementIsInTheViewport(value) {
        const locator = this._clone();
        locator.#ensureElementIsInTheViewport = value;
        return locator;
      }
      /**
       * Creates a new locator instance by cloning the current locator and
       * specifying whether the locator has to wait for the element's bounding box
       * to be same between two consecutive animation frames.
       *
       * @defaultValue `true`
       */
      setWaitForStableBoundingBox(value) {
        const locator = this._clone();
        locator.#waitForStableBoundingBox = value;
        return locator;
      }
      /**
       * @internal
       */
      copyOptions(locator) {
        this._timeout = locator._timeout;
        this.visibility = locator.visibility;
        this.#waitForEnabled = locator.#waitForEnabled;
        this.#ensureElementIsInTheViewport = locator.#ensureElementIsInTheViewport;
        this.#waitForStableBoundingBox = locator.#waitForStableBoundingBox;
        return this;
      }
      /**
       * If the element has a "disabled" property, wait for the element to be
       * enabled.
       */
      #waitForEnabledIfNeeded = (handle, signal) => {
        if (!this.#waitForEnabled) {
          return rxjs_js_1.EMPTY;
        }
        return (0, rxjs_js_1.from)(handle.frame.waitForFunction((element) => {
          if (!(element instanceof HTMLElement)) {
            return true;
          }
          const isNativeFormControl = [
            "BUTTON",
            "INPUT",
            "SELECT",
            "TEXTAREA",
            "OPTION",
            "OPTGROUP"
          ].includes(element.nodeName);
          return !isNativeFormControl || !element.hasAttribute("disabled");
        }, {
          timeout: this._timeout,
          signal
        }, handle)).pipe((0, rxjs_js_1.ignoreElements)());
      };
      /**
       * Compares the bounding box of the element for two consecutive animation
       * frames and waits till they are the same.
       */
      #waitForStableBoundingBoxIfNeeded = (handle) => {
        if (!this.#waitForStableBoundingBox) {
          return rxjs_js_1.EMPTY;
        }
        return (0, rxjs_js_1.defer)(() => {
          return (0, rxjs_js_1.from)(handle.evaluate((element) => {
            return new Promise((resolve5) => {
              window.requestAnimationFrame(() => {
                const rect1 = element.getBoundingClientRect();
                window.requestAnimationFrame(() => {
                  const rect2 = element.getBoundingClientRect();
                  resolve5([
                    {
                      x: rect1.x,
                      y: rect1.y,
                      width: rect1.width,
                      height: rect1.height
                    },
                    {
                      x: rect2.x,
                      y: rect2.y,
                      width: rect2.width,
                      height: rect2.height
                    }
                  ]);
                });
              });
            });
          }));
        }).pipe((0, rxjs_js_1.first)(([rect1, rect2]) => {
          return rect1.x === rect2.x && rect1.y === rect2.y && rect1.width === rect2.width && rect1.height === rect2.height;
        }), (0, rxjs_js_1.retry)({ delay: exports2.RETRY_DELAY }), (0, rxjs_js_1.ignoreElements)());
      };
      /**
       * Checks if the element is in the viewport and auto-scrolls it if it is not.
       */
      #ensureElementIsInTheViewportIfNeeded = (handle) => {
        if (!this.#ensureElementIsInTheViewport) {
          return rxjs_js_1.EMPTY;
        }
        return (0, rxjs_js_1.from)(handle.isIntersectingViewport({ threshold: 0 })).pipe((0, rxjs_js_1.filter)((isIntersectingViewport) => {
          return !isIntersectingViewport;
        }), (0, rxjs_js_1.mergeMap)(() => {
          return (0, rxjs_js_1.from)(handle.scrollIntoView());
        }), (0, rxjs_js_1.mergeMap)(() => {
          return (0, rxjs_js_1.defer)(() => {
            return (0, rxjs_js_1.from)(handle.isIntersectingViewport({ threshold: 0 }));
          }).pipe((0, rxjs_js_1.first)(rxjs_js_1.identity), (0, rxjs_js_1.retry)({ delay: exports2.RETRY_DELAY }), (0, rxjs_js_1.ignoreElements)());
        }));
      };
      #click(options) {
        const signal = options?.signal;
        const cause = new Error("Locator.click");
        return this._wait(options).pipe(this.operators.conditions([
          this.#ensureElementIsInTheViewportIfNeeded,
          this.#waitForStableBoundingBoxIfNeeded,
          this.#waitForEnabledIfNeeded
        ], signal), (0, rxjs_js_1.tap)(() => {
          return this.emit(LocatorEvent.Action, void 0);
        }), (0, rxjs_js_1.mergeMap)((handle) => {
          return (0, rxjs_js_1.from)(handle.click(options)).pipe((0, rxjs_js_1.catchError)((err) => {
            void handle.dispose().catch(util_js_1.debugError);
            throw err;
          }));
        }), this.operators.retryAndRaceWithSignalAndTimer(signal, cause));
      }
      #fill(value, options) {
        const signal = options?.signal;
        const typingThreshold = options?.typingThreshold ?? 100;
        const cause = new Error("Locator.fill");
        return this._wait(options).pipe(this.operators.conditions([
          this.#ensureElementIsInTheViewportIfNeeded,
          this.#waitForStableBoundingBoxIfNeeded,
          this.#waitForEnabledIfNeeded
        ], signal), (0, rxjs_js_1.tap)(() => {
          return this.emit(LocatorEvent.Action, void 0);
        }), (0, rxjs_js_1.mergeMap)((handle) => {
          return (0, rxjs_js_1.from)(handle.evaluate((el) => {
            if (el instanceof HTMLSelectElement) {
              return "select";
            }
            if (el instanceof HTMLTextAreaElement) {
              return "typeable-input";
            }
            if (el instanceof HTMLInputElement) {
              if ((/* @__PURE__ */ new Set([
                "textarea",
                "text",
                "url",
                "tel",
                "search",
                "password",
                "number",
                "email"
              ])).has(el.type)) {
                return "typeable-input";
              } else {
                return "other-input";
              }
            }
            if (el.isContentEditable) {
              return "contenteditable";
            }
            return "unknown";
          })).pipe((0, rxjs_js_1.mergeMap)((inputType) => {
            const fillDirectly = () => {
              return (0, rxjs_js_1.from)(handle.focus()).pipe((0, rxjs_js_1.mergeMap)(() => {
                return (0, rxjs_js_1.from)(handle.evaluate((input, newValue) => {
                  const element = input;
                  const currentValue = element.isContentEditable ? element.innerText : element.value;
                  if (currentValue === newValue) {
                    return;
                  }
                  if (element.isContentEditable) {
                    element.innerText = newValue;
                  } else {
                    element.value = newValue;
                  }
                  element.dispatchEvent(new Event("input", { bubbles: true }));
                  element.dispatchEvent(new Event("change", { bubbles: true }));
                }, value));
              }));
            };
            switch (inputType) {
              case "select":
                return (0, rxjs_js_1.from)(handle.select(value).then(rxjs_js_1.noop));
              case "contenteditable":
              case "typeable-input":
                if (value.length < typingThreshold) {
                  return (0, rxjs_js_1.from)(handle.evaluate((input, newValue) => {
                    const element = input;
                    const currentValue = element.isContentEditable ? element.innerText : input.value;
                    if (newValue.length <= currentValue.length || !newValue.startsWith(currentValue)) {
                      if (element.isContentEditable) {
                        element.innerText = "";
                      } else {
                        input.value = "";
                      }
                      return newValue;
                    }
                    if (element.isContentEditable) {
                      element.innerText = "";
                      element.innerText = currentValue;
                    } else {
                      input.value = "";
                      input.value = currentValue;
                    }
                    return newValue.substring(currentValue.length);
                  }, value)).pipe((0, rxjs_js_1.mergeMap)((textToType) => {
                    if (!textToType) {
                      return (0, rxjs_js_1.of)(void 0);
                    }
                    return (0, rxjs_js_1.from)(handle.type(textToType));
                  }));
                }
                return fillDirectly();
              case "other-input":
                return fillDirectly();
              case "unknown":
                throw new Error(`Element cannot be filled out.`);
            }
          })).pipe((0, rxjs_js_1.catchError)((err) => {
            void handle.dispose().catch(util_js_1.debugError);
            throw err;
          }));
        }), this.operators.retryAndRaceWithSignalAndTimer(signal, cause));
      }
      #hover(options) {
        const signal = options?.signal;
        const cause = new Error("Locator.hover");
        return this._wait(options).pipe(this.operators.conditions([
          this.#ensureElementIsInTheViewportIfNeeded,
          this.#waitForStableBoundingBoxIfNeeded
        ], signal), (0, rxjs_js_1.tap)(() => {
          return this.emit(LocatorEvent.Action, void 0);
        }), (0, rxjs_js_1.mergeMap)((handle) => {
          return (0, rxjs_js_1.from)(handle.hover()).pipe((0, rxjs_js_1.catchError)((err) => {
            void handle.dispose().catch(util_js_1.debugError);
            throw err;
          }));
        }), this.operators.retryAndRaceWithSignalAndTimer(signal, cause));
      }
      #scroll(options) {
        const signal = options?.signal;
        const cause = new Error("Locator.scroll");
        return this._wait(options).pipe(this.operators.conditions([
          this.#ensureElementIsInTheViewportIfNeeded,
          this.#waitForStableBoundingBoxIfNeeded
        ], signal), (0, rxjs_js_1.tap)(() => {
          return this.emit(LocatorEvent.Action, void 0);
        }), (0, rxjs_js_1.mergeMap)((handle) => {
          return (0, rxjs_js_1.from)(handle.evaluate((el, scrollTop, scrollLeft) => {
            if (scrollTop !== void 0) {
              el.scrollTop = scrollTop;
            }
            if (scrollLeft !== void 0) {
              el.scrollLeft = scrollLeft;
            }
          }, options?.scrollTop, options?.scrollLeft)).pipe((0, rxjs_js_1.catchError)((err) => {
            void handle.dispose().catch(util_js_1.debugError);
            throw err;
          }));
        }), this.operators.retryAndRaceWithSignalAndTimer(signal, cause));
      }
      /**
       * Clones the locator.
       */
      clone() {
        return this._clone();
      }
      /**
       * Waits for the locator to get a handle from the page.
       *
       * @public
       */
      async waitHandle(options) {
        const cause = new Error("Locator.waitHandle");
        return await (0, rxjs_js_1.firstValueFrom)(this._wait(options).pipe(this.operators.retryAndRaceWithSignalAndTimer(options?.signal, cause)));
      }
      /**
       * Waits for the locator to get the serialized value from the page.
       *
       * Note this requires the value to be JSON-serializable.
       *
       * @public
       */
      async wait(options) {
        const env_1 = { stack: [], error: void 0, hasError: false };
        try {
          const handle = __addDisposableResource2(env_1, await this.waitHandle(options), false);
          return await handle.jsonValue();
        } catch (e_1) {
          env_1.error = e_1;
          env_1.hasError = true;
        } finally {
          __disposeResources2(env_1);
        }
      }
      /**
       * Maps the locator using the provided mapper.
       *
       * @public
       */
      map(mapper) {
        return new MappedLocator(this._clone(), (handle) => {
          return handle.evaluateHandle(mapper);
        });
      }
      /**
       * Creates an expectation that is evaluated against located values.
       *
       * If the expectations do not match, then the locator will retry.
       *
       * @public
       */
      filter(predicate) {
        return new FilteredLocator(this._clone(), async (handle, signal) => {
          await handle.frame.waitForFunction(predicate, { signal, timeout: this._timeout }, handle);
          return true;
        });
      }
      /**
       * Creates an expectation that is evaluated against located handles.
       *
       * If the expectations do not match, then the locator will retry.
       *
       * @internal
       */
      filterHandle(predicate) {
        return new FilteredLocator(this._clone(), predicate);
      }
      /**
       * Maps the locator using the provided mapper.
       *
       * @internal
       */
      mapHandle(mapper) {
        return new MappedLocator(this._clone(), mapper);
      }
      /**
       * Clicks the located element.
       */
      click(options) {
        return (0, rxjs_js_1.firstValueFrom)(this.#click(options));
      }
      /**
       * Fills out the input identified by the locator using the provided value. The
       * type of the input is determined at runtime and the appropriate fill-out
       * method is chosen based on the type. `contenteditable`, select, textarea and
       * input elements are supported.
       */
      fill(value, options) {
        return (0, rxjs_js_1.firstValueFrom)(this.#fill(value, options));
      }
      /**
       * Hovers over the located element.
       */
      hover(options) {
        return (0, rxjs_js_1.firstValueFrom)(this.#hover(options));
      }
      /**
       * Scrolls the located element.
       */
      scroll(options) {
        return (0, rxjs_js_1.firstValueFrom)(this.#scroll(options));
      }
    };
    exports2.Locator = Locator;
    var FunctionLocator = class _FunctionLocator extends Locator {
      static create(pageOrFrame, func) {
        return new _FunctionLocator(pageOrFrame, func).setTimeout("getDefaultTimeout" in pageOrFrame ? pageOrFrame.getDefaultTimeout() : pageOrFrame.page().getDefaultTimeout());
      }
      #pageOrFrame;
      #func;
      constructor(pageOrFrame, func) {
        super();
        this.#pageOrFrame = pageOrFrame;
        this.#func = func;
      }
      _clone() {
        return new _FunctionLocator(this.#pageOrFrame, this.#func);
      }
      _wait(options) {
        const signal = options?.signal;
        return (0, rxjs_js_1.defer)(() => {
          return (0, rxjs_js_1.from)(this.#pageOrFrame.waitForFunction(this.#func, {
            timeout: this.timeout,
            signal
          }));
        }).pipe((0, rxjs_js_1.throwIfEmpty)());
      }
    };
    exports2.FunctionLocator = FunctionLocator;
    var DelegatedLocator = class extends Locator {
      #delegate;
      constructor(delegate) {
        super();
        this.#delegate = delegate;
        this.copyOptions(this.#delegate);
      }
      get delegate() {
        return this.#delegate;
      }
      setTimeout(timeout) {
        const locator = super.setTimeout(timeout);
        locator.#delegate = this.#delegate.setTimeout(timeout);
        return locator;
      }
      setVisibility(visibility) {
        const locator = super.setVisibility(visibility);
        locator.#delegate = locator.#delegate.setVisibility(visibility);
        return locator;
      }
      setWaitForEnabled(value) {
        const locator = super.setWaitForEnabled(value);
        locator.#delegate = this.#delegate.setWaitForEnabled(value);
        return locator;
      }
      setEnsureElementIsInTheViewport(value) {
        const locator = super.setEnsureElementIsInTheViewport(value);
        locator.#delegate = this.#delegate.setEnsureElementIsInTheViewport(value);
        return locator;
      }
      setWaitForStableBoundingBox(value) {
        const locator = super.setWaitForStableBoundingBox(value);
        locator.#delegate = this.#delegate.setWaitForStableBoundingBox(value);
        return locator;
      }
    };
    exports2.DelegatedLocator = DelegatedLocator;
    var FilteredLocator = class _FilteredLocator extends DelegatedLocator {
      #predicate;
      constructor(base, predicate) {
        super(base);
        this.#predicate = predicate;
      }
      _clone() {
        return new _FilteredLocator(this.delegate.clone(), this.#predicate).copyOptions(this);
      }
      _wait(options) {
        return this.delegate._wait(options).pipe((0, rxjs_js_1.mergeMap)((handle) => {
          return (0, rxjs_js_1.from)(Promise.resolve(this.#predicate(handle, options?.signal))).pipe((0, rxjs_js_1.filter)((value) => {
            return value;
          }), (0, rxjs_js_1.map)(() => {
            return handle;
          }));
        }), (0, rxjs_js_1.throwIfEmpty)());
      }
    };
    exports2.FilteredLocator = FilteredLocator;
    var MappedLocator = class _MappedLocator extends DelegatedLocator {
      #mapper;
      constructor(base, mapper) {
        super(base);
        this.#mapper = mapper;
      }
      _clone() {
        return new _MappedLocator(this.delegate.clone(), this.#mapper).copyOptions(this);
      }
      _wait(options) {
        return this.delegate._wait(options).pipe((0, rxjs_js_1.mergeMap)((handle) => {
          return (0, rxjs_js_1.from)(Promise.resolve(this.#mapper(handle, options?.signal)));
        }));
      }
    };
    exports2.MappedLocator = MappedLocator;
    var NodeLocator = class _NodeLocator extends Locator {
      static create(pageOrFrame, selector) {
        return new _NodeLocator(pageOrFrame, selector).setTimeout("getDefaultTimeout" in pageOrFrame ? pageOrFrame.getDefaultTimeout() : pageOrFrame.page().getDefaultTimeout());
      }
      static createFromHandle(pageOrFrame, handle) {
        return new _NodeLocator(pageOrFrame, handle).setTimeout("getDefaultTimeout" in pageOrFrame ? pageOrFrame.getDefaultTimeout() : pageOrFrame.page().getDefaultTimeout());
      }
      #pageOrFrame;
      #selectorOrHandle;
      constructor(pageOrFrame, selectorOrHandle) {
        super();
        this.#pageOrFrame = pageOrFrame;
        this.#selectorOrHandle = selectorOrHandle;
      }
      /**
       * Waits for the element to become visible or hidden. visibility === 'visible'
       * means that the element has a computed style, the visibility property other
       * than 'hidden' or 'collapse' and non-empty bounding box. visibility ===
       * 'hidden' means the opposite of that.
       */
      #waitForVisibilityIfNeeded = (handle) => {
        if (!this.visibility) {
          return rxjs_js_1.EMPTY;
        }
        return (() => {
          switch (this.visibility) {
            case "hidden":
              return (0, rxjs_js_1.defer)(() => {
                return (0, rxjs_js_1.from)(handle.isHidden());
              });
            case "visible":
              return (0, rxjs_js_1.defer)(() => {
                return (0, rxjs_js_1.from)(handle.isVisible());
              });
          }
        })().pipe((0, rxjs_js_1.first)(rxjs_js_1.identity), (0, rxjs_js_1.retry)({ delay: exports2.RETRY_DELAY }), (0, rxjs_js_1.ignoreElements)());
      };
      _clone() {
        return new _NodeLocator(
          this.#pageOrFrame,
          // @ts-expect-error TSC does cannot parse private overloads.
          this.#selectorOrHandle
        ).copyOptions(this);
      }
      _wait(options) {
        const signal = options?.signal;
        return (0, rxjs_js_1.defer)(() => {
          if (typeof this.#selectorOrHandle === "string") {
            return (0, rxjs_js_1.from)(this.#pageOrFrame.waitForSelector(this.#selectorOrHandle, {
              visible: false,
              timeout: this._timeout,
              signal
            }));
          } else {
            return (0, rxjs_js_1.of)(this.#selectorOrHandle);
          }
        }).pipe((0, rxjs_js_1.filter)((value) => {
          return value !== null;
        }), (0, rxjs_js_1.throwIfEmpty)(), this.operators.conditions([this.#waitForVisibilityIfNeeded], signal));
      }
    };
    exports2.NodeLocator = NodeLocator;
    function checkLocatorArray(locators) {
      for (const locator of locators) {
        if (!(locator instanceof Locator)) {
          throw new Error("Unknown locator for race candidate");
        }
      }
      return locators;
    }
    var RaceLocator = class _RaceLocator extends Locator {
      static create(locators) {
        const array = checkLocatorArray(locators);
        return new _RaceLocator(array);
      }
      #locators;
      constructor(locators) {
        super();
        this.#locators = locators;
      }
      _clone() {
        return new _RaceLocator(this.#locators.map((locator) => {
          return locator.clone();
        })).copyOptions(this);
      }
      _wait(options) {
        return (0, rxjs_js_1.race)(...this.#locators.map((locator) => {
          return locator._wait(options);
        }));
      }
    };
    exports2.RaceLocator = RaceLocator;
    exports2.RETRY_DELAY = 100;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/api/ElementHandle.js
var require_ElementHandle = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/api/ElementHandle.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    var __setFunctionName2 = exports2 && exports2.__setFunctionName || function(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 });
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ElementHandle = void 0;
    exports2.bindIsolatedHandle = bindIsolatedHandle;
    var GetQueryHandler_js_1 = require_GetQueryHandler();
    var LazyArg_js_1 = require_LazyArg();
    var util_js_1 = require_util();
    var assert_js_1 = require_assert();
    var AsyncIterableUtil_js_1 = require_AsyncIterableUtil();
    var decorators_js_1 = require_decorators();
    var ElementHandleSymbol_js_1 = require_ElementHandleSymbol();
    var JSHandle_js_1 = require_JSHandle();
    var locators_js_1 = require_locators();
    function bindIsolatedHandle(target, _) {
      return async function(...args2) {
        if (this.realm === this.frame.isolatedRealm()) {
          return await target.call(this, ...args2);
        }
        let adoptedThis;
        if (this["isolatedHandle"]) {
          adoptedThis = this["isolatedHandle"];
        } else {
          this["isolatedHandle"] = adoptedThis = await this.frame.isolatedRealm().adoptHandle(this);
        }
        const result = await target.call(adoptedThis, ...args2);
        if (result === adoptedThis) {
          return this;
        }
        if (result instanceof JSHandle_js_1.JSHandle) {
          return await this.realm.transferHandle(result);
        }
        if (Array.isArray(result)) {
          await Promise.all(result.map(async (item, index, result2) => {
            if (item instanceof JSHandle_js_1.JSHandle) {
              result2[index] = await this.realm.transferHandle(item);
            }
          }));
        }
        if (result instanceof Map) {
          await Promise.all([...result.entries()].map(async ([key, value]) => {
            if (value instanceof JSHandle_js_1.JSHandle) {
              result.set(key, await this.realm.transferHandle(value));
            }
          }));
        }
        return result;
      };
    }
    var ElementHandle = (() => {
      let _classSuper = JSHandle_js_1.JSHandle;
      let _instanceExtraInitializers = [];
      let _getProperty_decorators;
      let _getProperties_decorators;
      let _jsonValue_decorators;
      let _$_decorators;
      let _$$_decorators;
      let _private_$$_decorators;
      let _private_$$_descriptor;
      let _waitForSelector_decorators;
      let _isVisible_decorators;
      let _isHidden_decorators;
      let _toElement_decorators;
      let _clickablePoint_decorators;
      let _hover_decorators;
      let _click_decorators;
      let _drag_decorators;
      let _dragEnter_decorators;
      let _dragOver_decorators;
      let _drop_decorators;
      let _dragAndDrop_decorators;
      let _select_decorators;
      let _tap_decorators;
      let _touchStart_decorators;
      let _touchMove_decorators;
      let _touchEnd_decorators;
      let _focus_decorators;
      let _type_decorators;
      let _press_decorators;
      let _boundingBox_decorators;
      let _boxModel_decorators;
      let _screenshot_decorators;
      let _isIntersectingViewport_decorators;
      let _scrollIntoView_decorators;
      let _asLocator_decorators;
      return class ElementHandle2 extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          _getProperty_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _getProperties_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _jsonValue_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _$_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _$$_decorators = [(0, decorators_js_1.throwIfDisposed)()];
          _private_$$_decorators = [bindIsolatedHandle];
          _waitForSelector_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _isVisible_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _isHidden_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _toElement_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _clickablePoint_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _hover_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _click_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _drag_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _dragEnter_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _dragOver_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _drop_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _dragAndDrop_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _select_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _tap_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _touchStart_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _touchMove_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _touchEnd_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _focus_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _type_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _press_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _boundingBox_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _boxModel_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _screenshot_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _isIntersectingViewport_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _scrollIntoView_decorators = [(0, decorators_js_1.throwIfDisposed)(), bindIsolatedHandle];
          _asLocator_decorators = [(0, decorators_js_1.throwIfDisposed)()];
          __esDecorate2(this, null, _getProperty_decorators, { kind: "method", name: "getProperty", static: false, private: false, access: { has: (obj) => "getProperty" in obj, get: (obj) => obj.getProperty }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _getProperties_decorators, { kind: "method", name: "getProperties", static: false, private: false, access: { has: (obj) => "getProperties" in obj, get: (obj) => obj.getProperties }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _jsonValue_decorators, { kind: "method", name: "jsonValue", static: false, private: false, access: { has: (obj) => "jsonValue" in obj, get: (obj) => obj.jsonValue }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _$_decorators, { kind: "method", name: "$", static: false, private: false, access: { has: (obj) => "$" in obj, get: (obj) => obj.$ }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _$$_decorators, { kind: "method", name: "$$", static: false, private: false, access: { has: (obj) => "$$" in obj, get: (obj) => obj.$$ }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, _private_$$_descriptor = { value: __setFunctionName2(async function(selector) {
            return await this.#$$impl(selector);
          }, "#$$") }, _private_$$_decorators, { kind: "method", name: "#$$", static: false, private: true, access: { has: (obj) => #$$ in obj, get: (obj) => obj.#$$ }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _waitForSelector_decorators, { kind: "method", name: "waitForSelector", static: false, private: false, access: { has: (obj) => "waitForSelector" in obj, get: (obj) => obj.waitForSelector }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _isVisible_decorators, { kind: "method", name: "isVisible", static: false, private: false, access: { has: (obj) => "isVisible" in obj, get: (obj) => obj.isVisible }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _isHidden_decorators, { kind: "method", name: "isHidden", static: false, private: false, access: { has: (obj) => "isHidden" in obj, get: (obj) => obj.isHidden }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _toElement_decorators, { kind: "method", name: "toElement", static: false, private: false, access: { has: (obj) => "toElement" in obj, get: (obj) => obj.toElement }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _clickablePoint_decorators, { kind: "method", name: "clickablePoint", static: false, private: false, access: { has: (obj) => "clickablePoint" in obj, get: (obj) => obj.clickablePoint }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _hover_decorators, { kind: "method", name: "hover", static: false, private: false, access: { has: (obj) => "hover" in obj, get: (obj) => obj.hover }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _click_decorators, { kind: "method", name: "click", static: false, private: false, access: { has: (obj) => "click" in obj, get: (obj) => obj.click }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _drag_decorators, { kind: "method", name: "drag", static: false, private: false, access: { has: (obj) => "drag" in obj, get: (obj) => obj.drag }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _dragEnter_decorators, { kind: "method", name: "dragEnter", static: false, private: false, access: { has: (obj) => "dragEnter" in obj, get: (obj) => obj.dragEnter }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _dragOver_decorators, { kind: "method", name: "dragOver", static: false, private: false, access: { has: (obj) => "dragOver" in obj, get: (obj) => obj.dragOver }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _drop_decorators, { kind: "method", name: "drop", static: false, private: false, access: { has: (obj) => "drop" in obj, get: (obj) => obj.drop }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _dragAndDrop_decorators, { kind: "method", name: "dragAndDrop", static: false, private: false, access: { has: (obj) => "dragAndDrop" in obj, get: (obj) => obj.dragAndDrop }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _select_decorators, { kind: "method", name: "select", static: false, private: false, access: { has: (obj) => "select" in obj, get: (obj) => obj.select }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _tap_decorators, { kind: "method", name: "tap", static: false, private: false, access: { has: (obj) => "tap" in obj, get: (obj) => obj.tap }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _touchStart_decorators, { kind: "method", name: "touchStart", static: false, private: false, access: { has: (obj) => "touchStart" in obj, get: (obj) => obj.touchStart }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _touchMove_decorators, { kind: "method", name: "touchMove", static: false, private: false, access: { has: (obj) => "touchMove" in obj, get: (obj) => obj.touchMove }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _touchEnd_decorators, { kind: "method", name: "touchEnd", static: false, private: false, access: { has: (obj) => "touchEnd" in obj, get: (obj) => obj.touchEnd }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _focus_decorators, { kind: "method", name: "focus", static: false, private: false, access: { has: (obj) => "focus" in obj, get: (obj) => obj.focus }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _type_decorators, { kind: "method", name: "type", static: false, private: false, access: { has: (obj) => "type" in obj, get: (obj) => obj.type }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _press_decorators, { kind: "method", name: "press", static: false, private: false, access: { has: (obj) => "press" in obj, get: (obj) => obj.press }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _boundingBox_decorators, { kind: "method", name: "boundingBox", static: false, private: false, access: { has: (obj) => "boundingBox" in obj, get: (obj) => obj.boundingBox }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _boxModel_decorators, { kind: "method", name: "boxModel", static: false, private: false, access: { has: (obj) => "boxModel" in obj, get: (obj) => obj.boxModel }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _screenshot_decorators, { kind: "method", name: "screenshot", static: false, private: false, access: { has: (obj) => "screenshot" in obj, get: (obj) => obj.screenshot }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _isIntersectingViewport_decorators, { kind: "method", name: "isIntersectingViewport", static: false, private: false, access: { has: (obj) => "isIntersectingViewport" in obj, get: (obj) => obj.isIntersectingViewport }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _scrollIntoView_decorators, { kind: "method", name: "scrollIntoView", static: false, private: false, access: { has: (obj) => "scrollIntoView" in obj, get: (obj) => obj.scrollIntoView }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _asLocator_decorators, { kind: "method", name: "asLocator", static: false, private: false, access: { has: (obj) => "asLocator" in obj, get: (obj) => obj.asLocator }, metadata: _metadata }, null, _instanceExtraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        /**
         * @internal
         * Cached isolatedHandle to prevent
         * trying to adopt it multiple times
         */
        isolatedHandle = __runInitializers2(this, _instanceExtraInitializers);
        /**
         * @internal
         */
        handle;
        /**
         * @internal
         */
        constructor(handle) {
          super();
          this.handle = handle;
          this[ElementHandleSymbol_js_1._isElementHandle] = true;
        }
        /**
         * @internal
         */
        get id() {
          return this.handle.id;
        }
        /**
         * @internal
         */
        get disposed() {
          return this.handle.disposed;
        }
        /**
         * @internal
         */
        async getProperty(propertyName) {
          return await this.handle.getProperty(propertyName);
        }
        /**
         * @internal
         */
        async getProperties() {
          return await this.handle.getProperties();
        }
        /**
         * @internal
         */
        async evaluate(pageFunction, ...args2) {
          pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.evaluate.name, pageFunction);
          return await this.handle.evaluate(pageFunction, ...args2);
        }
        /**
         * @internal
         */
        async evaluateHandle(pageFunction, ...args2) {
          pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.evaluateHandle.name, pageFunction);
          return await this.handle.evaluateHandle(pageFunction, ...args2);
        }
        /**
         * @internal
         */
        async jsonValue() {
          return await this.handle.jsonValue();
        }
        /**
         * @internal
         */
        toString() {
          return this.handle.toString();
        }
        /**
         * @internal
         */
        remoteObject() {
          return this.handle.remoteObject();
        }
        /**
         * @internal
         */
        async dispose() {
          await Promise.all([this.handle.dispose(), this.isolatedHandle?.dispose()]);
        }
        /**
         * @internal
         */
        asElement() {
          return this;
        }
        /**
         * Queries the current element for an element matching the given selector.
         *
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}.
         * @returns A {@link ElementHandle | element handle} to the first element
         * matching the given selector. Otherwise, `null`.
         */
        async $(selector) {
          const { updatedSelector, QueryHandler } = (0, GetQueryHandler_js_1.getQueryHandlerAndSelector)(selector);
          return await QueryHandler.queryOne(this, updatedSelector);
        }
        /**
         * Queries the current element for all elements matching the given selector.
         *
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}.
         * @returns An array of {@link ElementHandle | element handles} that point to
         * elements matching the given selector.
         */
        async $$(selector, options) {
          if (options?.isolate === false) {
            return await this.#$$impl(selector);
          }
          return await this.#$$(selector);
        }
        /**
         * Isolates {@link ElementHandle.$$} if needed.
         *
         * @internal
         */
        get #$$() {
          return _private_$$_descriptor.value;
        }
        /**
         * Implementation for {@link ElementHandle.$$}.
         *
         * @internal
         */
        async #$$impl(selector) {
          const { updatedSelector, QueryHandler } = (0, GetQueryHandler_js_1.getQueryHandlerAndSelector)(selector);
          return await AsyncIterableUtil_js_1.AsyncIterableUtil.collect(QueryHandler.queryAll(this, updatedSelector));
        }
        /**
         * Runs the given function on the first element matching the given selector in
         * the current element.
         *
         * If the given function returns a promise, then this method will wait till
         * the promise resolves.
         *
         * @example
         *
         * ```ts
         * const tweetHandle = await page.$('.tweet');
         * expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe(
         *   '100',
         * );
         * expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe(
         *   '10',
         * );
         * ```
         *
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}.
         * @param pageFunction - The function to be evaluated in this element's page's
         * context. The first element matching the selector will be passed in as the
         * first argument.
         * @param args - Additional arguments to pass to `pageFunction`.
         * @returns A promise to the result of the function.
         */
        async $eval(selector, pageFunction, ...args2) {
          const env_1 = { stack: [], error: void 0, hasError: false };
          try {
            pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.$eval.name, pageFunction);
            const elementHandle = __addDisposableResource2(env_1, await this.$(selector), false);
            if (!elementHandle) {
              throw new Error(`Error: failed to find element matching selector "${selector}"`);
            }
            return await elementHandle.evaluate(pageFunction, ...args2);
          } catch (e_1) {
            env_1.error = e_1;
            env_1.hasError = true;
          } finally {
            __disposeResources2(env_1);
          }
        }
        /**
         * Runs the given function on an array of elements matching the given selector
         * in the current element.
         *
         * If the given function returns a promise, then this method will wait till
         * the promise resolves.
         *
         * @example
         * HTML:
         *
         * ```html
         * <div class="feed">
         *   <div class="tweet">Hello!</div>
         *   <div class="tweet">Hi!</div>
         * </div>
         * ```
         *
         * JavaScript:
         *
         * ```ts
         * const feedHandle = await page.$('.feed');
         *
         * const listOfTweets = await feedHandle.$$eval('.tweet', nodes =>
         *   nodes.map(n => n.innerText),
         * );
         * ```
         *
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}.
         * @param pageFunction - The function to be evaluated in the element's page's
         * context. An array of elements matching the given selector will be passed to
         * the function as its first argument.
         * @param args - Additional arguments to pass to `pageFunction`.
         * @returns A promise to the result of the function.
         */
        async $$eval(selector, pageFunction, ...args2) {
          const env_2 = { stack: [], error: void 0, hasError: false };
          try {
            pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.$$eval.name, pageFunction);
            const results = await this.$$(selector);
            const elements = __addDisposableResource2(env_2, await this.evaluateHandle((_, ...elements2) => {
              return elements2;
            }, ...results), false);
            const [result] = await Promise.all([
              elements.evaluate(pageFunction, ...args2),
              ...results.map((results2) => {
                return results2.dispose();
              })
            ]);
            return result;
          } catch (e_2) {
            env_2.error = e_2;
            env_2.hasError = true;
          } finally {
            __disposeResources2(env_2);
          }
        }
        /**
         * Wait for an element matching the given selector to appear in the current
         * element.
         *
         * Unlike {@link Frame.waitForSelector}, this method does not work across
         * navigations or if the element is detached from DOM.
         *
         * @example
         *
         * ```ts
         * import puppeteer from 'puppeteer';
         *
         * const browser = await puppeteer.launch();
         * const page = await browser.newPage();
         * let currentURL;
         * page
         *   .mainFrame()
         *   .waitForSelector('img')
         *   .then(() => console.log('First URL with image: ' + currentURL));
         *
         * for (currentURL of [
         *   'https://example.com',
         *   'https://google.com',
         *   'https://bbc.com',
         * ]) {
         *   await page.goto(currentURL);
         * }
         * await browser.close();
         * ```
         *
         * @param selector - The selector to query and wait for.
         * @param options - Options for customizing waiting behavior.
         * @returns An element matching the given selector.
         * @throws Throws if an element matching the given selector doesn't appear.
         */
        async waitForSelector(selector, options = {}) {
          const { updatedSelector, QueryHandler, polling } = (0, GetQueryHandler_js_1.getQueryHandlerAndSelector)(selector);
          return await QueryHandler.waitFor(this, updatedSelector, {
            polling,
            ...options
          });
        }
        async #checkVisibility(visibility) {
          return await this.evaluate(async (element, PuppeteerUtil, visibility2) => {
            return Boolean(PuppeteerUtil.checkVisibility(element, visibility2));
          }, LazyArg_js_1.LazyArg.create((context) => {
            return context.puppeteerUtil;
          }), visibility);
        }
        /**
         * An element is considered to be visible if all of the following is
         * true:
         *
         * - the element has
         *   {@link https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle | computed styles}.
         *
         * - the element has a non-empty
         *   {@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect | bounding client rect}.
         *
         * - the element's {@link https://developer.mozilla.org/en-US/docs/Web/CSS/visibility | visibility}
         *   is not `hidden` or `collapse`.
         */
        async isVisible() {
          return await this.#checkVisibility(true);
        }
        /**
         * An element is considered to be hidden if at least one of the following is true:
         *
         * - the element has no
         *   {@link https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle | computed styles}.
         *
         * - the element has an empty
         *   {@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect | bounding client rect}.
         *
         * - the element's {@link https://developer.mozilla.org/en-US/docs/Web/CSS/visibility | visibility}
         *   is `hidden` or `collapse`.
         */
        async isHidden() {
          return await this.#checkVisibility(false);
        }
        /**
         * Converts the current handle to the given element type.
         *
         * @example
         *
         * ```ts
         * const element: ElementHandle<Element> = await page.$(
         *   '.class-name-of-anchor',
         * );
         * // DO NOT DISPOSE `element`, this will be always be the same handle.
         * const anchor: ElementHandle<HTMLAnchorElement> =
         *   await element.toElement('a');
         * ```
         *
         * @param tagName - The tag name of the desired element type.
         * @throws An error if the handle does not match. **The handle will not be
         * automatically disposed.**
         */
        async toElement(tagName) {
          const isMatchingTagName = await this.evaluate((node, tagName2) => {
            return node.nodeName === tagName2.toUpperCase();
          }, tagName);
          if (!isMatchingTagName) {
            throw new Error(`Element is not a(n) \`${tagName}\` element`);
          }
          return this;
        }
        /**
         * Returns the middle point within an element unless a specific offset is provided.
         */
        async clickablePoint(offset) {
          const box = await this.#clickableBox();
          if (!box) {
            throw new Error("Node is either not clickable or not an Element");
          }
          if (offset !== void 0) {
            return {
              x: box.x + offset.x,
              y: box.y + offset.y
            };
          }
          return {
            x: box.x + box.width / 2,
            y: box.y + box.height / 2
          };
        }
        /**
         * This method scrolls element into view if needed, and then
         * uses {@link Page.mouse} to hover over the center of the element.
         * If the element is detached from DOM, the method throws an error.
         */
        async hover() {
          await this.scrollIntoViewIfNeeded();
          const { x, y } = await this.clickablePoint();
          await this.frame.page().mouse.move(x, y);
        }
        /**
         * This method scrolls element into view if needed, and then
         * uses {@link Page.mouse} to click in the center of the element.
         * If the element is detached from DOM, the method throws an error.
         */
        async click(options = {}) {
          await this.scrollIntoViewIfNeeded();
          const { x, y } = await this.clickablePoint(options.offset);
          try {
            await this.frame.page().mouse.click(x, y, options);
          } finally {
            if (options.debugHighlight) {
              await this.frame.page().evaluate((x2, y2) => {
                const highlight = document.createElement("div");
                highlight.innerHTML = `<style>
        @scope {
          :scope {
              position: fixed;
              left: ${x2}px;
              top: ${y2}px;
              width: 10px;
              height: 10px;
              border-radius: 50%;
              animation: colorChange 10s 1 normal;
              animation-fill-mode: forwards;
          }

          @keyframes colorChange {
              from {
                  background-color: red;
              }
              to {
                  background-color: #FADADD00;
              }
          }
        }
      </style>`;
                highlight.addEventListener("animationend", () => {
                  highlight.remove();
                }, { once: true });
                document.body.append(highlight);
              }, x, y);
            }
          }
        }
        /**
         * Drags an element over the given element or point.
         *
         * @returns DEPRECATED. When drag interception is enabled, the drag payload is
         * returned.
         */
        async drag(target) {
          await this.scrollIntoViewIfNeeded();
          const page2 = this.frame.page();
          if (page2.isDragInterceptionEnabled()) {
            const source = await this.clickablePoint();
            if (target instanceof ElementHandle2) {
              target = await target.clickablePoint();
            }
            return await page2.mouse.drag(source, target);
          }
          try {
            if (!page2._isDragging) {
              page2._isDragging = true;
              await this.hover();
              await page2.mouse.down();
            }
            if (target instanceof ElementHandle2) {
              await target.hover();
            } else {
              await page2.mouse.move(target.x, target.y);
            }
          } catch (error) {
            page2._isDragging = false;
            throw error;
          }
        }
        /**
         * @deprecated Do not use. `dragenter` will automatically be performed during dragging.
         */
        async dragEnter(data = { items: [], dragOperationsMask: 1 }) {
          const page2 = this.frame.page();
          await this.scrollIntoViewIfNeeded();
          const target = await this.clickablePoint();
          await page2.mouse.dragEnter(target, data);
        }
        /**
         * @deprecated Do not use. `dragover` will automatically be performed during dragging.
         */
        async dragOver(data = { items: [], dragOperationsMask: 1 }) {
          const page2 = this.frame.page();
          await this.scrollIntoViewIfNeeded();
          const target = await this.clickablePoint();
          await page2.mouse.dragOver(target, data);
        }
        /**
         * @internal
         */
        async drop(dataOrElement = {
          items: [],
          dragOperationsMask: 1
        }) {
          const page2 = this.frame.page();
          if ("items" in dataOrElement) {
            await this.scrollIntoViewIfNeeded();
            const destination = await this.clickablePoint();
            await page2.mouse.drop(destination, dataOrElement);
          } else {
            await dataOrElement.drag(this);
            page2._isDragging = false;
            await page2.mouse.up();
          }
        }
        /**
         * @deprecated Use `ElementHandle.drop` instead.
         */
        async dragAndDrop(target, options) {
          const page2 = this.frame.page();
          (0, assert_js_1.assert)(page2.isDragInterceptionEnabled(), "Drag Interception is not enabled!");
          await this.scrollIntoViewIfNeeded();
          const startPoint = await this.clickablePoint();
          const targetPoint = await target.clickablePoint();
          await page2.mouse.dragAndDrop(startPoint, targetPoint, options);
        }
        /**
         * Triggers a `change` and `input` event once all the provided options have been
         * selected. If there's no `<select>` element matching `selector`, the method
         * throws an error.
         *
         * @example
         *
         * ```ts
         * handle.select('blue'); // single selection
         * handle.select('red', 'green', 'blue'); // multiple selections
         * ```
         *
         * @param values - Values of options to select. If the `<select>` has the
         * `multiple` attribute, all values are considered, otherwise only the first
         * one is taken into account.
         */
        async select(...values) {
          for (const value of values) {
            (0, assert_js_1.assert)((0, util_js_1.isString)(value), 'Values must be strings. Found value "' + value + '" of type "' + typeof value + '"');
          }
          return await this.evaluate((element, vals) => {
            const values2 = new Set(vals);
            if (!(element instanceof HTMLSelectElement)) {
              throw new Error("Element is not a <select> element.");
            }
            const selectedValues = /* @__PURE__ */ new Set();
            if (!element.multiple) {
              for (const option of element.options) {
                option.selected = false;
              }
              for (const option of element.options) {
                if (values2.has(option.value)) {
                  option.selected = true;
                  selectedValues.add(option.value);
                  break;
                }
              }
            } else {
              for (const option of element.options) {
                option.selected = values2.has(option.value);
                if (option.selected) {
                  selectedValues.add(option.value);
                }
              }
            }
            element.dispatchEvent(new Event("input", { bubbles: true }));
            element.dispatchEvent(new Event("change", { bubbles: true }));
            return [...selectedValues.values()];
          }, values);
        }
        /**
         * This method scrolls element into view if needed, and then uses
         * {@link Touchscreen.tap} to tap in the center of the element.
         * If the element is detached from DOM, the method throws an error.
         */
        async tap() {
          await this.scrollIntoViewIfNeeded();
          const { x, y } = await this.clickablePoint();
          await this.frame.page().touchscreen.tap(x, y);
        }
        /**
         * This method scrolls the element into view if needed, and then
         * starts a touch in the center of the element.
         * @returns A {@link TouchHandle} representing the touch that was started
         */
        async touchStart() {
          await this.scrollIntoViewIfNeeded();
          const { x, y } = await this.clickablePoint();
          return await this.frame.page().touchscreen.touchStart(x, y);
        }
        /**
         * This method scrolls the element into view if needed, and then
         * moves the touch to the center of the element.
         * @param touch - An optional {@link TouchHandle}. If provided, this touch
         * will be moved. If not provided, the first active touch will be moved.
         */
        async touchMove(touch) {
          await this.scrollIntoViewIfNeeded();
          const { x, y } = await this.clickablePoint();
          if (touch) {
            return await touch.move(x, y);
          }
          await this.frame.page().touchscreen.touchMove(x, y);
        }
        async touchEnd() {
          await this.scrollIntoViewIfNeeded();
          await this.frame.page().touchscreen.touchEnd();
        }
        /**
         * Calls {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus | focus} on the element.
         */
        async focus() {
          await this.evaluate((element) => {
            if (!(element instanceof HTMLElement)) {
              throw new Error("Cannot focus non-HTMLElement");
            }
            return element.focus();
          });
        }
        /**
         * Focuses the element, and then sends a `keydown`, `keypress`/`input`, and
         * `keyup` event for each character in the text.
         *
         * To press a special key, like `Control` or `ArrowDown`,
         * use {@link ElementHandle.press}.
         *
         * @example
         *
         * ```ts
         * await elementHandle.type('Hello'); // Types instantly
         * await elementHandle.type('World', {delay: 100}); // Types slower, like a user
         * ```
         *
         * @example
         * An example of typing into a text field and then submitting the form:
         *
         * ```ts
         * const elementHandle = await page.$('input');
         * await elementHandle.type('some text');
         * await elementHandle.press('Enter');
         * ```
         *
         * @param options - Delay in milliseconds. Defaults to 0.
         */
        async type(text, options) {
          await this.focus();
          await this.frame.page().keyboard.type(text, options);
        }
        /**
         * Focuses the element, and then uses {@link Keyboard.down} and {@link Keyboard.up}.
         *
         * @remarks
         * If `key` is a single character and no modifier keys besides `Shift`
         * are being held down, a `keypress`/`input` event will also be generated.
         * The `text` option can be specified to force an input event to be generated.
         *
         * **NOTE** Modifier keys DO affect `elementHandle.press`. Holding down `Shift`
         * will type the text in upper case.
         *
         * @param key - Name of key to press, such as `ArrowLeft`.
         * See {@link KeyInput} for a list of all key names.
         */
        async press(key, options) {
          await this.focus();
          await this.frame.page().keyboard.press(key, options);
        }
        async #clickableBox() {
          const boxes = await this.evaluate((element) => {
            if (!(element instanceof Element)) {
              return null;
            }
            return [...element.getClientRects()].map((rect) => {
              return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
            });
          });
          if (!boxes?.length) {
            return null;
          }
          await this.#intersectBoundingBoxesWithFrame(boxes);
          let frame = this.frame;
          let parentFrame;
          while (parentFrame = frame?.parentFrame()) {
            const env_3 = { stack: [], error: void 0, hasError: false };
            try {
              const handle = __addDisposableResource2(env_3, await frame.frameElement(), false);
              if (!handle) {
                throw new Error("Unsupported frame type");
              }
              const parentBox = await handle.evaluate((element) => {
                if (element.getClientRects().length === 0) {
                  return null;
                }
                const rect = element.getBoundingClientRect();
                const style = window.getComputedStyle(element);
                return {
                  left: rect.left + parseInt(style.paddingLeft, 10) + parseInt(style.borderLeftWidth, 10),
                  top: rect.top + parseInt(style.paddingTop, 10) + parseInt(style.borderTopWidth, 10)
                };
              });
              if (!parentBox) {
                return null;
              }
              for (const box2 of boxes) {
                box2.x += parentBox.left;
                box2.y += parentBox.top;
              }
              await handle.#intersectBoundingBoxesWithFrame(boxes);
              frame = parentFrame;
            } catch (e_3) {
              env_3.error = e_3;
              env_3.hasError = true;
            } finally {
              __disposeResources2(env_3);
            }
          }
          const box = boxes.find((box2) => {
            return box2.width >= 1 && box2.height >= 1;
          });
          if (!box) {
            return null;
          }
          return {
            x: box.x,
            y: box.y,
            height: box.height,
            width: box.width
          };
        }
        async #intersectBoundingBoxesWithFrame(boxes) {
          const { documentWidth, documentHeight } = await this.frame.isolatedRealm().evaluate(() => {
            return {
              documentWidth: document.documentElement.clientWidth,
              documentHeight: document.documentElement.clientHeight
            };
          });
          for (const box of boxes) {
            intersectBoundingBox(box, documentWidth, documentHeight);
          }
        }
        /**
         * This method returns the bounding box of the element (relative to the main frame),
         * or `null` if the element is {@link https://drafts.csswg.org/css-display-4/#box-generation | not part of the layout}
         * (example: `display: none`).
         */
        async boundingBox() {
          const box = await this.evaluate((element) => {
            if (!(element instanceof Element)) {
              return null;
            }
            if (element.getClientRects().length === 0) {
              return null;
            }
            const rect = element.getBoundingClientRect();
            return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
          });
          if (!box) {
            return null;
          }
          const offset = await this.#getTopLeftCornerOfFrame();
          if (!offset) {
            return null;
          }
          return {
            x: box.x + offset.x,
            y: box.y + offset.y,
            height: box.height,
            width: box.width
          };
        }
        /**
         * This method returns boxes of the element,
         * or `null` if the element is {@link https://drafts.csswg.org/css-display-4/#box-generation | not part of the layout}
         * (example: `display: none`).
         *
         * @remarks
         *
         * Boxes are represented as an array of points;
         * Each Point is an object `{x, y}`. Box points are sorted clock-wise.
         */
        async boxModel() {
          const model = await this.evaluate((element) => {
            if (!(element instanceof Element)) {
              return null;
            }
            if (element.getClientRects().length === 0) {
              return null;
            }
            const rect = element.getBoundingClientRect();
            const style = window.getComputedStyle(element);
            const offsets = {
              padding: {
                left: parseInt(style.paddingLeft, 10),
                top: parseInt(style.paddingTop, 10),
                right: parseInt(style.paddingRight, 10),
                bottom: parseInt(style.paddingBottom, 10)
              },
              margin: {
                left: -parseInt(style.marginLeft, 10),
                top: -parseInt(style.marginTop, 10),
                right: -parseInt(style.marginRight, 10),
                bottom: -parseInt(style.marginBottom, 10)
              },
              border: {
                left: parseInt(style.borderLeft, 10),
                top: parseInt(style.borderTop, 10),
                right: parseInt(style.borderRight, 10),
                bottom: parseInt(style.borderBottom, 10)
              }
            };
            const border = [
              { x: rect.left, y: rect.top },
              { x: rect.left + rect.width, y: rect.top },
              { x: rect.left + rect.width, y: rect.top + rect.height },
              { x: rect.left, y: rect.top + rect.height }
            ];
            const padding = transformQuadWithOffsets(border, offsets.border);
            const content = transformQuadWithOffsets(padding, offsets.padding);
            const margin = transformQuadWithOffsets(border, offsets.margin);
            return {
              content,
              padding,
              border,
              margin,
              width: rect.width,
              height: rect.height
            };
            function transformQuadWithOffsets(quad, offsets2) {
              return [
                {
                  x: quad[0].x + offsets2.left,
                  y: quad[0].y + offsets2.top
                },
                {
                  x: quad[1].x - offsets2.right,
                  y: quad[1].y + offsets2.top
                },
                {
                  x: quad[2].x - offsets2.right,
                  y: quad[2].y - offsets2.bottom
                },
                {
                  x: quad[3].x + offsets2.left,
                  y: quad[3].y - offsets2.bottom
                }
              ];
            }
          });
          if (!model) {
            return null;
          }
          const offset = await this.#getTopLeftCornerOfFrame();
          if (!offset) {
            return null;
          }
          for (const attribute of [
            "content",
            "padding",
            "border",
            "margin"
          ]) {
            for (const point of model[attribute]) {
              point.x += offset.x;
              point.y += offset.y;
            }
          }
          return model;
        }
        async #getTopLeftCornerOfFrame() {
          const point = { x: 0, y: 0 };
          let frame = this.frame;
          let parentFrame;
          while (parentFrame = frame?.parentFrame()) {
            const env_4 = { stack: [], error: void 0, hasError: false };
            try {
              const handle = __addDisposableResource2(env_4, await frame.frameElement(), false);
              if (!handle) {
                throw new Error("Unsupported frame type");
              }
              const parentBox = await handle.evaluate((element) => {
                if (element.getClientRects().length === 0) {
                  return null;
                }
                const rect = element.getBoundingClientRect();
                const style = window.getComputedStyle(element);
                return {
                  left: rect.left + parseInt(style.paddingLeft, 10) + parseInt(style.borderLeftWidth, 10),
                  top: rect.top + parseInt(style.paddingTop, 10) + parseInt(style.borderTopWidth, 10)
                };
              });
              if (!parentBox) {
                return null;
              }
              point.x += parentBox.left;
              point.y += parentBox.top;
              frame = parentFrame;
            } catch (e_4) {
              env_4.error = e_4;
              env_4.hasError = true;
            } finally {
              __disposeResources2(env_4);
            }
          }
          return point;
        }
        async screenshot(options = {}) {
          const { scrollIntoView = true, clip } = options;
          const page2 = this.frame.page();
          if (scrollIntoView) {
            await this.scrollIntoViewIfNeeded();
          }
          const elementClip = await this.#nonEmptyVisibleBoundingBox();
          const [pageLeft, pageTop] = await this.evaluate(() => {
            if (!window.visualViewport) {
              throw new Error("window.visualViewport is not supported.");
            }
            return [
              window.visualViewport.pageLeft,
              window.visualViewport.pageTop
            ];
          });
          elementClip.x += pageLeft;
          elementClip.y += pageTop;
          if (clip) {
            elementClip.x += clip.x;
            elementClip.y += clip.y;
            elementClip.height = clip.height;
            elementClip.width = clip.width;
          }
          return await page2.screenshot({ ...options, clip: elementClip });
        }
        async #nonEmptyVisibleBoundingBox() {
          const box = await this.boundingBox();
          (0, assert_js_1.assert)(box, "Node is either not visible or not an HTMLElement");
          (0, assert_js_1.assert)(box.width !== 0, "Node has 0 width.");
          (0, assert_js_1.assert)(box.height !== 0, "Node has 0 height.");
          return box;
        }
        /**
         * @internal
         */
        async assertConnectedElement() {
          const error = await this.evaluate(async (element) => {
            if (!element.isConnected) {
              return "Node is detached from document";
            }
            if (element.nodeType !== Node.ELEMENT_NODE) {
              return "Node is not of type HTMLElement";
            }
            return;
          });
          if (error) {
            throw new Error(error);
          }
        }
        /**
         * @internal
         */
        async scrollIntoViewIfNeeded() {
          if (await this.isIntersectingViewport({
            threshold: 1
          })) {
            return;
          }
          await this.scrollIntoView();
        }
        /**
         * Resolves to true if the element is visible in the current viewport. If an
         * element is an SVG, we check if the svg owner element is in the viewport
         * instead. See https://crbug.com/963246.
         *
         * @param options - Threshold for the intersection between 0 (no intersection) and 1
         * (full intersection). Defaults to 1.
         */
        async isIntersectingViewport(options = {}) {
          const env_5 = { stack: [], error: void 0, hasError: false };
          try {
            await this.assertConnectedElement();
            const handle = await this.#asSVGElementHandle();
            const target = __addDisposableResource2(env_5, handle && await handle.#getOwnerSVGElement(), false);
            return await (target ?? this).evaluate(async (element, threshold) => {
              const visibleRatio = await new Promise((resolve5) => {
                const observer = new IntersectionObserver((entries) => {
                  resolve5(entries[0].intersectionRatio);
                  observer.disconnect();
                });
                observer.observe(element);
              });
              return threshold === 1 ? visibleRatio === 1 : visibleRatio > threshold;
            }, options.threshold ?? 0);
          } catch (e_5) {
            env_5.error = e_5;
            env_5.hasError = true;
          } finally {
            __disposeResources2(env_5);
          }
        }
        /**
         * Scrolls the element into view using either the automation protocol client
         * or by calling element.scrollIntoView.
         */
        async scrollIntoView() {
          await this.assertConnectedElement();
          await this.evaluate(async (element) => {
            element.scrollIntoView({
              block: "center",
              inline: "center",
              behavior: "instant"
            });
          });
        }
        /**
         * Creates a locator based on an ElementHandle. This would not allow
         * refreshing the element handle if it is stale but it allows re-using other
         * locator pre-conditions.
         */
        asLocator() {
          return locators_js_1.NodeLocator.createFromHandle(this.frame, this);
        }
        /**
         * Returns true if an element is an SVGElement (included svg, path, rect
         * etc.).
         */
        async #asSVGElementHandle() {
          if (await this.evaluate((element) => {
            return element instanceof SVGElement;
          })) {
            return this;
          } else {
            return null;
          }
        }
        async #getOwnerSVGElement() {
          return await this.evaluateHandle((element) => {
            if (element instanceof SVGSVGElement) {
              return element;
            }
            return element.ownerSVGElement;
          });
        }
      };
    })();
    exports2.ElementHandle = ElementHandle;
    function intersectBoundingBox(box, width, height) {
      box.width = Math.max(box.x >= 0 ? Math.min(width - box.x, box.width) : Math.min(width, box.width + box.x), 0);
      box.height = Math.max(box.y >= 0 ? Math.min(height - box.y, box.height) : Math.min(height, box.height + box.y), 0);
      box.x = Math.max(box.x, 0);
      box.y = Math.max(box.y, 0);
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/api/Frame.js
var require_Frame = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/api/Frame.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Frame = exports2.throwIfDetached = exports2.FrameEvent = void 0;
    var EventEmitter_js_1 = require_EventEmitter();
    var GetQueryHandler_js_1 = require_GetQueryHandler();
    var HandleIterator_js_1 = require_HandleIterator();
    var util_js_1 = require_util();
    var environment_js_1 = require_environment();
    var assert_js_1 = require_assert();
    var decorators_js_1 = require_decorators();
    var locators_js_1 = require_locators();
    var FrameEvent;
    (function(FrameEvent2) {
      FrameEvent2.FrameNavigated = /* @__PURE__ */ Symbol("Frame.FrameNavigated");
      FrameEvent2.FrameSwapped = /* @__PURE__ */ Symbol("Frame.FrameSwapped");
      FrameEvent2.LifecycleEvent = /* @__PURE__ */ Symbol("Frame.LifecycleEvent");
      FrameEvent2.FrameNavigatedWithinDocument = /* @__PURE__ */ Symbol("Frame.FrameNavigatedWithinDocument");
      FrameEvent2.FrameDetached = /* @__PURE__ */ Symbol("Frame.FrameDetached");
      FrameEvent2.FrameSwappedByActivation = /* @__PURE__ */ Symbol("Frame.FrameSwappedByActivation");
    })(FrameEvent || (exports2.FrameEvent = FrameEvent = {}));
    exports2.throwIfDetached = (0, decorators_js_1.throwIfDisposed)((frame) => {
      return `Attempted to use detached Frame '${frame._id}'.`;
    });
    var Frame = (() => {
      let _classSuper = EventEmitter_js_1.EventEmitter;
      let _instanceExtraInitializers = [];
      let _frameElement_decorators;
      let _evaluateHandle_decorators;
      let _evaluate_decorators;
      let _locator_decorators;
      let _$_decorators;
      let _$$_decorators;
      let _$eval_decorators;
      let _$$eval_decorators;
      let _waitForSelector_decorators;
      let _waitForFunction_decorators;
      let _content_decorators;
      let _addScriptTag_decorators;
      let _addStyleTag_decorators;
      let _click_decorators;
      let _focus_decorators;
      let _hover_decorators;
      let _select_decorators;
      let _tap_decorators;
      let _type_decorators;
      let _title_decorators;
      return class Frame extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          _frameElement_decorators = [exports2.throwIfDetached];
          _evaluateHandle_decorators = [exports2.throwIfDetached];
          _evaluate_decorators = [exports2.throwIfDetached];
          _locator_decorators = [exports2.throwIfDetached];
          _$_decorators = [exports2.throwIfDetached];
          _$$_decorators = [exports2.throwIfDetached];
          _$eval_decorators = [exports2.throwIfDetached];
          _$$eval_decorators = [exports2.throwIfDetached];
          _waitForSelector_decorators = [exports2.throwIfDetached];
          _waitForFunction_decorators = [exports2.throwIfDetached];
          _content_decorators = [exports2.throwIfDetached];
          _addScriptTag_decorators = [exports2.throwIfDetached];
          _addStyleTag_decorators = [exports2.throwIfDetached];
          _click_decorators = [exports2.throwIfDetached];
          _focus_decorators = [exports2.throwIfDetached];
          _hover_decorators = [exports2.throwIfDetached];
          _select_decorators = [exports2.throwIfDetached];
          _tap_decorators = [exports2.throwIfDetached];
          _type_decorators = [exports2.throwIfDetached];
          _title_decorators = [exports2.throwIfDetached];
          __esDecorate2(this, null, _frameElement_decorators, { kind: "method", name: "frameElement", static: false, private: false, access: { has: (obj) => "frameElement" in obj, get: (obj) => obj.frameElement }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _evaluateHandle_decorators, { kind: "method", name: "evaluateHandle", static: false, private: false, access: { has: (obj) => "evaluateHandle" in obj, get: (obj) => obj.evaluateHandle }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _evaluate_decorators, { kind: "method", name: "evaluate", static: false, private: false, access: { has: (obj) => "evaluate" in obj, get: (obj) => obj.evaluate }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _locator_decorators, { kind: "method", name: "locator", static: false, private: false, access: { has: (obj) => "locator" in obj, get: (obj) => obj.locator }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _$_decorators, { kind: "method", name: "$", static: false, private: false, access: { has: (obj) => "$" in obj, get: (obj) => obj.$ }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _$$_decorators, { kind: "method", name: "$$", static: false, private: false, access: { has: (obj) => "$$" in obj, get: (obj) => obj.$$ }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _$eval_decorators, { kind: "method", name: "$eval", static: false, private: false, access: { has: (obj) => "$eval" in obj, get: (obj) => obj.$eval }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _$$eval_decorators, { kind: "method", name: "$$eval", static: false, private: false, access: { has: (obj) => "$$eval" in obj, get: (obj) => obj.$$eval }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _waitForSelector_decorators, { kind: "method", name: "waitForSelector", static: false, private: false, access: { has: (obj) => "waitForSelector" in obj, get: (obj) => obj.waitForSelector }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _waitForFunction_decorators, { kind: "method", name: "waitForFunction", static: false, private: false, access: { has: (obj) => "waitForFunction" in obj, get: (obj) => obj.waitForFunction }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _content_decorators, { kind: "method", name: "content", static: false, private: false, access: { has: (obj) => "content" in obj, get: (obj) => obj.content }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _addScriptTag_decorators, { kind: "method", name: "addScriptTag", static: false, private: false, access: { has: (obj) => "addScriptTag" in obj, get: (obj) => obj.addScriptTag }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _addStyleTag_decorators, { kind: "method", name: "addStyleTag", static: false, private: false, access: { has: (obj) => "addStyleTag" in obj, get: (obj) => obj.addStyleTag }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _click_decorators, { kind: "method", name: "click", static: false, private: false, access: { has: (obj) => "click" in obj, get: (obj) => obj.click }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _focus_decorators, { kind: "method", name: "focus", static: false, private: false, access: { has: (obj) => "focus" in obj, get: (obj) => obj.focus }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _hover_decorators, { kind: "method", name: "hover", static: false, private: false, access: { has: (obj) => "hover" in obj, get: (obj) => obj.hover }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _select_decorators, { kind: "method", name: "select", static: false, private: false, access: { has: (obj) => "select" in obj, get: (obj) => obj.select }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _tap_decorators, { kind: "method", name: "tap", static: false, private: false, access: { has: (obj) => "tap" in obj, get: (obj) => obj.tap }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _type_decorators, { kind: "method", name: "type", static: false, private: false, access: { has: (obj) => "type" in obj, get: (obj) => obj.type }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _title_decorators, { kind: "method", name: "title", static: false, private: false, access: { has: (obj) => "title" in obj, get: (obj) => obj.title }, metadata: _metadata }, null, _instanceExtraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        /**
         * @internal
         */
        _id = __runInitializers2(this, _instanceExtraInitializers);
        /**
         * @internal
         */
        _parentId;
        /**
         * @internal
         */
        _name;
        /**
         * @internal
         */
        _hasStartedLoading = false;
        /**
         * @internal
         */
        constructor() {
          super();
        }
        #_document;
        /**
         * @internal
         */
        #document() {
          if (!this.#_document) {
            this.#_document = this.mainRealm().evaluateHandle(() => {
              return document;
            });
          }
          return this.#_document;
        }
        /**
         * Used to clear the document handle that has been destroyed.
         *
         * @internal
         */
        clearDocumentHandle() {
          this.#_document = void 0;
        }
        /**
         * @returns The frame element associated with this frame (if any).
         */
        async frameElement() {
          const env_1 = { stack: [], error: void 0, hasError: false };
          try {
            const parentFrame = this.parentFrame();
            if (!parentFrame) {
              return null;
            }
            const list = __addDisposableResource2(env_1, await parentFrame.isolatedRealm().evaluateHandle(() => {
              return document.querySelectorAll("iframe,frame");
            }), false);
            for await (const iframe_1 of (0, HandleIterator_js_1.transposeIterableHandle)(list)) {
              const env_2 = { stack: [], error: void 0, hasError: false };
              try {
                const iframe = __addDisposableResource2(env_2, iframe_1, false);
                const frame = await iframe.contentFrame();
                if (frame?._id === this._id) {
                  return await parentFrame.mainRealm().adoptHandle(iframe);
                }
              } catch (e_1) {
                env_2.error = e_1;
                env_2.hasError = true;
              } finally {
                __disposeResources2(env_2);
              }
            }
            return null;
          } catch (e_2) {
            env_1.error = e_2;
            env_1.hasError = true;
          } finally {
            __disposeResources2(env_1);
          }
        }
        /**
         * Behaves identically to {@link Page.evaluateHandle} except it's run within
         * the context of this frame.
         *
         * See {@link Page.evaluateHandle} for details.
         */
        async evaluateHandle(pageFunction, ...args2) {
          pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.evaluateHandle.name, pageFunction);
          return await this.mainRealm().evaluateHandle(pageFunction, ...args2);
        }
        /**
         * Behaves identically to {@link Page.evaluate} except it's run within
         * the context of this frame.
         *
         * See {@link Page.evaluate} for details.
         */
        async evaluate(pageFunction, ...args2) {
          pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.evaluate.name, pageFunction);
          return await this.mainRealm().evaluate(pageFunction, ...args2);
        }
        /**
         * @internal
         */
        locator(input) {
          if (typeof input === "string") {
            return locators_js_1.NodeLocator.create(this, input);
          } else {
            return locators_js_1.FunctionLocator.create(this, input);
          }
        }
        /**
         * Queries the frame for an element matching the given selector.
         *
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}.
         *
         * @returns A {@link ElementHandle | element handle} to the first element
         * matching the given selector. Otherwise, `null`.
         */
        async $(selector) {
          const document2 = await this.#document();
          return await document2.$(selector);
        }
        /**
         * Queries the frame for all elements matching the given selector.
         *
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}.
         *
         * @returns An array of {@link ElementHandle | element handles} that point to
         * elements matching the given selector.
         */
        async $$(selector, options) {
          const document2 = await this.#document();
          return await document2.$$(selector, options);
        }
        /**
         * Runs the given function on the first element matching the given selector in
         * the frame.
         *
         * If the given function returns a promise, then this method will wait till
         * the promise resolves.
         *
         * @example
         *
         * ```ts
         * const searchValue = await frame.$eval('#search', el => el.value);
         * ```
         *
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}.
         * @param pageFunction - The function to be evaluated in the frame's context.
         * The first element matching the selector will be passed to the function as
         * its first argument.
         * @param args - Additional arguments to pass to `pageFunction`.
         * @returns A promise to the result of the function.
         */
        async $eval(selector, pageFunction, ...args2) {
          pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.$eval.name, pageFunction);
          const document2 = await this.#document();
          return await document2.$eval(selector, pageFunction, ...args2);
        }
        /**
         * Runs the given function on an array of elements matching the given selector
         * in the frame.
         *
         * If the given function returns a promise, then this method will wait till
         * the promise resolves.
         *
         * @example
         *
         * ```ts
         * const divsCounts = await frame.$$eval('div', divs => divs.length);
         * ```
         *
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}.
         * @param pageFunction - The function to be evaluated in the frame's context.
         * An array of elements matching the given selector will be passed to the
         * function as its first argument.
         * @param args - Additional arguments to pass to `pageFunction`.
         * @returns A promise to the result of the function.
         */
        async $$eval(selector, pageFunction, ...args2) {
          pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.$$eval.name, pageFunction);
          const document2 = await this.#document();
          return await document2.$$eval(selector, pageFunction, ...args2);
        }
        /**
         * Waits for an element matching the given selector to appear in the frame.
         *
         * This method works across navigations.
         *
         * @example
         *
         * ```ts
         * import puppeteer from 'puppeteer';
         *
         * const browser = await puppeteer.launch();
         * const page = await browser.newPage();
         * let currentURL;
         * page
         *   .mainFrame()
         *   .waitForSelector('img')
         *   .then(() => console.log('First URL with image: ' + currentURL));
         *
         * for (currentURL of [
         *   'https://example.com',
         *   'https://google.com',
         *   'https://bbc.com',
         * ]) {
         *   await page.goto(currentURL);
         * }
         * await browser.close();
         * ```
         *
         * @param selector - The selector to query and wait for.
         * @param options - Options for customizing waiting behavior.
         * @returns An element matching the given selector.
         * @throws Throws if an element matching the given selector doesn't appear.
         */
        async waitForSelector(selector, options = {}) {
          const { updatedSelector, QueryHandler, polling } = (0, GetQueryHandler_js_1.getQueryHandlerAndSelector)(selector);
          return await QueryHandler.waitFor(this, updatedSelector, {
            polling,
            ...options
          });
        }
        /**
         * @example
         * The `waitForFunction` can be used to observe viewport size change:
         *
         * ```ts
         * import puppeteer from 'puppeteer';
         *
         * const browser = await puppeteer.launch();
         * const page = await browser.newPage();
         * const watchDog = page
         *   .mainFrame()
         *   .waitForFunction('window.innerWidth < 100');
         * page.setViewport({width: 50, height: 50});
         * await watchDog;
         * await browser.close();
         * ```
         *
         * To pass arguments from Node.js to the predicate of `page.waitForFunction` function:
         *
         * ```ts
         * const selector = '.foo';
         * await frame.waitForFunction(
         *   selector => !!document.querySelector(selector),
         *   {}, // empty options object
         *   selector,
         * );
         * ```
         *
         * @param pageFunction - the function to evaluate in the frame context.
         * @param options - options to configure the polling method, timeout and signal.
         * @param args - arguments to pass to the `pageFunction`.
         * @returns the promise which resolve when the `pageFunction` returns a truthy value.
         */
        async waitForFunction(pageFunction, options = {}, ...args2) {
          return await this.mainRealm().waitForFunction(pageFunction, options, ...args2);
        }
        /**
         * The full HTML contents of the frame, including the DOCTYPE.
         */
        async content() {
          return await this.evaluate(() => {
            let content = "";
            for (const node of document.childNodes) {
              switch (node) {
                case document.documentElement:
                  content += document.documentElement.outerHTML;
                  break;
                default:
                  content += new XMLSerializer().serializeToString(node);
                  break;
              }
            }
            return content;
          });
        }
        /**
         * @internal
         */
        async setFrameContent(content) {
          return await this.evaluate((html) => {
            document.open();
            document.write(html);
            document.close();
          }, content);
        }
        /**
         * The frame's `name` attribute as specified in the tag.
         *
         * @remarks
         * If the name is empty, it returns the `id` attribute instead.
         *
         * @remarks
         * This value is calculated once when the frame is created, and will not
         * update if the attribute is changed later.
         *
         * @deprecated Use
         *
         * ```ts
         * const element = await frame.frameElement();
         * const nameOrId = await element.evaluate(frame => frame.name ?? frame.id);
         * ```
         */
        name() {
          return this._name || "";
        }
        /**
         * Is`true` if the frame has been detached. Otherwise, `false`.
         *
         * @deprecated Use the `detached` getter.
         */
        isDetached() {
          return this.detached;
        }
        /**
         * @internal
         */
        get disposed() {
          return this.detached;
        }
        /**
         * Adds a `<script>` tag into the page with the desired url or content.
         *
         * @param options - Options for the script.
         * @returns An {@link ElementHandle | element handle} to the injected
         * `<script>` element.
         */
        async addScriptTag(options) {
          let { content = "", type } = options;
          const { path: path2 } = options;
          if (+!!options.url + +!!path2 + +!!content !== 1) {
            throw new Error("Exactly one of `url`, `path`, or `content` must be specified.");
          }
          if (path2) {
            content = await environment_js_1.environment.value.fs.promises.readFile(path2, "utf8");
            content += `//# sourceURL=${path2.replace(/\n/g, "")}`;
          }
          type = type ?? "text/javascript";
          return await this.mainRealm().transferHandle(await this.isolatedRealm().evaluateHandle(async ({ url, id, type: type2, content: content2 }) => {
            return await new Promise((resolve5, reject) => {
              const script = document.createElement("script");
              script.type = type2;
              script.text = content2;
              script.addEventListener("error", (event) => {
                reject(new Error(event.message ?? "Could not load script"));
              }, { once: true });
              if (id) {
                script.id = id;
              }
              if (url) {
                script.src = url;
                script.addEventListener("load", () => {
                  resolve5(script);
                }, { once: true });
                document.head.appendChild(script);
              } else {
                document.head.appendChild(script);
                resolve5(script);
              }
            });
          }, { ...options, type, content }));
        }
        /**
         * @internal
         */
        async addStyleTag(options) {
          let { content = "" } = options;
          const { path: path2 } = options;
          if (+!!options.url + +!!path2 + +!!content !== 1) {
            throw new Error("Exactly one of `url`, `path`, or `content` must be specified.");
          }
          if (path2) {
            content = await environment_js_1.environment.value.fs.promises.readFile(path2, "utf8");
            content += "/*# sourceURL=" + path2.replace(/\n/g, "") + "*/";
            options.content = content;
          }
          return await this.mainRealm().transferHandle(await this.isolatedRealm().evaluateHandle(async ({ url, content: content2 }) => {
            return await new Promise((resolve5, reject) => {
              let element;
              if (!url) {
                element = document.createElement("style");
                element.appendChild(document.createTextNode(content2));
              } else {
                const link = document.createElement("link");
                link.rel = "stylesheet";
                link.href = url;
                element = link;
              }
              element.addEventListener("load", () => {
                resolve5(element);
              }, { once: true });
              element.addEventListener("error", (event) => {
                reject(new Error(event.message ?? "Could not load style"));
              }, { once: true });
              document.head.appendChild(element);
              return element;
            });
          }, options));
        }
        /**
         * Clicks the first element found that matches `selector`.
         *
         * @remarks
         * If `click()` triggers a navigation event and there's a separate
         * `page.waitForNavigation()` promise to be resolved, you may end up with a
         * race condition that yields unexpected results. The correct pattern for
         * click and wait for navigation is the following:
         *
         * ```ts
         * const [response] = await Promise.all([
         *   page.waitForNavigation(waitOptions),
         *   frame.click(selector, clickOptions),
         * ]);
         * ```
         *
         * @param selector - The selector to query for.
         */
        async click(selector, options = {}) {
          const env_3 = { stack: [], error: void 0, hasError: false };
          try {
            const handle = __addDisposableResource2(env_3, await this.$(selector), false);
            (0, assert_js_1.assert)(handle, `No element found for selector: ${selector}`);
            await handle.click(options);
            await handle.dispose();
          } catch (e_3) {
            env_3.error = e_3;
            env_3.hasError = true;
          } finally {
            __disposeResources2(env_3);
          }
        }
        /**
         * Focuses the first element that matches the `selector`.
         *
         * @param selector - The selector to query for.
         * @throws Throws if there's no element matching `selector`.
         */
        async focus(selector) {
          const env_4 = { stack: [], error: void 0, hasError: false };
          try {
            const handle = __addDisposableResource2(env_4, await this.$(selector), false);
            (0, assert_js_1.assert)(handle, `No element found for selector: ${selector}`);
            await handle.focus();
          } catch (e_4) {
            env_4.error = e_4;
            env_4.hasError = true;
          } finally {
            __disposeResources2(env_4);
          }
        }
        /**
         * Hovers the pointer over the center of the first element that matches the
         * `selector`.
         *
         * @param selector - The selector to query for.
         * @throws Throws if there's no element matching `selector`.
         */
        async hover(selector) {
          const env_5 = { stack: [], error: void 0, hasError: false };
          try {
            const handle = __addDisposableResource2(env_5, await this.$(selector), false);
            (0, assert_js_1.assert)(handle, `No element found for selector: ${selector}`);
            await handle.hover();
          } catch (e_5) {
            env_5.error = e_5;
            env_5.hasError = true;
          } finally {
            __disposeResources2(env_5);
          }
        }
        /**
         * Selects a set of value on the first `<select>` element that matches the
         * `selector`.
         *
         * @example
         *
         * ```ts
         * frame.select('select#colors', 'blue'); // single selection
         * frame.select('select#colors', 'red', 'green', 'blue'); // multiple selections
         * ```
         *
         * @param selector - The selector to query for.
         * @param values - The array of values to select. If the `<select>` has the
         * `multiple` attribute, all values are considered, otherwise only the first
         * one is taken into account.
         * @returns the list of values that were successfully selected.
         * @throws Throws if there's no `<select>` matching `selector`.
         */
        async select(selector, ...values) {
          const env_6 = { stack: [], error: void 0, hasError: false };
          try {
            const handle = __addDisposableResource2(env_6, await this.$(selector), false);
            (0, assert_js_1.assert)(handle, `No element found for selector: ${selector}`);
            return await handle.select(...values);
          } catch (e_6) {
            env_6.error = e_6;
            env_6.hasError = true;
          } finally {
            __disposeResources2(env_6);
          }
        }
        /**
         * Taps the first element that matches the `selector`.
         *
         * @param selector - The selector to query for.
         * @throws Throws if there's no element matching `selector`.
         */
        async tap(selector) {
          const env_7 = { stack: [], error: void 0, hasError: false };
          try {
            const handle = __addDisposableResource2(env_7, await this.$(selector), false);
            (0, assert_js_1.assert)(handle, `No element found for selector: ${selector}`);
            await handle.tap();
          } catch (e_7) {
            env_7.error = e_7;
            env_7.hasError = true;
          } finally {
            __disposeResources2(env_7);
          }
        }
        /**
         * Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character
         * in the text.
         *
         * @remarks
         * To press a special key, like `Control` or `ArrowDown`, use
         * {@link Keyboard.press}.
         *
         * @example
         *
         * ```ts
         * await frame.type('#mytextarea', 'Hello'); // Types instantly
         * await frame.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user
         * ```
         *
         * @param selector - the selector for the element to type into. If there are
         * multiple the first will be used.
         * @param text - text to type into the element
         * @param options - takes one option, `delay`, which sets the time to wait
         * between key presses in milliseconds. Defaults to `0`.
         */
        async type(selector, text, options) {
          const env_8 = { stack: [], error: void 0, hasError: false };
          try {
            const handle = __addDisposableResource2(env_8, await this.$(selector), false);
            (0, assert_js_1.assert)(handle, `No element found for selector: ${selector}`);
            await handle.type(text, options);
          } catch (e_8) {
            env_8.error = e_8;
            env_8.hasError = true;
          } finally {
            __disposeResources2(env_8);
          }
        }
        /**
         * The frame's title.
         */
        async title() {
          return await this.isolatedRealm().evaluate(() => {
            return document.title;
          });
        }
      };
    })();
    exports2.Frame = Frame;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/api/HTTPRequest.js
var require_HTTPRequest = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/api/HTTPRequest.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.STATUS_TEXTS = exports2.InterceptResolutionAction = exports2.HTTPRequest = exports2.DEFAULT_INTERCEPT_RESOLUTION_PRIORITY = void 0;
    exports2.headersArray = headersArray;
    exports2.handleError = handleError;
    var util_js_1 = require_util();
    var assert_js_1 = require_assert();
    var encoding_js_1 = require_encoding();
    exports2.DEFAULT_INTERCEPT_RESOLUTION_PRIORITY = 0;
    var HTTPRequest = class {
      /**
       * @internal
       */
      _interceptionId;
      /**
       * @internal
       */
      _failureText = null;
      /**
       * @internal
       */
      _response = null;
      /**
       * @internal
       */
      _fromMemoryCache = false;
      /**
       * @internal
       */
      _redirectChain = [];
      /**
       * @internal
       */
      interception = {
        enabled: false,
        handled: false,
        handlers: [],
        resolutionState: {
          action: InterceptResolutionAction.None
        },
        requestOverrides: {},
        response: null,
        abortReason: null
      };
      /**
       * @internal
       */
      constructor() {
      }
      /**
       * The `ContinueRequestOverrides` that will be used
       * if the interception is allowed to continue (ie, `abort()` and
       * `respond()` aren't called).
       */
      continueRequestOverrides() {
        return this.interception.requestOverrides;
      }
      /**
       * The `ResponseForRequest` that gets used if the
       * interception is allowed to respond (ie, `abort()` is not called).
       */
      responseForRequest() {
        return this.interception.response;
      }
      /**
       * The most recent reason for aborting the request
       */
      abortErrorReason() {
        return this.interception.abortReason;
      }
      /**
       * An InterceptResolutionState object describing the current resolution
       * action and priority.
       *
       * InterceptResolutionState contains:
       * action: InterceptResolutionAction
       * priority?: number
       *
       * InterceptResolutionAction is one of: `abort`, `respond`, `continue`,
       * `disabled`, `none`, or `already-handled`.
       */
      interceptResolutionState() {
        if (!this.interception.enabled) {
          return { action: InterceptResolutionAction.Disabled };
        }
        if (this.interception.handled) {
          return { action: InterceptResolutionAction.AlreadyHandled };
        }
        return { ...this.interception.resolutionState };
      }
      /**
       * Is `true` if the intercept resolution has already been handled,
       * `false` otherwise.
       */
      isInterceptResolutionHandled() {
        return this.interception.handled;
      }
      /**
       * Adds an async request handler to the processing queue.
       * Deferred handlers are not guaranteed to execute in any particular order,
       * but they are guaranteed to resolve before the request interception
       * is finalized.
       */
      enqueueInterceptAction(pendingHandler) {
        this.interception.handlers.push(pendingHandler);
      }
      /**
       * Awaits pending interception handlers and then decides how to fulfill
       * the request interception.
       */
      async finalizeInterceptions() {
        await this.interception.handlers.reduce((promiseChain, interceptAction) => {
          return promiseChain.then(interceptAction);
        }, Promise.resolve());
        this.interception.handlers = [];
        const { action } = this.interceptResolutionState();
        switch (action) {
          case "abort":
            return await this._abort(this.interception.abortReason);
          case "respond":
            if (this.interception.response === null) {
              throw new Error("Response is missing for the interception");
            }
            return await this._respond(this.interception.response);
          case "continue":
            return await this._continue(this.interception.requestOverrides);
        }
      }
      /**
       * @internal
       */
      verifyInterception() {
        (0, assert_js_1.assert)(this.interception.enabled, "Request Interception is not enabled!");
        (0, assert_js_1.assert)(!this.interception.handled, "Request is already handled!");
      }
      /**
       * Continues request with optional request overrides.
       *
       * @example
       *
       * ```ts
       * await page.setRequestInterception(true);
       * page.on('request', request => {
       *   // Override headers
       *   const headers = Object.assign({}, request.headers(), {
       *     foo: 'bar', // set "foo" header
       *     origin: undefined, // remove "origin" header
       *   });
       *   request.continue({headers});
       * });
       * ```
       *
       * @param overrides - optional overrides to apply to the request.
       * @param priority - If provided, intercept is resolved using cooperative
       * handling rules. Otherwise, intercept is resolved immediately.
       *
       * @remarks
       *
       * To use this, request interception should be enabled with
       * {@link Page.setRequestInterception}.
       *
       * Exception is immediately thrown if the request interception is not enabled.
       */
      async continue(overrides = {}, priority) {
        this.verifyInterception();
        if (!this.canBeIntercepted()) {
          return;
        }
        if (priority === void 0) {
          return await this._continue(overrides);
        }
        this.interception.requestOverrides = overrides;
        if (this.interception.resolutionState.priority === void 0 || priority > this.interception.resolutionState.priority) {
          this.interception.resolutionState = {
            action: InterceptResolutionAction.Continue,
            priority
          };
          return;
        }
        if (priority === this.interception.resolutionState.priority) {
          if (this.interception.resolutionState.action === "abort" || this.interception.resolutionState.action === "respond") {
            return;
          }
          this.interception.resolutionState.action = InterceptResolutionAction.Continue;
        }
        return;
      }
      /**
       * Fulfills a request with the given response.
       *
       * @example
       * An example of fulfilling all requests with 404 responses:
       *
       * ```ts
       * await page.setRequestInterception(true);
       * page.on('request', request => {
       *   request.respond({
       *     status: 404,
       *     contentType: 'text/plain',
       *     body: 'Not Found!',
       *   });
       * });
       * ```
       *
       * NOTE: Mocking responses for dataURL requests is not supported.
       * Calling `request.respond` for a dataURL request is a noop.
       *
       * @param response - the response to fulfill the request with.
       * @param priority - If provided, intercept is resolved using
       * cooperative handling rules. Otherwise, intercept is resolved
       * immediately.
       *
       * @remarks
       *
       * To use this, request
       * interception should be enabled with {@link Page.setRequestInterception}.
       *
       * Exception is immediately thrown if the request interception is not enabled.
       */
      async respond(response, priority) {
        this.verifyInterception();
        if (!this.canBeIntercepted()) {
          return;
        }
        if (priority === void 0) {
          return await this._respond(response);
        }
        this.interception.response = response;
        if (this.interception.resolutionState.priority === void 0 || priority > this.interception.resolutionState.priority) {
          this.interception.resolutionState = {
            action: InterceptResolutionAction.Respond,
            priority
          };
          return;
        }
        if (priority === this.interception.resolutionState.priority) {
          if (this.interception.resolutionState.action === "abort") {
            return;
          }
          this.interception.resolutionState.action = InterceptResolutionAction.Respond;
        }
      }
      /**
       * Aborts a request.
       *
       * @param errorCode - optional error code to provide.
       * @param priority - If provided, intercept is resolved using
       * cooperative handling rules. Otherwise, intercept is resolved
       * immediately.
       *
       * @remarks
       *
       * To use this, request interception should be enabled with
       * {@link Page.setRequestInterception}. If it is not enabled, this method will
       * throw an exception immediately.
       */
      async abort(errorCode = "failed", priority) {
        this.verifyInterception();
        if (!this.canBeIntercepted()) {
          return;
        }
        const errorReason = errorReasons[errorCode];
        (0, assert_js_1.assert)(errorReason, "Unknown error code: " + errorCode);
        if (priority === void 0) {
          return await this._abort(errorReason);
        }
        this.interception.abortReason = errorReason;
        if (this.interception.resolutionState.priority === void 0 || priority >= this.interception.resolutionState.priority) {
          this.interception.resolutionState = {
            action: InterceptResolutionAction.Abort,
            priority
          };
          return;
        }
      }
      /**
       * @internal
       */
      static getResponse(body) {
        const byteBody = (0, util_js_1.isString)(body) ? new TextEncoder().encode(body) : body;
        return {
          contentLength: byteBody.byteLength,
          base64: (0, encoding_js_1.typedArrayToBase64)(byteBody)
        };
      }
    };
    exports2.HTTPRequest = HTTPRequest;
    var InterceptResolutionAction;
    (function(InterceptResolutionAction2) {
      InterceptResolutionAction2["Abort"] = "abort";
      InterceptResolutionAction2["Respond"] = "respond";
      InterceptResolutionAction2["Continue"] = "continue";
      InterceptResolutionAction2["Disabled"] = "disabled";
      InterceptResolutionAction2["None"] = "none";
      InterceptResolutionAction2["AlreadyHandled"] = "already-handled";
    })(InterceptResolutionAction || (exports2.InterceptResolutionAction = InterceptResolutionAction = {}));
    function headersArray(headers) {
      const result = [];
      for (const name in headers) {
        const value = headers[name];
        if (!Object.is(value, void 0)) {
          const values = Array.isArray(value) ? value : [value];
          result.push(...values.map((value2) => {
            return { name, value: value2 + "" };
          }));
        }
      }
      return result;
    }
    exports2.STATUS_TEXTS = {
      "100": "Continue",
      "101": "Switching Protocols",
      "102": "Processing",
      "103": "Early Hints",
      "200": "OK",
      "201": "Created",
      "202": "Accepted",
      "203": "Non-Authoritative Information",
      "204": "No Content",
      "205": "Reset Content",
      "206": "Partial Content",
      "207": "Multi-Status",
      "208": "Already Reported",
      "226": "IM Used",
      "300": "Multiple Choices",
      "301": "Moved Permanently",
      "302": "Found",
      "303": "See Other",
      "304": "Not Modified",
      "305": "Use Proxy",
      "306": "Switch Proxy",
      "307": "Temporary Redirect",
      "308": "Permanent Redirect",
      "400": "Bad Request",
      "401": "Unauthorized",
      "402": "Payment Required",
      "403": "Forbidden",
      "404": "Not Found",
      "405": "Method Not Allowed",
      "406": "Not Acceptable",
      "407": "Proxy Authentication Required",
      "408": "Request Timeout",
      "409": "Conflict",
      "410": "Gone",
      "411": "Length Required",
      "412": "Precondition Failed",
      "413": "Payload Too Large",
      "414": "URI Too Long",
      "415": "Unsupported Media Type",
      "416": "Range Not Satisfiable",
      "417": "Expectation Failed",
      "418": "I'm a teapot",
      "421": "Misdirected Request",
      "422": "Unprocessable Entity",
      "423": "Locked",
      "424": "Failed Dependency",
      "425": "Too Early",
      "426": "Upgrade Required",
      "428": "Precondition Required",
      "429": "Too Many Requests",
      "431": "Request Header Fields Too Large",
      "451": "Unavailable For Legal Reasons",
      "500": "Internal Server Error",
      "501": "Not Implemented",
      "502": "Bad Gateway",
      "503": "Service Unavailable",
      "504": "Gateway Timeout",
      "505": "HTTP Version Not Supported",
      "506": "Variant Also Negotiates",
      "507": "Insufficient Storage",
      "508": "Loop Detected",
      "510": "Not Extended",
      "511": "Network Authentication Required"
    };
    var errorReasons = {
      aborted: "Aborted",
      accessdenied: "AccessDenied",
      addressunreachable: "AddressUnreachable",
      blockedbyclient: "BlockedByClient",
      blockedbyresponse: "BlockedByResponse",
      connectionaborted: "ConnectionAborted",
      connectionclosed: "ConnectionClosed",
      connectionfailed: "ConnectionFailed",
      connectionrefused: "ConnectionRefused",
      connectionreset: "ConnectionReset",
      internetdisconnected: "InternetDisconnected",
      namenotresolved: "NameNotResolved",
      timedout: "TimedOut",
      failed: "Failed"
    };
    function handleError(error) {
      if (error.originalMessage.includes("Invalid header") || error.originalMessage.includes("Unsafe header") || error.originalMessage.includes('Expected "header"') || // WebDriver BiDi error for invalid values, for example, headers.
      error.originalMessage.includes("invalid argument")) {
        throw error;
      }
      (0, util_js_1.debugError)(error);
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/api/HTTPResponse.js
var require_HTTPResponse = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/api/HTTPResponse.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.HTTPResponse = void 0;
    var HTTPResponse = class {
      /**
       * @internal
       */
      constructor() {
      }
      /**
       * True if the response was successful (status in the range 200-299).
       */
      ok() {
        const status = this.status();
        return status === 0 || status >= 200 && status <= 299;
      }
      /**
       * {@inheritDoc HTTPResponse.content}
       */
      async buffer() {
        const content = await this.content();
        return Buffer.from(content);
      }
      /**
       * Promise which resolves to a text (utf8) representation of response body.
       *
       * @remarks
       *
       * This method will throw if the content is not utf-8 string
       */
      async text() {
        const content = await this.content();
        return new TextDecoder("utf-8", { fatal: true }).decode(content);
      }
      /**
       * Promise which resolves to a JSON representation of response body.
       *
       * @remarks
       *
       * This method will throw if the response body is not parsable via
       * `JSON.parse`.
       */
      async json() {
        const content = await this.text();
        return JSON.parse(content);
      }
    };
    exports2.HTTPResponse = HTTPResponse;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/util/incremental-id-generator.js
var require_incremental_id_generator = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/util/incremental-id-generator.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createIncrementalIdGenerator = createIncrementalIdGenerator;
    function createIncrementalIdGenerator() {
      let id = 0;
      return () => {
        if (id === Number.MAX_SAFE_INTEGER) {
          id = 0;
        }
        return ++id;
      };
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/api/Input.js
var require_Input = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/api/Input.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Touchscreen = exports2.Mouse = exports2.MouseButton = exports2.Keyboard = void 0;
    var Errors_js_1 = require_Errors();
    var incremental_id_generator_js_1 = require_incremental_id_generator();
    var Keyboard = class {
      /**
       * @internal
       */
      constructor() {
      }
    };
    exports2.Keyboard = Keyboard;
    exports2.MouseButton = Object.freeze({
      Left: "left",
      Right: "right",
      Middle: "middle",
      Back: "back",
      Forward: "forward"
    });
    var Mouse = class {
      /**
       * @internal
       */
      constructor() {
      }
    };
    exports2.Mouse = Mouse;
    var Touchscreen = class {
      /**
       * @internal
       */
      idGenerator = (0, incremental_id_generator_js_1.createIncrementalIdGenerator)();
      /**
       * @internal
       */
      touches = [];
      /**
       * @internal
       */
      constructor() {
      }
      /**
       * @internal
       */
      removeHandle(handle) {
        const index = this.touches.indexOf(handle);
        if (index === -1) {
          return;
        }
        this.touches.splice(index, 1);
      }
      /**
       * Dispatches a `touchstart` and `touchend` event.
       * @param x - Horizontal position of the tap.
       * @param y - Vertical position of the tap.
       */
      async tap(x, y) {
        const touch = await this.touchStart(x, y);
        await touch.end();
      }
      /**
       * Dispatches a `touchMove` event on the first touch that is active.
       * @param x - Horizontal position of the move.
       * @param y - Vertical position of the move.
       *
       * @remarks
       *
       * Not every `touchMove` call results in a `touchmove` event being emitted,
       * depending on the browser's optimizations. For example, Chrome
       * {@link https://developer.chrome.com/blog/a-more-compatible-smoother-touch/#chromes-new-model-the-throttled-async-touchmove-model | throttles}
       * touch move events.
       */
      async touchMove(x, y) {
        const touch = this.touches[0];
        if (!touch) {
          throw new Errors_js_1.TouchError("Must start a new Touch first");
        }
        return await touch.move(x, y);
      }
      /**
       * Dispatches a `touchend` event on the first touch that is active.
       */
      async touchEnd() {
        const touch = this.touches.shift();
        if (!touch) {
          throw new Errors_js_1.TouchError("Must start a new Touch first");
        }
        await touch.end();
      }
    };
    exports2.Touchscreen = Touchscreen;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/TimeoutSettings.js
var require_TimeoutSettings = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/TimeoutSettings.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.TimeoutSettings = void 0;
    var DEFAULT_TIMEOUT = 3e4;
    var TimeoutSettings = class {
      #defaultTimeout;
      #defaultNavigationTimeout;
      constructor() {
        this.#defaultTimeout = null;
        this.#defaultNavigationTimeout = null;
      }
      setDefaultTimeout(timeout) {
        this.#defaultTimeout = timeout;
      }
      setDefaultNavigationTimeout(timeout) {
        this.#defaultNavigationTimeout = timeout;
      }
      navigationTimeout() {
        if (this.#defaultNavigationTimeout !== null) {
          return this.#defaultNavigationTimeout;
        }
        if (this.#defaultTimeout !== null) {
          return this.#defaultTimeout;
        }
        return DEFAULT_TIMEOUT;
      }
      timeout() {
        if (this.#defaultTimeout !== null) {
          return this.#defaultTimeout;
        }
        return DEFAULT_TIMEOUT;
      }
    };
    exports2.TimeoutSettings = TimeoutSettings;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/api/Page.js
var require_Page = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/api/Page.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.supportedMetrics = exports2.Page = void 0;
    exports2.setDefaultScreenshotOptions = setDefaultScreenshotOptions;
    var rxjs_js_1 = require_rxjs();
    var Errors_js_1 = require_Errors();
    var EventEmitter_js_1 = require_EventEmitter();
    var TimeoutSettings_js_1 = require_TimeoutSettings();
    var util_js_1 = require_util();
    var environment_js_1 = require_environment();
    var decorators_js_1 = require_decorators();
    var disposable_js_1 = require_disposable();
    var encoding_js_1 = require_encoding();
    var locators_js_1 = require_locators();
    function setDefaultScreenshotOptions(options) {
      options.optimizeForSpeed ??= false;
      options.type ??= "png";
      options.fromSurface ??= true;
      options.fullPage ??= false;
      options.omitBackground ??= false;
      options.encoding ??= "binary";
      options.captureBeyondViewport ??= true;
    }
    var Page = (() => {
      let _classSuper = EventEmitter_js_1.EventEmitter;
      let _instanceExtraInitializers = [];
      let _screenshot_decorators;
      return class Page extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          __esDecorate2(this, null, _screenshot_decorators, { kind: "method", name: "screenshot", static: false, private: false, access: { has: (obj) => "screenshot" in obj, get: (obj) => obj.screenshot }, metadata: _metadata }, null, _instanceExtraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        /**
         * @internal
         */
        _isDragging = (__runInitializers2(this, _instanceExtraInitializers), false);
        /**
         * @internal
         */
        _timeoutSettings = new TimeoutSettings_js_1.TimeoutSettings();
        /**
         * Internal API to get an implementation-specific identifier
         * for the tab. In Chrome, it is a tab target id. If unknown,
         * returns an empty string.
         *
         * @internal
         */
        _tabId = "";
        #requestHandlers = /* @__PURE__ */ new WeakMap();
        #inflight$ = new rxjs_js_1.ReplaySubject(1);
        /**
         * @internal
         */
        constructor() {
          super();
          (0, util_js_1.fromEmitterEvent)(
            this,
            "request"
            /* PageEvent.Request */
          ).pipe((0, rxjs_js_1.mergeMap)((originalRequest) => {
            return (0, rxjs_js_1.concat)((0, rxjs_js_1.of)(1), (0, rxjs_js_1.merge)((0, util_js_1.fromEmitterEvent)(
              this,
              "requestfailed"
              /* PageEvent.RequestFailed */
            ), (0, util_js_1.fromEmitterEvent)(
              this,
              "requestfinished"
              /* PageEvent.RequestFinished */
            ), (0, util_js_1.fromEmitterEvent)(
              this,
              "response"
              /* PageEvent.Response */
            ).pipe((0, rxjs_js_1.map)((response) => {
              return response.request();
            }))).pipe((0, rxjs_js_1.filter)((request) => {
              return request.id === originalRequest.id;
            }), (0, rxjs_js_1.take)(1), (0, rxjs_js_1.map)(() => {
              return -1;
            })));
          }), (0, rxjs_js_1.mergeScan)((acc, addend) => {
            return (0, rxjs_js_1.of)(acc + addend);
          }, 0), (0, rxjs_js_1.takeUntil)((0, util_js_1.fromEmitterEvent)(
            this,
            "close"
            /* PageEvent.Close */
          )), (0, rxjs_js_1.startWith)(0)).subscribe(this.#inflight$);
        }
        /**
         * Listen to page events.
         *
         * @remarks
         * This method exists to define event typings and handle proper wireup of
         * cooperative request interception. Actual event listening and dispatching is
         * delegated to {@link EventEmitter}.
         *
         * @internal
         */
        on(type, handler) {
          if (type !== "request") {
            return super.on(type, handler);
          }
          let wrapper = this.#requestHandlers.get(handler);
          if (wrapper === void 0) {
            wrapper = (event) => {
              event.enqueueInterceptAction(() => {
                return handler(event);
              });
            };
            this.#requestHandlers.set(handler, wrapper);
          }
          return super.on(type, wrapper);
        }
        /**
         * @internal
         */
        off(type, handler) {
          if (type === "request") {
            handler = this.#requestHandlers.get(handler) || handler;
          }
          return super.off(type, handler);
        }
        /**
         * {@inheritDoc Accessibility}
         */
        get accessibility() {
          return this.mainFrame().accessibility;
        }
        locator(input) {
          if (typeof input === "string") {
            return locators_js_1.NodeLocator.create(this, input);
          } else {
            return locators_js_1.FunctionLocator.create(this, input);
          }
        }
        /**
         * A shortcut for {@link Locator.race} that does not require static imports.
         *
         * @internal
         */
        locatorRace(locators) {
          return locators_js_1.Locator.race(locators);
        }
        /**
         * Finds the first element that matches the selector. If no element matches
         * the selector, the return value resolves to `null`.
         *
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}.
         *
         * @remarks
         *
         * Shortcut for {@link Frame.$ | Page.mainFrame().$(selector) }.
         */
        async $(selector) {
          return await this.mainFrame().$(selector);
        }
        /**
         * Finds elements on the page that match the selector. If no elements
         * match the selector, the return value resolves to `[]`.
         *
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}.
         *
         * @remarks
         *
         * Shortcut for {@link Frame.$$ | Page.mainFrame().$$(selector) }.
         */
        async $$(selector, options) {
          return await this.mainFrame().$$(selector, options);
        }
        /**
         * @remarks
         *
         * The only difference between {@link Page.evaluate | page.evaluate} and
         * `page.evaluateHandle` is that `evaluateHandle` will return the value
         * wrapped in an in-page object.
         *
         * If the function passed to `page.evaluateHandle` returns a Promise, the
         * function will wait for the promise to resolve and return its value.
         *
         * You can pass a string instead of a function (although functions are
         * recommended as they are easier to debug and use with TypeScript):
         *
         * @example
         *
         * ```ts
         * const aHandle = await page.evaluateHandle('document');
         * ```
         *
         * @example
         * {@link JSHandle} instances can be passed as arguments to the `pageFunction`:
         *
         * ```ts
         * const aHandle = await page.evaluateHandle(() => document.body);
         * const resultHandle = await page.evaluateHandle(
         *   body => body.innerHTML,
         *   aHandle,
         * );
         * console.log(await resultHandle.jsonValue());
         * await resultHandle.dispose();
         * ```
         *
         * Most of the time this function returns a {@link JSHandle},
         * but if `pageFunction` returns a reference to an element,
         * you instead get an {@link ElementHandle} back:
         *
         * @example
         *
         * ```ts
         * const button = await page.evaluateHandle(() =>
         *   document.querySelector('button'),
         * );
         * // can call `click` because `button` is an `ElementHandle`
         * await button.click();
         * ```
         *
         * The TypeScript definitions assume that `evaluateHandle` returns
         * a `JSHandle`, but if you know it's going to return an
         * `ElementHandle`, pass it as the generic argument:
         *
         * ```ts
         * const button = await page.evaluateHandle<ElementHandle>(...);
         * ```
         *
         * @param pageFunction - a function that is run within the page
         * @param args - arguments to be passed to the pageFunction
         */
        async evaluateHandle(pageFunction, ...args2) {
          pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.evaluateHandle.name, pageFunction);
          return await this.mainFrame().evaluateHandle(pageFunction, ...args2);
        }
        /**
         * This method finds the first element within the page that matches the selector
         * and passes the result as the first argument to the `pageFunction`.
         *
         * @remarks
         *
         * If no element is found matching `selector`, the method will throw an error.
         *
         * If `pageFunction` returns a promise `$eval` will wait for the promise to
         * resolve and then return its value.
         *
         * @example
         *
         * ```ts
         * const searchValue = await page.$eval('#search', el => el.value);
         * const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
         * const html = await page.$eval('.main-container', el => el.outerHTML);
         * ```
         *
         * If you are using TypeScript, you may have to provide an explicit type to the
         * first argument of the `pageFunction`.
         * By default it is typed as `Element`, but you may need to provide a more
         * specific sub-type:
         *
         * @example
         *
         * ```ts
         * // if you don't provide HTMLInputElement here, TS will error
         * // as `value` is not on `Element`
         * const searchValue = await page.$eval(
         *   '#search',
         *   (el: HTMLInputElement) => el.value,
         * );
         * ```
         *
         * The compiler should be able to infer the return type
         * from the `pageFunction` you provide. If it is unable to, you can use the generic
         * type to tell the compiler what return type you expect from `$eval`:
         *
         * @example
         *
         * ```ts
         * // The compiler can infer the return type in this case, but if it can't
         * // or if you want to be more explicit, provide it as the generic type.
         * const searchValue = await page.$eval<string>(
         *   '#search',
         *   (el: HTMLInputElement) => el.value,
         * );
         * ```
         *
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}.
         * @param pageFunction - the function to be evaluated in the page context.
         * Will be passed the result of the element matching the selector as its
         * first argument.
         * @param args - any additional arguments to pass through to `pageFunction`.
         *
         * @returns The result of calling `pageFunction`. If it returns an element it
         * is wrapped in an {@link ElementHandle}, else the raw value itself is
         * returned.
         */
        async $eval(selector, pageFunction, ...args2) {
          pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.$eval.name, pageFunction);
          return await this.mainFrame().$eval(selector, pageFunction, ...args2);
        }
        /**
         * This method returns all elements matching the selector and passes the
         * resulting array as the first argument to the `pageFunction`.
         *
         * @remarks
         * If `pageFunction` returns a promise `$$eval` will wait for the promise to
         * resolve and then return its value.
         *
         * @example
         *
         * ```ts
         * // get the amount of divs on the page
         * const divCount = await page.$$eval('div', divs => divs.length);
         *
         * // get the text content of all the `.options` elements:
         * const options = await page.$$eval('div > span.options', options => {
         *   return options.map(option => option.textContent);
         * });
         * ```
         *
         * If you are using TypeScript, you may have to provide an explicit type to the
         * first argument of the `pageFunction`.
         * By default it is typed as `Element[]`, but you may need to provide a more
         * specific sub-type:
         *
         * @example
         *
         * ```ts
         * await page.$$eval('input', elements => {
         *   return elements.map(e => e.value);
         * });
         * ```
         *
         * The compiler should be able to infer the return type
         * from the `pageFunction` you provide. If it is unable to, you can use the generic
         * type to tell the compiler what return type you expect from `$$eval`:
         *
         * @example
         *
         * ```ts
         * const allInputValues = await page.$$eval('input', elements =>
         *   elements.map(e => e.textContent),
         * );
         * ```
         *
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}.
         * @param pageFunction - the function to be evaluated in the page context.
         * Will be passed an array of matching elements as its first argument.
         * @param args - any additional arguments to pass through to `pageFunction`.
         *
         * @returns The result of calling `pageFunction`. If it returns an element it
         * is wrapped in an {@link ElementHandle}, else the raw value itself is
         * returned.
         */
        async $$eval(selector, pageFunction, ...args2) {
          pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.$$eval.name, pageFunction);
          return await this.mainFrame().$$eval(selector, pageFunction, ...args2);
        }
        /**
         * Adds a `<script>` tag into the page with the desired URL or content.
         *
         * @remarks
         * Shortcut for
         * {@link Frame.addScriptTag | page.mainFrame().addScriptTag(options)}.
         *
         * @param options - Options for the script.
         * @returns An {@link ElementHandle | element handle} to the injected
         * `<script>` element.
         */
        async addScriptTag(options) {
          return await this.mainFrame().addScriptTag(options);
        }
        async addStyleTag(options) {
          return await this.mainFrame().addStyleTag(options);
        }
        /**
         * The page's URL.
         *
         * @remarks
         *
         * Shortcut for {@link Frame.url | page.mainFrame().url()}.
         */
        url() {
          return this.mainFrame().url();
        }
        /**
         * The full HTML contents of the page, including the DOCTYPE.
         */
        async content() {
          return await this.mainFrame().content();
        }
        /**
         * Set the content of the page.
         *
         * @param html - HTML markup to assign to the page.
         * @param options - Parameters that has some properties.
         */
        async setContent(html, options) {
          await this.mainFrame().setContent(html, options);
        }
        /**
         * {@inheritDoc Frame.goto}
         */
        async goto(url, options) {
          return await this.mainFrame().goto(url, options);
        }
        /**
         * Waits for the page to navigate to a new URL or to reload. It is useful when
         * you run code that will indirectly cause the page to navigate.
         *
         * @example
         *
         * ```ts
         * const [response] = await Promise.all([
         *   page.waitForNavigation(), // The promise resolves after navigation has finished
         *   page.click('a.my-link'), // Clicking the link will indirectly cause a navigation
         * ]);
         * ```
         *
         * @remarks
         *
         * Usage of the
         * {@link https://developer.mozilla.org/en-US/docs/Web/API/History_API | History API}
         * to change the URL is considered a navigation.
         *
         * @param options - Navigation parameters which might have the following
         * properties:
         * @returns A `Promise` which resolves to the main resource response.
         *
         * - In case of multiple redirects, the navigation will resolve with the
         *   response of the last redirect.
         * - In case of navigation to a different anchor or navigation due to History
         *   API usage, the navigation will resolve with `null`.
         */
        async waitForNavigation(options = {}) {
          return await this.mainFrame().waitForNavigation(options);
        }
        /**
         * @param urlOrPredicate - A URL or predicate to wait for
         * @param options - Optional waiting parameters
         * @returns Promise which resolves to the matched request
         * @example
         *
         * ```ts
         * const firstRequest = await page.waitForRequest(
         *   'https://example.com/resource',
         * );
         * const finalRequest = await page.waitForRequest(
         *   request => request.url() === 'https://example.com',
         * );
         * return finalRequest.response()?.ok();
         * ```
         *
         * @remarks
         * Optional Waiting Parameters have:
         *
         * - `timeout`: Maximum wait time in milliseconds, defaults to `30` seconds, pass
         *   `0` to disable the timeout. The default value can be changed by using the
         *   {@link Page.setDefaultTimeout} method.
         *
         * - `signal`: A signal object that allows you to cancel a waitForRequest call.
         */
        waitForRequest(urlOrPredicate, options = {}) {
          const { timeout: ms = this._timeoutSettings.timeout(), signal } = options;
          if (typeof urlOrPredicate === "string") {
            const url = urlOrPredicate;
            urlOrPredicate = (request) => {
              return request.url() === url;
            };
          }
          const observable$ = (0, util_js_1.fromEmitterEvent)(
            this,
            "request"
            /* PageEvent.Request */
          ).pipe((0, util_js_1.filterAsync)(urlOrPredicate), (0, rxjs_js_1.raceWith)((0, util_js_1.timeout)(ms), (0, util_js_1.fromAbortSignal)(signal), (0, util_js_1.fromEmitterEvent)(
            this,
            "close"
            /* PageEvent.Close */
          ).pipe((0, rxjs_js_1.map)(() => {
            throw new Errors_js_1.TargetCloseError("Page closed!");
          }))));
          return (0, rxjs_js_1.firstValueFrom)(observable$);
        }
        /**
         * @param urlOrPredicate - A URL or predicate to wait for.
         * @param options - Optional waiting parameters
         * @returns Promise which resolves to the matched response.
         * @example
         *
         * ```ts
         * const firstResponse = await page.waitForResponse(
         *   'https://example.com/resource',
         * );
         * const finalResponse = await page.waitForResponse(
         *   response =>
         *     response.url() === 'https://example.com' && response.status() === 200,
         * );
         * const finalResponse = await page.waitForResponse(async response => {
         *   return (await response.text()).includes('<html>');
         * });
         * return finalResponse.ok();
         * ```
         *
         * @remarks
         * Optional Parameter have:
         *
         * - `timeout`: Maximum wait time in milliseconds, defaults to `30` seconds,
         *   pass `0` to disable the timeout. The default value can be changed by using
         *   the {@link Page.setDefaultTimeout} method.
         *
         * - `signal`: A signal object that allows you to cancel a waitForResponse call.
         */
        waitForResponse(urlOrPredicate, options = {}) {
          const { timeout: ms = this._timeoutSettings.timeout(), signal } = options;
          if (typeof urlOrPredicate === "string") {
            const url = urlOrPredicate;
            urlOrPredicate = (response) => {
              return response.url() === url;
            };
          }
          const observable$ = (0, util_js_1.fromEmitterEvent)(
            this,
            "response"
            /* PageEvent.Response */
          ).pipe((0, util_js_1.filterAsync)(urlOrPredicate), (0, rxjs_js_1.raceWith)((0, util_js_1.timeout)(ms), (0, util_js_1.fromAbortSignal)(signal), (0, util_js_1.fromEmitterEvent)(
            this,
            "close"
            /* PageEvent.Close */
          ).pipe((0, rxjs_js_1.map)(() => {
            throw new Errors_js_1.TargetCloseError("Page closed!");
          }))));
          return (0, rxjs_js_1.firstValueFrom)(observable$);
        }
        /**
         * Waits for the network to be idle.
         *
         * @remarks The function will always wait at least the
         * set {@link WaitForNetworkIdleOptions.idleTime | IdleTime}.
         *
         * @param options - Options to configure waiting behavior.
         * @returns A promise which resolves once the network is idle.
         */
        waitForNetworkIdle(options = {}) {
          return (0, rxjs_js_1.firstValueFrom)(this.waitForNetworkIdle$(options));
        }
        /**
         * @internal
         */
        waitForNetworkIdle$(options = {}) {
          const { timeout: ms = this._timeoutSettings.timeout(), idleTime = util_js_1.NETWORK_IDLE_TIME, concurrency = 0, signal } = options;
          return this.#inflight$.pipe((0, rxjs_js_1.map)((inflight) => {
            return inflight > concurrency;
          }), (0, rxjs_js_1.distinctUntilChanged)(), (0, rxjs_js_1.switchMap)((isInflightOverConcurrency) => {
            if (isInflightOverConcurrency) {
              return rxjs_js_1.EMPTY;
            }
            return (0, rxjs_js_1.timer)(idleTime);
          }), (0, rxjs_js_1.map)(() => {
          }), (0, rxjs_js_1.raceWith)((0, util_js_1.timeout)(ms), (0, util_js_1.fromAbortSignal)(signal), (0, util_js_1.fromEmitterEvent)(
            this,
            "close"
            /* PageEvent.Close */
          ).pipe((0, rxjs_js_1.map)(() => {
            throw new Errors_js_1.TargetCloseError("Page closed!");
          }))));
        }
        /**
         * Waits for a frame matching the given conditions to appear.
         *
         * @example
         *
         * ```ts
         * const frame = await page.waitForFrame(async frame => {
         *   const frameElement = await frame.frameElement();
         *   if (!frameElement) {
         *     return false;
         *   }
         *   const name = await frameElement.evaluate(el => el.getAttribute('name'));
         *   return name === 'test';
         * });
         * ```
         */
        async waitForFrame(urlOrPredicate, options = {}) {
          const { timeout: ms = this.getDefaultTimeout(), signal } = options;
          const predicate = (0, util_js_1.isString)(urlOrPredicate) ? (frame) => {
            return urlOrPredicate === frame.url();
          } : urlOrPredicate;
          return await (0, rxjs_js_1.firstValueFrom)((0, rxjs_js_1.merge)((0, util_js_1.fromEmitterEvent)(
            this,
            "frameattached"
            /* PageEvent.FrameAttached */
          ), (0, util_js_1.fromEmitterEvent)(
            this,
            "framenavigated"
            /* PageEvent.FrameNavigated */
          ), (0, rxjs_js_1.from)(this.frames())).pipe((0, util_js_1.filterAsync)(predicate), (0, rxjs_js_1.first)(), (0, rxjs_js_1.raceWith)((0, util_js_1.timeout)(ms), (0, util_js_1.fromAbortSignal)(signal), (0, util_js_1.fromEmitterEvent)(
            this,
            "close"
            /* PageEvent.Close */
          ).pipe((0, rxjs_js_1.map)(() => {
            throw new Errors_js_1.TargetCloseError("Page closed.");
          })))));
        }
        /**
         * Emulates a given device's metrics and user agent.
         *
         * To aid emulation, Puppeteer provides a list of known devices that can be
         * via {@link KnownDevices}.
         *
         * @remarks
         * This method is a shortcut for calling two methods:
         * {@link Page.(setUserAgent:2) } and {@link Page.setViewport}.
         *
         * This method will resize the page. A lot of websites don't expect phones to
         * change size, so you should emulate before navigating to the page.
         *
         * @example
         *
         * ```ts
         * import {KnownDevices} from 'puppeteer';
         * const iPhone = KnownDevices['iPhone 15 Pro'];
         *
         * const browser = await puppeteer.launch();
         * const page = await browser.newPage();
         * await page.emulate(iPhone);
         * await page.goto('https://www.google.com');
         * // other actions...
         * await browser.close();
         * ```
         */
        async emulate(device) {
          await Promise.all([
            this.setUserAgent({ userAgent: device.userAgent }),
            this.setViewport(device.viewport)
          ]);
        }
        /**
         * Evaluates a function in the page's context and returns the result.
         *
         * If the function passed to `page.evaluate` returns a Promise, the
         * function will wait for the promise to resolve and return its value.
         *
         * @example
         *
         * ```ts
         * const result = await frame.evaluate(() => {
         *   return Promise.resolve(8 * 7);
         * });
         * console.log(result); // prints "56"
         * ```
         *
         * You can pass a string instead of a function (although functions are
         * recommended as they are easier to debug and use with TypeScript):
         *
         * @example
         *
         * ```ts
         * const aHandle = await page.evaluate('1 + 2');
         * ```
         *
         * To get the best TypeScript experience, you should pass in as the
         * generic the type of `pageFunction`:
         *
         * ```ts
         * const aHandle = await page.evaluate(() => 2);
         * ```
         *
         * @example
         *
         * {@link ElementHandle} instances (including {@link JSHandle}s) can be passed
         * as arguments to the `pageFunction`:
         *
         * ```ts
         * const bodyHandle = await page.$('body');
         * const html = await page.evaluate(body => body.innerHTML, bodyHandle);
         * await bodyHandle.dispose();
         * ```
         *
         * @param pageFunction - a function that is run within the page
         * @param args - arguments to be passed to the pageFunction
         *
         * @returns the return value of `pageFunction`.
         */
        async evaluate(pageFunction, ...args2) {
          pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.evaluate.name, pageFunction);
          return await this.mainFrame().evaluate(pageFunction, ...args2);
        }
        /**
         * @internal
         */
        async _maybeWriteTypedArrayToFile(path2, typedArray) {
          if (!path2) {
            return;
          }
          await environment_js_1.environment.value.fs.promises.writeFile(path2, typedArray);
        }
        /**
         * Captures a screencast of this {@link Page | page}.
         *
         * @example
         * Recording a {@link Page | page}:
         *
         * ```
         * import puppeteer from 'puppeteer';
         *
         * // Launch a browser
         * const browser = await puppeteer.launch();
         *
         * // Create a new page
         * const page = await browser.newPage();
         *
         * // Go to your site.
         * await page.goto("https://www.example.com");
         *
         * // Start recording.
         * const recorder = await page.screencast({path: 'recording.webm'});
         *
         * // Do something.
         *
         * // Stop recording.
         * await recorder.stop();
         *
         * browser.close();
         * ```
         *
         * @param options - Configures screencast behavior.
         *
         * @experimental
         *
         * @remarks
         *
         * By default, all recordings will be {@link https://www.webmproject.org/ | WebM} format using
         * the {@link https://www.webmproject.org/vp9/ | VP9} video codec, with a frame rate of 30 FPS.
         *
         * You must have {@link https://ffmpeg.org/ | ffmpeg} installed on your system.
         */
        async screencast(options = {}) {
          const ScreenRecorder = environment_js_1.environment.value.ScreenRecorder;
          const [width, height, devicePixelRatio] = await this.#getNativePixelDimensions();
          let crop;
          if (options.crop) {
            const { x, y, width: cropWidth, height: cropHeight } = roundRectangle(normalizeRectangle(options.crop));
            if (x < 0 || y < 0) {
              throw new Error(`\`crop.x\` and \`crop.y\` must be greater than or equal to 0.`);
            }
            if (cropWidth <= 0 || cropHeight <= 0) {
              throw new Error(`\`crop.height\` and \`crop.width\` must be greater than or equal to 0.`);
            }
            const viewportWidth = width / devicePixelRatio;
            const viewportHeight = height / devicePixelRatio;
            if (x + cropWidth > viewportWidth) {
              throw new Error(`\`crop.width\` cannot be larger than the viewport width (${viewportWidth}).`);
            }
            if (y + cropHeight > viewportHeight) {
              throw new Error(`\`crop.height\` cannot be larger than the viewport height (${viewportHeight}).`);
            }
            crop = {
              x: x * devicePixelRatio,
              y: y * devicePixelRatio,
              width: cropWidth * devicePixelRatio,
              height: cropHeight * devicePixelRatio
            };
          }
          if (options.speed !== void 0 && options.speed <= 0) {
            throw new Error(`\`speed\` must be greater than 0.`);
          }
          if (options.scale !== void 0 && options.scale <= 0) {
            throw new Error(`\`scale\` must be greater than 0.`);
          }
          const recorder = new ScreenRecorder(this, width, height, {
            ...options,
            crop
          });
          try {
            await this._startScreencast();
          } catch (error) {
            void recorder.stop();
            throw error;
          }
          if (options.path) {
            const { createWriteStream } = environment_js_1.environment.value.fs;
            const stream = createWriteStream(options.path, "binary");
            recorder.pipe(stream);
          }
          return recorder;
        }
        #screencastSessionCount = 0;
        #startScreencastPromise;
        /**
         * @internal
         */
        async _startScreencast() {
          ++this.#screencastSessionCount;
          if (!this.#startScreencastPromise) {
            this.#startScreencastPromise = this.mainFrame().client.send("Page.startScreencast", { format: "png" }).then(() => {
              return new Promise((resolve5) => {
                return this.mainFrame().client.once("Page.screencastFrame", () => {
                  return resolve5();
                });
              });
            });
          }
          await this.#startScreencastPromise;
        }
        /**
         * @internal
         */
        async _stopScreencast() {
          --this.#screencastSessionCount;
          if (!this.#startScreencastPromise) {
            return;
          }
          this.#startScreencastPromise = void 0;
          if (this.#screencastSessionCount === 0) {
            await this.mainFrame().client.send("Page.stopScreencast");
          }
        }
        /**
         * Gets the native, non-emulated dimensions of the viewport.
         */
        async #getNativePixelDimensions() {
          const env_1 = { stack: [], error: void 0, hasError: false };
          try {
            const viewport = this.viewport();
            const stack = __addDisposableResource2(env_1, new disposable_js_1.DisposableStack(), false);
            if (viewport && viewport.deviceScaleFactor !== 0) {
              await this.setViewport({ ...viewport, deviceScaleFactor: 0 });
              stack.defer(() => {
                void this.setViewport(viewport).catch(util_js_1.debugError);
              });
            }
            return await this.mainFrame().isolatedRealm().evaluate(() => {
              return [
                window.visualViewport.width * window.devicePixelRatio,
                window.visualViewport.height * window.devicePixelRatio,
                window.devicePixelRatio
              ];
            });
          } catch (e_1) {
            env_1.error = e_1;
            env_1.hasError = true;
          } finally {
            __disposeResources2(env_1);
          }
        }
        async screenshot(userOptions = {}) {
          const env_2 = { stack: [], error: void 0, hasError: false };
          try {
            const _guard = __addDisposableResource2(env_2, await this.browserContext().startScreenshot(), false);
            const options = {
              ...userOptions,
              clip: userOptions.clip ? {
                ...userOptions.clip
              } : void 0
            };
            if (options.type === void 0 && options.path !== void 0) {
              const filePath = options.path;
              const extension = filePath.slice(filePath.lastIndexOf(".") + 1).toLowerCase();
              switch (extension) {
                case "png":
                  options.type = "png";
                  break;
                case "jpeg":
                case "jpg":
                  options.type = "jpeg";
                  break;
                case "webp":
                  options.type = "webp";
                  break;
              }
            }
            if (options.quality !== void 0) {
              if (options.quality < 0 || options.quality > 100) {
                throw new Error(`Expected 'quality' (${options.quality}) to be between 0 and 100, inclusive.`);
              }
              if (options.type === void 0 || !["jpeg", "webp"].includes(options.type)) {
                throw new Error(`${options.type ?? "png"} screenshots do not support 'quality'.`);
              }
            }
            if (options.clip) {
              if (options.clip.width <= 0) {
                throw new Error("'width' in 'clip' must be positive.");
              }
              if (options.clip.height <= 0) {
                throw new Error("'height' in 'clip' must be positive.");
              }
            }
            setDefaultScreenshotOptions(options);
            const stack = __addDisposableResource2(env_2, new disposable_js_1.AsyncDisposableStack(), true);
            if (options.clip) {
              if (options.fullPage) {
                throw new Error("'clip' and 'fullPage' are mutually exclusive");
              }
              options.clip = roundRectangle(normalizeRectangle(options.clip));
            } else {
              if (options.fullPage) {
                if (!options.captureBeyondViewport) {
                  const scrollDimensions = await this.mainFrame().isolatedRealm().evaluate(() => {
                    const element = document.documentElement;
                    return {
                      width: element.scrollWidth,
                      height: element.scrollHeight
                    };
                  });
                  const viewport = this.viewport();
                  await this.setViewport({
                    ...viewport,
                    ...scrollDimensions
                  });
                  stack.defer(async () => {
                    await this.setViewport(viewport).catch(util_js_1.debugError);
                  });
                }
              } else {
                options.captureBeyondViewport = false;
              }
            }
            const data = await this._screenshot(options);
            if (options.encoding === "base64") {
              return data;
            }
            const typedArray = (0, encoding_js_1.stringToTypedArray)(data, true);
            await this._maybeWriteTypedArrayToFile(options.path, typedArray);
            return typedArray;
          } catch (e_2) {
            env_2.error = e_2;
            env_2.hasError = true;
          } finally {
            const result_1 = __disposeResources2(env_2);
            if (result_1)
              await result_1;
          }
        }
        /**
         * The page's title
         *
         * @remarks
         *
         * Shortcut for {@link Frame.title | page.mainFrame().title()}.
         */
        async title() {
          return await this.mainFrame().title();
        }
        /**
         * This method fetches an element with `selector`, scrolls it into view if
         * needed, and then uses {@link Page.mouse} to click in the center of the
         * element. If there's no element matching `selector`, the method throws an
         * error.
         *
         * @remarks
         *
         * Bear in mind that if `click()` triggers a navigation event and
         * there's a separate `page.waitForNavigation()` promise to be resolved, you
         * may end up with a race condition that yields unexpected results. The
         * correct pattern for click and wait for navigation is the following:
         *
         * ```ts
         * const [response] = await Promise.all([
         *   page.waitForNavigation(waitOptions),
         *   page.click(selector, clickOptions),
         * ]);
         * ```
         *
         * Shortcut for {@link Frame.click | page.mainFrame().click(selector[, options]) }.
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}. If there are
         * multiple elements satisfying the `selector`, the first will be clicked
         * @param options - `Object`
         * @returns Promise which resolves when the element matching `selector` is
         * successfully clicked. The Promise will be rejected if there is no element
         * matching `selector`.
         */
        click(selector, options) {
          return this.mainFrame().click(selector, options);
        }
        /**
         * This method fetches an element with `selector` and focuses it. If
         * there's no element matching `selector`, the method throws an error.
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}.
         * If there are multiple elements satisfying the selector, the first
         * will be focused.
         * @returns Promise which resolves when the element matching selector
         * is successfully focused. The promise will be rejected if there is
         * no element matching selector.
         *
         * @remarks
         *
         * Shortcut for
         * {@link Frame.focus | page.mainFrame().focus(selector)}.
         */
        focus(selector) {
          return this.mainFrame().focus(selector);
        }
        /**
         * This method fetches an element with `selector`, scrolls it into view if
         * needed, and then uses {@link Page.mouse}
         * to hover over the center of the element.
         * If there's no element matching `selector`, the method throws an error.
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}. If there are
         * multiple elements satisfying the `selector`, the first will be hovered.
         * @returns Promise which resolves when the element matching `selector` is
         * successfully hovered. Promise gets rejected if there's no element matching
         * `selector`.
         *
         * @remarks
         *
         * Shortcut for {@link Page.hover | page.mainFrame().hover(selector)}.
         */
        hover(selector) {
          return this.mainFrame().hover(selector);
        }
        /**
         * Triggers a `change` and `input` event once all the provided options have been
         * selected. If there's no `<select>` element matching `selector`, the method
         * throws an error.
         *
         * @example
         *
         * ```ts
         * page.select('select#colors', 'blue'); // single selection
         * page.select('select#colors', 'red', 'green', 'blue'); // multiple selections
         * ```
         *
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}.
         * @param values - Values of options to select. If the `<select>` has the
         * `multiple` attribute, all values are considered, otherwise only the first one
         * is taken into account.
         * @returns
         *
         * @remarks
         *
         * Shortcut for {@link Frame.select | page.mainFrame().select()}
         */
        select(selector, ...values) {
          return this.mainFrame().select(selector, ...values);
        }
        /**
         * This method fetches an element with `selector`, scrolls it into view if
         * needed, and then uses {@link Page.touchscreen}
         * to tap in the center of the element.
         * If there's no element matching `selector`, the method throws an error.
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}. If there are multiple elements satisfying the
         * selector, the first will be tapped.
         *
         * @remarks
         *
         * Shortcut for {@link Frame.tap | page.mainFrame().tap(selector)}.
         */
        tap(selector) {
          return this.mainFrame().tap(selector);
        }
        /**
         * Sends a `keydown`, `keypress/input`, and `keyup` event for each character
         * in the text.
         *
         * To press a special key, like `Control` or `ArrowDown`, use {@link Keyboard.press}.
         * @example
         *
         * ```ts
         * await page.type('#mytextarea', 'Hello');
         * // Types instantly
         * await page.type('#mytextarea', 'World', {delay: 100});
         * // Types slower, like a user
         * ```
         *
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}.
         * @param text - A text to type into a focused element.
         * @param options - have property `delay` which is the Time to wait between
         * key presses in milliseconds. Defaults to `0`.
         * @returns
         */
        type(selector, text, options) {
          return this.mainFrame().type(selector, text, options);
        }
        /**
         * Wait for the `selector` to appear in page. If at the moment of calling the
         * method the `selector` already exists, the method will return immediately. If
         * the `selector` doesn't appear after the `timeout` milliseconds of waiting, the
         * function will throw.
         *
         * @example
         * This method works across navigations:
         *
         * ```ts
         * import puppeteer from 'puppeteer';
         *
         * const browser = await puppeteer.launch();
         * const page = await browser.newPage();
         * let currentURL;
         * page
         *   .waitForSelector('img')
         *   .then(() => console.log('First URL with image: ' + currentURL));
         * for (currentURL of [
         *   'https://example.com',
         *   'https://google.com',
         *   'https://bbc.com',
         * ]) {
         *   await page.goto(currentURL);
         * }
         * await browser.close();
         * ```
         *
         * @param selector -
         * {@link https://pptr.dev/guides/page-interactions#selectors | selector}
         * to query the page for.
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | CSS selectors}
         * can be passed as-is and a
         * {@link https://pptr.dev/guides/page-interactions#non-css-selectors | Puppeteer-specific selector syntax}
         * allows querying by
         * {@link https://pptr.dev/guides/page-interactions#text-selectors--p-text | text},
         * {@link https://pptr.dev/guides/page-interactions#aria-selectors--p-aria | a11y role and name},
         * and
         * {@link https://pptr.dev/guides/page-interactions#xpath-selectors--p-xpath | xpath}
         * and
         * {@link https://pptr.dev/guides/page-interactions#querying-elements-in-shadow-dom | combining these queries across shadow roots}.
         * Alternatively, you can specify the selector type using a
         * {@link https://pptr.dev/guides/page-interactions#prefixed-selector-syntax | prefix}.
         * @param options - Optional waiting parameters
         * @returns Promise which resolves when element specified by selector string
         * is added to DOM. Resolves to `null` if waiting for hidden: `true` and
         * selector is not found in DOM.
         *
         * @remarks
         * The optional Parameter in Arguments `options` are:
         *
         * - `visible`: A boolean wait for element to be present in DOM and to be
         *   visible, i.e. to not have `display: none` or `visibility: hidden` CSS
         *   properties. Defaults to `false`.
         *
         * - `hidden`: Wait for element to not be found in the DOM or to be hidden,
         *   i.e. have `display: none` or `visibility: hidden` CSS properties. Defaults to
         *   `false`.
         *
         * - `timeout`: maximum time to wait for in milliseconds. Defaults to `30000`
         *   (30 seconds). Pass `0` to disable timeout. The default value can be changed
         *   by using the {@link Page.setDefaultTimeout} method.
         *
         * - `signal`: A signal object that allows you to cancel a waitForSelector call.
         */
        async waitForSelector(selector, options = {}) {
          return await this.mainFrame().waitForSelector(selector, options);
        }
        /**
         * Waits for the provided function, `pageFunction`, to return a truthy value when
         * evaluated in the page's context.
         *
         * @example
         * {@link Page.waitForFunction} can be used to observe a viewport size change:
         *
         * ```ts
         * import puppeteer from 'puppeteer';
         *
         * const browser = await puppeteer.launch();
         * const page = await browser.newPage();
         * const watchDog = page.waitForFunction('window.innerWidth < 100');
         * await page.setViewport({width: 50, height: 50});
         * await watchDog;
         * await browser.close();
         * ```
         *
         * @example
         * Arguments can be passed from Node.js to `pageFunction`:
         *
         * ```ts
         * const selector = '.foo';
         * await page.waitForFunction(
         *   selector => !!document.querySelector(selector),
         *   {},
         *   selector,
         * );
         * ```
         *
         * @example
         * The provided `pageFunction` can be asynchronous:
         *
         * ```ts
         * const username = 'github-username';
         * await page.waitForFunction(
         *   async username => {
         *     const githubResponse = await fetch(
         *       `https://api.github.com/users/${username}`,
         *     );
         *     const githubUser = await githubResponse.json();
         *     // show the avatar
         *     const img = document.createElement('img');
         *     img.src = githubUser.avatar_url;
         *     // wait 3 seconds
         *     await new Promise((resolve, reject) => setTimeout(resolve, 3000));
         *     img.remove();
         *   },
         *   {},
         *   username,
         * );
         * ```
         *
         * @param pageFunction - Function to be evaluated in browser context until it returns a
         * truthy value.
         * @param options - Options for configuring waiting behavior.
         */
        waitForFunction(pageFunction, options, ...args2) {
          return this.mainFrame().waitForFunction(pageFunction, options, ...args2);
        }
        /** @internal */
        [(_screenshot_decorators = [(0, decorators_js_1.guarded)(function() {
          return this.browser();
        })], disposable_js_1.disposeSymbol)]() {
          return void this.close().catch(util_js_1.debugError);
        }
        /** @internal */
        [disposable_js_1.asyncDisposeSymbol]() {
          return this.close();
        }
      };
    })();
    exports2.Page = Page;
    exports2.supportedMetrics = /* @__PURE__ */ new Set([
      "Timestamp",
      "Documents",
      "Frames",
      "JSEventListeners",
      "Nodes",
      "LayoutCount",
      "RecalcStyleCount",
      "LayoutDuration",
      "RecalcStyleDuration",
      "ScriptDuration",
      "TaskDuration",
      "JSHeapUsedSize",
      "JSHeapTotalSize"
    ]);
    function normalizeRectangle(clip) {
      return {
        ...clip,
        ...clip.width < 0 ? {
          x: clip.x + clip.width,
          width: -clip.width
        } : {
          x: clip.x,
          width: clip.width
        },
        ...clip.height < 0 ? {
          y: clip.y + clip.height,
          height: -clip.height
        } : {
          y: clip.y,
          height: clip.height
        }
      };
    }
    function roundRectangle(clip) {
      const x = Math.round(clip.x);
      const y = Math.round(clip.y);
      const width = Math.round(clip.width + clip.x - x);
      const height = Math.round(clip.height + clip.y - y);
      return { ...clip, x, y, width, height };
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/WaitTask.js
var require_WaitTask = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/WaitTask.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.TaskManager = exports2.WaitTask = void 0;
    var Deferred_js_1 = require_Deferred();
    var ErrorLike_js_1 = require_ErrorLike();
    var Function_js_1 = require_Function();
    var Errors_js_1 = require_Errors();
    var LazyArg_js_1 = require_LazyArg();
    var WaitTask = class {
      #world;
      #polling;
      #root;
      #fn;
      #args;
      #timeout;
      #genericError = new Error("Waiting failed");
      #timeoutError;
      #result = Deferred_js_1.Deferred.create();
      #poller;
      #signal;
      #reruns = [];
      constructor(world, options, fn, ...args2) {
        this.#world = world;
        this.#polling = options.polling;
        this.#root = options.root;
        this.#signal = options.signal;
        this.#signal?.addEventListener("abort", this.#onAbortSignal, {
          once: true
        });
        switch (typeof fn) {
          case "string":
            this.#fn = `() => {return (${fn});}`;
            break;
          default:
            this.#fn = (0, Function_js_1.stringifyFunction)(fn);
            break;
        }
        this.#args = args2;
        this.#world.taskManager.add(this);
        if (options.timeout) {
          this.#timeoutError = new Errors_js_1.TimeoutError(`Waiting failed: ${options.timeout}ms exceeded`);
          this.#timeout = setTimeout(() => {
            void this.terminate(this.#timeoutError);
          }, options.timeout);
        }
        void this.rerun();
      }
      get result() {
        return this.#result.valueOrThrow();
      }
      async rerun() {
        for (const prev of this.#reruns) {
          prev.abort();
        }
        this.#reruns.length = 0;
        const controller = new AbortController();
        this.#reruns.push(controller);
        try {
          switch (this.#polling) {
            case "raf":
              this.#poller = await this.#world.evaluateHandle(({ RAFPoller, createFunction }, fn, ...args2) => {
                const fun = createFunction(fn);
                return new RAFPoller(() => {
                  return fun(...args2);
                });
              }, LazyArg_js_1.LazyArg.create((context) => {
                return context.puppeteerUtil;
              }), this.#fn, ...this.#args);
              break;
            case "mutation":
              this.#poller = await this.#world.evaluateHandle(({ MutationPoller, createFunction }, root, fn, ...args2) => {
                const fun = createFunction(fn);
                return new MutationPoller(() => {
                  return fun(...args2);
                }, root || document);
              }, LazyArg_js_1.LazyArg.create((context) => {
                return context.puppeteerUtil;
              }), this.#root, this.#fn, ...this.#args);
              break;
            default:
              this.#poller = await this.#world.evaluateHandle(({ IntervalPoller, createFunction }, ms, fn, ...args2) => {
                const fun = createFunction(fn);
                return new IntervalPoller(() => {
                  return fun(...args2);
                }, ms);
              }, LazyArg_js_1.LazyArg.create((context) => {
                return context.puppeteerUtil;
              }), this.#polling, this.#fn, ...this.#args);
              break;
          }
          await this.#poller.evaluate((poller) => {
            void poller.start();
          });
          const result = await this.#poller.evaluateHandle((poller) => {
            return poller.result();
          });
          this.#result.resolve(result);
          await this.terminate();
        } catch (error) {
          if (controller.signal.aborted) {
            return;
          }
          const badError = this.getBadError(error);
          if (badError) {
            this.#genericError.cause = badError;
            await this.terminate(this.#genericError);
          }
        }
      }
      async terminate(error) {
        this.#world.taskManager.delete(this);
        this.#signal?.removeEventListener("abort", this.#onAbortSignal);
        clearTimeout(this.#timeout);
        if (error && !this.#result.finished()) {
          this.#result.reject(error);
        }
        if (this.#poller) {
          try {
            await this.#poller.evaluate(async (poller) => {
              await poller.stop();
            });
            if (this.#poller) {
              await this.#poller.dispose();
              this.#poller = void 0;
            }
          } catch {
          }
        }
      }
      /**
       * Not all errors lead to termination. They usually imply we need to rerun the task.
       */
      getBadError(error) {
        if ((0, ErrorLike_js_1.isErrorLike)(error)) {
          if (error.message.includes("Execution context is not available in detached frame")) {
            return new Error("Waiting failed: Frame detached");
          }
          if (error.message.includes("Execution context was destroyed")) {
            return;
          }
          if (error.message.includes("Cannot find context with specified id")) {
            return;
          }
          if (error.message.includes("DiscardedBrowsingContextError")) {
            return;
          }
          return error;
        }
        return new Error("WaitTask failed with an error", {
          cause: error
        });
      }
      #onAbortSignal = () => {
        void this.terminate(this.#signal?.reason);
      };
    };
    exports2.WaitTask = WaitTask;
    var TaskManager = class {
      #tasks = /* @__PURE__ */ new Set();
      add(task) {
        this.#tasks.add(task);
      }
      delete(task) {
        this.#tasks.delete(task);
      }
      terminateAll(error) {
        for (const task of this.#tasks) {
          void task.terminate(error);
        }
        this.#tasks.clear();
      }
      async rerunAll() {
        await Promise.all([...this.#tasks].map((task) => {
          return task.rerun();
        }));
      }
    };
    exports2.TaskManager = TaskManager;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/api/Realm.js
var require_Realm = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/api/Realm.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Realm = void 0;
    var WaitTask_js_1 = require_WaitTask();
    var disposable_js_1 = require_disposable();
    var Realm = class {
      timeoutSettings;
      taskManager = new WaitTask_js_1.TaskManager();
      constructor(timeoutSettings) {
        this.timeoutSettings = timeoutSettings;
      }
      async waitForFunction(pageFunction, options = {}, ...args2) {
        const { polling = "raf", timeout = this.timeoutSettings.timeout(), root, signal } = options;
        if (typeof polling === "number" && polling < 0) {
          throw new Error("Cannot poll with non-positive interval");
        }
        const waitTask = new WaitTask_js_1.WaitTask(this, {
          polling,
          root,
          timeout,
          signal
        }, pageFunction, ...args2);
        return await waitTask.result;
      }
      get disposed() {
        return this.#disposed;
      }
      #disposed = false;
      /** @internal */
      dispose() {
        this.#disposed = true;
        this.taskManager.terminateAll(new Error("waitForFunction failed: frame got detached."));
      }
      /** @internal */
      [disposable_js_1.disposeSymbol]() {
        this.dispose();
      }
    };
    exports2.Realm = Realm;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/api/Target.js
var require_Target = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/api/Target.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Target = exports2.TargetType = void 0;
    var TargetType;
    (function(TargetType2) {
      TargetType2["PAGE"] = "page";
      TargetType2["BACKGROUND_PAGE"] = "background_page";
      TargetType2["SERVICE_WORKER"] = "service_worker";
      TargetType2["SHARED_WORKER"] = "shared_worker";
      TargetType2["BROWSER"] = "browser";
      TargetType2["WEBVIEW"] = "webview";
      TargetType2["OTHER"] = "other";
      TargetType2["TAB"] = "tab";
    })(TargetType || (exports2.TargetType = TargetType = {}));
    var Target = class {
      /**
       * @internal
       */
      constructor() {
      }
      /**
       * If the target is not of type `"service_worker"` or `"shared_worker"`, returns `null`.
       */
      async worker() {
        return null;
      }
      /**
       * If the target is not of type `"page"`, `"webview"` or `"background_page"`,
       * returns `null`.
       */
      async page() {
        return null;
      }
    };
    exports2.Target = Target;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/api/WebWorker.js
var require_WebWorker = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/api/WebWorker.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.WebWorker = void 0;
    var Errors_js_1 = require_Errors();
    var EventEmitter_js_1 = require_EventEmitter();
    var TimeoutSettings_js_1 = require_TimeoutSettings();
    var util_js_1 = require_util();
    var WebWorker = class extends EventEmitter_js_1.EventEmitter {
      /**
       * @internal
       */
      timeoutSettings = new TimeoutSettings_js_1.TimeoutSettings();
      #url;
      /**
       * @internal
       */
      constructor(url) {
        super();
        this.#url = url;
      }
      /**
       * The URL of this web worker.
       */
      url() {
        return this.#url;
      }
      /**
       * Evaluates a given function in the {@link WebWorker | worker}.
       *
       * @remarks If the given function returns a promise,
       * {@link WebWorker.evaluate | evaluate} will wait for the promise to resolve.
       *
       * As a rule of thumb, if the return value of the given function is more
       * complicated than a JSON object (e.g. most classes), then
       * {@link WebWorker.evaluate | evaluate} will _likely_ return some truncated
       * value (or `{}`). This is because we are not returning the actual return
       * value, but a deserialized version as a result of transferring the return
       * value through a protocol to Puppeteer.
       *
       * In general, you should use
       * {@link WebWorker.evaluateHandle | evaluateHandle} if
       * {@link WebWorker.evaluate | evaluate} cannot serialize the return value
       * properly or you need a mutable {@link JSHandle | handle} to the return
       * object.
       *
       * @param func - Function to be evaluated.
       * @param args - Arguments to pass into `func`.
       * @returns The result of `func`.
       */
      async evaluate(func, ...args2) {
        func = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.evaluate.name, func);
        return await this.mainRealm().evaluate(func, ...args2);
      }
      /**
       * Evaluates a given function in the {@link WebWorker | worker}.
       *
       * @remarks If the given function returns a promise,
       * {@link WebWorker.evaluate | evaluate} will wait for the promise to resolve.
       *
       * In general, you should use
       * {@link WebWorker.evaluateHandle | evaluateHandle} if
       * {@link WebWorker.evaluate | evaluate} cannot serialize the return value
       * properly or you need a mutable {@link JSHandle | handle} to the return
       * object.
       *
       * @param func - Function to be evaluated.
       * @param args - Arguments to pass into `func`.
       * @returns A {@link JSHandle | handle} to the return value of `func`.
       */
      async evaluateHandle(func, ...args2) {
        func = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.evaluateHandle.name, func);
        return await this.mainRealm().evaluateHandle(func, ...args2);
      }
      async close() {
        throw new Errors_js_1.UnsupportedOperation("WebWorker.close() is not supported");
      }
    };
    exports2.WebWorker = WebWorker;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/api/api.js
var require_api = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/api/api.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    __exportStar2(require_Browser(), exports2);
    __exportStar2(require_BrowserContext(), exports2);
    __exportStar2(require_CDPSession(), exports2);
    __exportStar2(require_DeviceRequestPrompt(), exports2);
    __exportStar2(require_Dialog(), exports2);
    __exportStar2(require_ElementHandle(), exports2);
    __exportStar2(require_Frame(), exports2);
    __exportStar2(require_HTTPRequest(), exports2);
    __exportStar2(require_HTTPResponse(), exports2);
    __exportStar2(require_Input(), exports2);
    __exportStar2(require_JSHandle(), exports2);
    __exportStar2(require_Page(), exports2);
    __exportStar2(require_Realm(), exports2);
    __exportStar2(require_Target(), exports2);
    __exportStar2(require_WebWorker(), exports2);
    __exportStar2(require_locators(), exports2);
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Accessibility.js
var require_Accessibility = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Accessibility.js"(exports2) {
    "use strict";
    init_prefix();
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Accessibility = void 0;
    var util_js_1 = require_util();
    var Accessibility = class {
      #realm;
      #frameId;
      /**
       * @internal
       */
      constructor(realm, frameId = "") {
        this.#realm = realm;
        this.#frameId = frameId;
      }
      /**
       * Captures the current state of the accessibility tree.
       * The returned object represents the root accessible node of the page.
       *
       * @remarks
       *
       * **NOTE** The Chrome accessibility tree contains nodes that go unused on
       * most platforms and by most screen readers. Puppeteer will discard them as
       * well for an easier to process tree, unless `interestingOnly` is set to
       * `false`.
       *
       * @example
       * An example of dumping the entire accessibility tree:
       *
       * ```ts
       * const snapshot = await page.accessibility.snapshot();
       * console.log(snapshot);
       * ```
       *
       * @example
       * An example of logging the focused node's name:
       *
       * ```ts
       * const snapshot = await page.accessibility.snapshot();
       * const node = findFocusedNode(snapshot);
       * console.log(node && node.name);
       *
       * function findFocusedNode(node) {
       *   if (node.focused) return node;
       *   for (const child of node.children || []) {
       *     const foundNode = findFocusedNode(child);
       *     return foundNode;
       *   }
       *   return null;
       * }
       * ```
       *
       * @returns An AXNode object representing the snapshot.
       */
      async snapshot(options = {}) {
        const { interestingOnly = true, root = null, includeIframes = false } = options;
        const { nodes } = await this.#realm.environment.client.send("Accessibility.getFullAXTree", {
          frameId: this.#frameId
        });
        let backendNodeId;
        if (root) {
          const { node } = await this.#realm.environment.client.send("DOM.describeNode", {
            objectId: root.id
          });
          backendNodeId = node.backendNodeId;
        }
        const defaultRoot = AXNode.createTree(this.#realm, nodes);
        const populateIframes = async (root2) => {
          if (root2.payload.role?.value === "Iframe") {
            const env_1 = { stack: [], error: void 0, hasError: false };
            try {
              if (!root2.payload.backendDOMNodeId) {
                return;
              }
              const handle = __addDisposableResource2(env_1, await this.#realm.adoptBackendNode(root2.payload.backendDOMNodeId), false);
              if (!handle || !("contentFrame" in handle)) {
                return;
              }
              const frame = await handle.contentFrame();
              if (!frame) {
                return;
              }
              try {
                const iframeSnapshot = await frame.accessibility.snapshot(options);
                root2.iframeSnapshot = iframeSnapshot ?? void 0;
              } catch (error) {
                (0, util_js_1.debugError)(error);
              }
            } catch (e_1) {
              env_1.error = e_1;
              env_1.hasError = true;
            } finally {
              __disposeResources2(env_1);
            }
          }
          for (const child of root2.children) {
            await populateIframes(child);
          }
        };
        let needle = defaultRoot;
        if (!defaultRoot) {
          return null;
        }
        if (includeIframes) {
          await populateIframes(defaultRoot);
        }
        if (backendNodeId) {
          needle = defaultRoot.find((node) => {
            return node.payload.backendDOMNodeId === backendNodeId;
          });
        }
        if (!needle) {
          return null;
        }
        if (!interestingOnly) {
          return this.serializeTree(needle)[0] ?? null;
        }
        const interestingNodes = /* @__PURE__ */ new Set();
        this.collectInterestingNodes(interestingNodes, defaultRoot, false);
        return this.serializeTree(needle, interestingNodes)[0] ?? null;
      }
      serializeTree(node, interestingNodes) {
        const children = [];
        for (const child of node.children) {
          children.push(...this.serializeTree(child, interestingNodes));
        }
        if (interestingNodes && !interestingNodes.has(node)) {
          return children;
        }
        const serializedNode = node.serialize();
        if (children.length) {
          serializedNode.children = children;
        }
        if (node.iframeSnapshot) {
          if (!serializedNode.children) {
            serializedNode.children = [];
          }
          serializedNode.children.push(node.iframeSnapshot);
        }
        return [serializedNode];
      }
      collectInterestingNodes(collection, node, insideControl) {
        if (node.isInteresting(insideControl) || node.iframeSnapshot) {
          collection.add(node);
        }
        if (node.isLeafNode()) {
          return;
        }
        insideControl = insideControl || node.isControl();
        for (const child of node.children) {
          this.collectInterestingNodes(collection, child, insideControl);
        }
      }
    };
    exports2.Accessibility = Accessibility;
    var AXNode = class _AXNode {
      payload;
      children = [];
      iframeSnapshot;
      #richlyEditable = false;
      #editable = false;
      #focusable = false;
      #hidden = false;
      #busy = false;
      #modal = false;
      #hasErrormessage = false;
      #hasDetails = false;
      #name;
      #role;
      #description;
      #roledescription;
      #live;
      #ignored;
      #cachedHasFocusableChild;
      #realm;
      constructor(realm, payload) {
        this.payload = payload;
        this.#role = this.payload.role ? this.payload.role.value : "Unknown";
        this.#ignored = this.payload.ignored;
        this.#name = this.payload.name ? this.payload.name.value : "";
        this.#description = this.payload.description ? this.payload.description.value : void 0;
        this.#realm = realm;
        for (const property of this.payload.properties || []) {
          if (property.name === "editable") {
            this.#richlyEditable = property.value.value === "richtext";
            this.#editable = true;
          }
          if (property.name === "focusable") {
            this.#focusable = property.value.value;
          }
          if (property.name === "hidden") {
            this.#hidden = property.value.value;
          }
          if (property.name === "busy") {
            this.#busy = property.value.value;
          }
          if (property.name === "live") {
            this.#live = property.value.value;
          }
          if (property.name === "modal") {
            this.#modal = property.value.value;
          }
          if (property.name === "roledescription") {
            this.#roledescription = property.value.value;
          }
          if (property.name === "errormessage") {
            this.#hasErrormessage = true;
          }
          if (property.name === "details") {
            this.#hasDetails = true;
          }
        }
      }
      #isPlainTextField() {
        if (this.#richlyEditable) {
          return false;
        }
        if (this.#editable) {
          return true;
        }
        return this.#role === "textbox" || this.#role === "searchbox";
      }
      #isTextOnlyObject() {
        const role = this.#role;
        return role === "LineBreak" || role === "text" || role === "InlineTextBox" || role === "StaticText";
      }
      #hasFocusableChild() {
        if (this.#cachedHasFocusableChild === void 0) {
          this.#cachedHasFocusableChild = false;
          for (const child of this.children) {
            if (child.#focusable || child.#hasFocusableChild()) {
              this.#cachedHasFocusableChild = true;
              break;
            }
          }
        }
        return this.#cachedHasFocusableChild;
      }
      find(predicate) {
        if (predicate(this)) {
          return this;
        }
        for (const child of this.children) {
          const result = child.find(predicate);
          if (result) {
            return result;
          }
        }
        return null;
      }
      isLeafNode() {
        if (!this.children.length) {
          return true;
        }
        if (this.#isPlainTextField() || this.#isTextOnlyObject()) {
          return true;
        }
        switch (this.#role) {
          case "doc-cover":
          case "graphics-symbol":
          case "img":
          case "image":
          case "Meter":
          case "scrollbar":
          case "slider":
          case "separator":
          case "progressbar":
            return true;
          default:
            break;
        }
        if (this.#hasFocusableChild()) {
          return false;
        }
        if (this.#role === "heading" && this.#name) {
          return true;
        }
        return false;
      }
      isControl() {
        switch (this.#role) {
          case "button":
          case "checkbox":
          case "ColorWell":
          case "combobox":
          case "DisclosureTriangle":
          case "listbox":
          case "menu":
          case "menubar":
          case "menuitem":
          case "menuitemcheckbox":
          case "menuitemradio":
          case "radio":
          case "scrollbar":
          case "searchbox":
          case "slider":
          case "spinbutton":
          case "switch":
          case "tab":
          case "textbox":
          case "tree":
          case "treeitem":
            return true;
          default:
            return false;
        }
      }
      isLandmark() {
        switch (this.#role) {
          case "banner":
          case "complementary":
          case "contentinfo":
          case "form":
          case "main":
          case "navigation":
          case "region":
          case "search":
            return true;
          default:
            return false;
        }
      }
      isInteresting(insideControl) {
        const role = this.#role;
        if (role === "Ignored" || this.#hidden || this.#ignored) {
          return false;
        }
        if (this.isLandmark()) {
          return true;
        }
        if (this.#focusable || this.#richlyEditable || this.#busy || this.#live && this.#live !== "off" || this.#modal || this.#hasErrormessage || this.#hasDetails || this.#roledescription) {
          return true;
        }
        if (this.isControl()) {
          return true;
        }
        if (insideControl) {
          return false;
        }
        return this.isLeafNode() && (!!this.#name || !!this.#description);
      }
      serialize() {
        const properties = /* @__PURE__ */ new Map();
        for (const property of this.payload.properties || []) {
          properties.set(property.name.toLowerCase(), property.value.value);
        }
        if (this.payload.name) {
          properties.set("name", this.payload.name.value);
        }
        if (this.payload.value) {
          properties.set("value", this.payload.value.value);
        }
        if (this.payload.description) {
          properties.set("description", this.payload.description.value);
        }
        const node = {
          role: this.#role,
          elementHandle: async () => {
            const env_2 = { stack: [], error: void 0, hasError: false };
            try {
              if (!this.payload.backendDOMNodeId) {
                return null;
              }
              const handle = __addDisposableResource2(env_2, await this.#realm.adoptBackendNode(this.payload.backendDOMNodeId), false);
              return await handle.evaluateHandle((node2) => {
                return node2.nodeType === Node.TEXT_NODE ? node2.parentElement : node2;
              });
            } catch (e_2) {
              env_2.error = e_2;
              env_2.hasError = true;
            } finally {
              __disposeResources2(env_2);
            }
          },
          backendNodeId: this.payload.backendDOMNodeId,
          // LoaderId is an experimental mechanism to establish unique IDs across
          // navigations.
          loaderId: this.#realm.environment._loaderId
        };
        const userStringProperties = [
          "name",
          "value",
          "description",
          "keyshortcuts",
          "roledescription",
          "valuetext",
          "url"
        ];
        const getUserStringPropertyValue = (key) => {
          return properties.get(key);
        };
        for (const userStringProperty of userStringProperties) {
          if (!properties.has(userStringProperty)) {
            continue;
          }
          node[userStringProperty] = getUserStringPropertyValue(userStringProperty);
        }
        const booleanProperties = [
          "disabled",
          "expanded",
          "focused",
          "modal",
          "multiline",
          "multiselectable",
          "readonly",
          "required",
          "selected",
          "busy",
          "atomic"
        ];
        const getBooleanPropertyValue = (key) => {
          return !!properties.get(key);
        };
        for (const booleanProperty of booleanProperties) {
          if (booleanProperty === "focused" && this.#role === "RootWebArea") {
            continue;
          }
          if (!properties.has(booleanProperty)) {
            continue;
          }
          node[booleanProperty] = getBooleanPropertyValue(booleanProperty);
        }
        const tristateProperties = ["checked", "pressed"];
        for (const tristateProperty of tristateProperties) {
          if (!properties.has(tristateProperty)) {
            continue;
          }
          const value = properties.get(tristateProperty);
          node[tristateProperty] = value === "mixed" ? "mixed" : value === "true" ? true : false;
        }
        const numericalProperties = [
          "level",
          "valuemax",
          "valuemin"
        ];
        const getNumericalPropertyValue = (key) => {
          return properties.get(key);
        };
        for (const numericalProperty of numericalProperties) {
          if (!properties.has(numericalProperty)) {
            continue;
          }
          node[numericalProperty] = getNumericalPropertyValue(numericalProperty);
        }
        const tokenProperties = [
          "autocomplete",
          "haspopup",
          "invalid",
          "orientation",
          "live",
          "relevant",
          "errormessage",
          "details"
        ];
        const getTokenPropertyValue = (key) => {
          return properties.get(key);
        };
        for (const tokenProperty of tokenProperties) {
          const value = getTokenPropertyValue(tokenProperty);
          if (!value || value === "false") {
            continue;
          }
          node[tokenProperty] = getTokenPropertyValue(tokenProperty);
        }
        return node;
      }
      static createTree(realm, payloads) {
        const nodeById = /* @__PURE__ */ new Map();
        for (const payload of payloads) {
          nodeById.set(payload.nodeId, new _AXNode(realm, payload));
        }
        for (const node of nodeById.values()) {
          for (const childId of node.payload.childIds || []) {
            const child = nodeById.get(childId);
            if (child) {
              node.children.push(child);
            }
          }
        }
        return nodeById.values().next().value ?? null;
      }
    };
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Binding.js
var require_Binding = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Binding.js"(exports2) {
    "use strict";
    init_prefix();
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Binding = void 0;
    var JSHandle_js_1 = require_JSHandle();
    var util_js_1 = require_util();
    var disposable_js_1 = require_disposable();
    var ErrorLike_js_1 = require_ErrorLike();
    var Binding = class {
      #name;
      #fn;
      #initSource;
      constructor(name, fn, initSource) {
        this.#name = name;
        this.#fn = fn;
        this.#initSource = initSource;
      }
      get name() {
        return this.#name;
      }
      get initSource() {
        return this.#initSource;
      }
      /**
       * @param context - Context to run the binding in; the context should have
       * the binding added to it beforehand.
       * @param id - ID of the call. This should come from the CDP
       * `onBindingCalled` response.
       * @param args - Plain arguments from CDP.
       */
      async run(context, id, args2, isTrivial) {
        const stack = new disposable_js_1.DisposableStack();
        try {
          if (!isTrivial) {
            const env_1 = { stack: [], error: void 0, hasError: false };
            try {
              const handles = __addDisposableResource2(env_1, await context.evaluateHandle((name, seq) => {
                return globalThis[name].args.get(seq);
              }, this.#name, id), false);
              const properties = await handles.getProperties();
              for (const [index, handle] of properties) {
                if (index in args2) {
                  switch (handle.remoteObject().subtype) {
                    case "node":
                      args2[+index] = handle;
                      break;
                    default:
                      stack.use(handle);
                  }
                } else {
                  stack.use(handle);
                }
              }
            } catch (e_1) {
              env_1.error = e_1;
              env_1.hasError = true;
            } finally {
              __disposeResources2(env_1);
            }
          }
          await context.evaluate((name, seq, result) => {
            const callbacks = globalThis[name].callbacks;
            callbacks.get(seq).resolve(result);
            callbacks.delete(seq);
          }, this.#name, id, await this.#fn(...args2));
          for (const arg of args2) {
            if (arg instanceof JSHandle_js_1.JSHandle) {
              stack.use(arg);
            }
          }
        } catch (error) {
          if ((0, ErrorLike_js_1.isErrorLike)(error)) {
            await context.evaluate((name, seq, message, stack2) => {
              const error2 = new Error(message);
              error2.stack = stack2;
              const callbacks = globalThis[name].callbacks;
              callbacks.get(seq).reject(error2);
              callbacks.delete(seq);
            }, this.#name, id, error.message, error.stack).catch(util_js_1.debugError);
          } else {
            await context.evaluate((name, seq, error2) => {
              const callbacks = globalThis[name].callbacks;
              callbacks.get(seq).reject(error2);
              callbacks.delete(seq);
            }, this.#name, id, error).catch(util_js_1.debugError);
          }
        }
      }
    };
    exports2.Binding = Binding;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/BluetoothEmulation.js
var require_BluetoothEmulation = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/BluetoothEmulation.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CdpBluetoothEmulation = void 0;
    var CdpBluetoothEmulation = class {
      #connection;
      constructor(connection) {
        this.#connection = connection;
      }
      async emulateAdapter(state, leSupported = true) {
        await this.#connection.send("BluetoothEmulation.disable");
        await this.#connection.send("BluetoothEmulation.enable", {
          state,
          leSupported
        });
      }
      async disableEmulation() {
        await this.#connection.send("BluetoothEmulation.disable");
      }
      async simulatePreconnectedPeripheral(preconnectedPeripheral) {
        await this.#connection.send("BluetoothEmulation.simulatePreconnectedPeripheral", preconnectedPeripheral);
      }
    };
    exports2.CdpBluetoothEmulation = CdpBluetoothEmulation;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/ConsoleMessage.js
var require_ConsoleMessage = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/ConsoleMessage.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ConsoleMessage = void 0;
    var ConsoleMessage = class {
      #type;
      #text;
      #args;
      #stackTraceLocations;
      #frame;
      #rawStackTrace;
      #targetId;
      /**
       * @internal
       */
      constructor(type, text, args2, stackTraceLocations, frame, rawStackTrace, targetId) {
        this.#type = type;
        this.#text = text;
        this.#args = args2;
        this.#stackTraceLocations = stackTraceLocations;
        this.#frame = frame;
        this.#rawStackTrace = rawStackTrace;
        this.#targetId = targetId;
      }
      /**
       * The type of the console message.
       */
      type() {
        return this.#type;
      }
      /**
       * The text of the console message.
       */
      text() {
        return this.#text;
      }
      /**
       * An array of arguments passed to the console.
       */
      args() {
        return this.#args;
      }
      /**
       * The location of the console message.
       */
      location() {
        return this.#stackTraceLocations[0] ?? (this.#frame ? { url: this.#frame.url() } : {});
      }
      /**
       * The array of locations on the stack of the console message.
       */
      stackTrace() {
        return this.#stackTraceLocations;
      }
      /**
       * The underlying protocol stack trace if available.
       *
       * @internal
       */
      _rawStackTrace() {
        return this.#rawStackTrace;
      }
      /**
       * The targetId from which this console message originated.
       *
       * @internal
       */
      _targetId() {
        return this.#targetId;
      }
    };
    exports2.ConsoleMessage = ConsoleMessage;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/FileChooser.js
var require_FileChooser = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/FileChooser.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.FileChooser = void 0;
    var assert_js_1 = require_assert();
    var FileChooser = class {
      #element;
      #multiple;
      #handled = false;
      /**
       * @internal
       */
      constructor(element, multiple) {
        this.#element = element;
        this.#multiple = multiple;
      }
      /**
       * Whether file chooser allow for
       * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#attr-multiple | multiple}
       * file selection.
       */
      isMultiple() {
        return this.#multiple;
      }
      /**
       * Accept the file chooser request with the given file paths.
       *
       * @remarks This will not validate whether the file paths exists. Also, if a
       * path is relative, then it is resolved against the
       * {@link https://nodejs.org/api/process.html#process_process_cwd | current working directory}.
       * For locals script connecting to remote chrome environments, paths must be
       * absolute.
       */
      async accept(paths) {
        (0, assert_js_1.assert)(!this.#handled, "Cannot accept FileChooser which is already handled!");
        this.#handled = true;
        await this.#element.uploadFile(...paths);
      }
      /**
       * Closes the file chooser without selecting any files.
       */
      async cancel() {
        (0, assert_js_1.assert)(!this.#handled, "Cannot cancel FileChooser which is already handled!");
        this.#handled = true;
        await this.#element.evaluate((element) => {
          element.dispatchEvent(new Event("cancel", { bubbles: true }));
        });
      }
    };
    exports2.FileChooser = FileChooser;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/NetworkManagerEvents.js
var require_NetworkManagerEvents = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/NetworkManagerEvents.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NetworkManagerEvent = void 0;
    var NetworkManagerEvent;
    (function(NetworkManagerEvent2) {
      NetworkManagerEvent2.Request = /* @__PURE__ */ Symbol("NetworkManager.Request");
      NetworkManagerEvent2.RequestServedFromCache = /* @__PURE__ */ Symbol("NetworkManager.RequestServedFromCache");
      NetworkManagerEvent2.Response = /* @__PURE__ */ Symbol("NetworkManager.Response");
      NetworkManagerEvent2.RequestFailed = /* @__PURE__ */ Symbol("NetworkManager.RequestFailed");
      NetworkManagerEvent2.RequestFinished = /* @__PURE__ */ Symbol("NetworkManager.RequestFinished");
    })(NetworkManagerEvent || (exports2.NetworkManagerEvent = NetworkManagerEvent = {}));
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js
var require_CallbackRegistry = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Callback = exports2.CallbackRegistry = void 0;
    var Deferred_js_1 = require_Deferred();
    var ErrorLike_js_1 = require_ErrorLike();
    var Errors_js_1 = require_Errors();
    var util_js_1 = require_util();
    var CallbackRegistry = class {
      #callbacks = /* @__PURE__ */ new Map();
      #idGenerator;
      constructor(idGenerator) {
        this.#idGenerator = idGenerator;
      }
      create(label, timeout, request) {
        const callback = new Callback(this.#idGenerator(), label, timeout);
        this.#callbacks.set(callback.id, callback);
        try {
          request(callback.id);
        } catch (error) {
          callback.promise.catch(util_js_1.debugError).finally(() => {
            this.#callbacks.delete(callback.id);
          });
          callback.reject(error);
          throw error;
        }
        return callback.promise.finally(() => {
          this.#callbacks.delete(callback.id);
        });
      }
      reject(id, message, originalMessage) {
        const callback = this.#callbacks.get(id);
        if (!callback) {
          return;
        }
        this._reject(callback, message, originalMessage);
      }
      rejectRaw(id, error) {
        const callback = this.#callbacks.get(id);
        if (!callback) {
          return;
        }
        callback.reject(error);
      }
      _reject(callback, errorMessage, originalMessage) {
        let error;
        let message;
        if (errorMessage instanceof Errors_js_1.ProtocolError) {
          error = errorMessage;
          error.cause = callback.error;
          message = errorMessage.message;
        } else {
          error = callback.error;
          message = errorMessage;
        }
        callback.reject((0, ErrorLike_js_1.rewriteError)(error, `Protocol error (${callback.label}): ${message}`, originalMessage));
      }
      resolve(id, value) {
        const callback = this.#callbacks.get(id);
        if (!callback) {
          return;
        }
        callback.resolve(value);
      }
      clear() {
        for (const callback of this.#callbacks.values()) {
          this._reject(callback, new Errors_js_1.TargetCloseError("Target closed"));
        }
        this.#callbacks.clear();
      }
      /**
       * @internal
       */
      getPendingProtocolErrors() {
        const result = [];
        for (const callback of this.#callbacks.values()) {
          result.push(new Error(`${callback.label} timed out. Trace: ${callback.error.stack}`));
        }
        return result;
      }
    };
    exports2.CallbackRegistry = CallbackRegistry;
    var Callback = class {
      #id;
      #error = new Errors_js_1.ProtocolError();
      #deferred = Deferred_js_1.Deferred.create();
      #timer;
      #label;
      constructor(id, label, timeout) {
        this.#id = id;
        this.#label = label;
        if (timeout) {
          this.#timer = setTimeout(() => {
            this.#deferred.reject((0, ErrorLike_js_1.rewriteError)(this.#error, `${label} timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed.`));
          }, timeout);
        }
      }
      resolve(value) {
        clearTimeout(this.#timer);
        this.#deferred.resolve(value);
      }
      reject(error) {
        clearTimeout(this.#timer);
        this.#deferred.reject(error);
      }
      get id() {
        return this.#id;
      }
      get promise() {
        return this.#deferred.valueOrThrow();
      }
      get error() {
        return this.#error;
      }
      get label() {
        return this.#label;
      }
    };
    exports2.Callback = Callback;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/CdpSession.js
var require_CdpSession = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/CdpSession.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CdpCDPSession = void 0;
    var CDPSession_js_1 = require_CDPSession();
    var CallbackRegistry_js_1 = require_CallbackRegistry();
    var Errors_js_1 = require_Errors();
    var assert_js_1 = require_assert();
    var ErrorLike_js_1 = require_ErrorLike();
    var CdpCDPSession = class extends CDPSession_js_1.CDPSession {
      #sessionId;
      #targetType;
      #callbacks;
      #connection;
      #parentSessionId;
      #target;
      #rawErrors = false;
      #detached = false;
      /**
       * @internal
       */
      constructor(connection, targetType, sessionId, parentSessionId, rawErrors) {
        super();
        this.#connection = connection;
        this.#targetType = targetType;
        this.#callbacks = new CallbackRegistry_js_1.CallbackRegistry(connection._idGenerator);
        this.#sessionId = sessionId;
        this.#parentSessionId = parentSessionId;
        this.#rawErrors = rawErrors;
      }
      /**
       * Sets the {@link CdpTarget} associated with the session instance.
       *
       * @internal
       */
      setTarget(target) {
        this.#target = target;
      }
      /**
       * Gets the {@link CdpTarget} associated with the session instance.
       *
       * @internal
       */
      target() {
        (0, assert_js_1.assert)(this.#target, "Target must exist");
        return this.#target;
      }
      connection() {
        return this.#connection;
      }
      get detached() {
        return this.#connection._closed || this.#detached;
      }
      parentSession() {
        if (!this.#parentSessionId) {
          return this;
        }
        const parent = this.#connection?.session(this.#parentSessionId);
        return parent ?? void 0;
      }
      send(method, params, options) {
        if (this.detached) {
          return Promise.reject(new Errors_js_1.TargetCloseError(`Protocol error (${method}): Session closed. Most likely the ${this.#targetType} has been closed.`));
        }
        return this.#connection._rawSend(this.#callbacks, method, params, this.#sessionId, options);
      }
      /**
       * @internal
       */
      onMessage(object) {
        if (object.id) {
          if (object.error) {
            if (this.#rawErrors) {
              this.#callbacks.rejectRaw(object.id, object.error);
            } else {
              this.#callbacks.reject(object.id, (0, ErrorLike_js_1.createProtocolErrorMessage)(object), object.error.message);
            }
          } else {
            this.#callbacks.resolve(object.id, object.result);
          }
        } else {
          (0, assert_js_1.assert)(!object.id);
          this.emit(object.method, object.params);
        }
      }
      /**
       * Detaches the cdpSession from the target. Once detached, the cdpSession object
       * won't emit any events and can't be used to send messages.
       */
      async detach() {
        if (this.detached) {
          throw new Error(`Session already detached. Most likely the ${this.#targetType} has been closed.`);
        }
        await this.#connection.send("Target.detachFromTarget", {
          sessionId: this.#sessionId
        });
        this.#detached = true;
      }
      /**
       * @internal
       */
      onClosed() {
        this.#callbacks.clear();
        this.#detached = true;
        this.emit(CDPSession_js_1.CDPSessionEvent.Disconnected, void 0);
      }
      /**
       * Returns the session's id.
       */
      id() {
        return this.#sessionId;
      }
      /**
       * @internal
       */
      getPendingProtocolErrors() {
        return this.#callbacks.getPendingProtocolErrors();
      }
    };
    exports2.CdpCDPSession = CdpCDPSession;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Connection.js
var require_Connection = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Connection.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Connection = void 0;
    exports2.isTargetClosedError = isTargetClosedError;
    var CDPSession_js_1 = require_CDPSession();
    var CallbackRegistry_js_1 = require_CallbackRegistry();
    var Debug_js_1 = require_Debug();
    var Errors_js_1 = require_Errors();
    var EventEmitter_js_1 = require_EventEmitter();
    var ErrorLike_js_1 = require_ErrorLike();
    var incremental_id_generator_js_1 = require_incremental_id_generator();
    var CdpSession_js_1 = require_CdpSession();
    var debugProtocolSend = (0, Debug_js_1.debug)("puppeteer:protocol:SEND \u25BA");
    var debugProtocolReceive = (0, Debug_js_1.debug)("puppeteer:protocol:RECV \u25C0");
    var Connection = class extends EventEmitter_js_1.EventEmitter {
      #url;
      #transport;
      #delay;
      #timeout;
      #sessions = /* @__PURE__ */ new Map();
      #closed = false;
      #manuallyAttached = /* @__PURE__ */ new Set();
      #callbacks;
      #rawErrors = false;
      #idGenerator;
      constructor(url, transport, delay = 0, timeout, rawErrors = false, idGenerator = (0, incremental_id_generator_js_1.createIncrementalIdGenerator)()) {
        super();
        this.#rawErrors = rawErrors;
        this.#idGenerator = idGenerator;
        this.#callbacks = new CallbackRegistry_js_1.CallbackRegistry(idGenerator);
        this.#url = url;
        this.#delay = delay;
        this.#timeout = timeout ?? 18e4;
        this.#transport = transport;
        this.#transport.onmessage = this.onMessage.bind(this);
        this.#transport.onclose = this.#onClose.bind(this);
      }
      static fromSession(session) {
        return session.connection();
      }
      /**
       * @internal
       */
      get delay() {
        return this.#delay;
      }
      get timeout() {
        return this.#timeout;
      }
      /**
       * @internal
       */
      get _closed() {
        return this.#closed;
      }
      /**
       * @internal
       */
      get _idGenerator() {
        return this.#idGenerator;
      }
      /**
       * @internal
       */
      get _sessions() {
        return this.#sessions;
      }
      /**
       * @internal
       */
      _session(sessionId) {
        return this.#sessions.get(sessionId) || null;
      }
      /**
       * @param sessionId - The session id
       * @returns The current CDP session if it exists
       */
      session(sessionId) {
        return this._session(sessionId);
      }
      url() {
        return this.#url;
      }
      send(method, params, options) {
        return this._rawSend(this.#callbacks, method, params, void 0, options);
      }
      /**
       * @internal
       */
      _rawSend(callbacks, method, params, sessionId, options) {
        if (this.#closed) {
          return Promise.reject(new Errors_js_1.ConnectionClosedError("Connection closed."));
        }
        return callbacks.create(method, options?.timeout ?? this.#timeout, (id) => {
          const stringifiedMessage = JSON.stringify({
            method,
            params,
            id,
            sessionId
          });
          debugProtocolSend(stringifiedMessage);
          this.#transport.send(stringifiedMessage);
        });
      }
      /**
       * @internal
       */
      async closeBrowser() {
        await this.send("Browser.close");
      }
      /**
       * @internal
       */
      async onMessage(message) {
        if (this.#delay) {
          await new Promise((r) => {
            return setTimeout(r, this.#delay);
          });
        }
        debugProtocolReceive(message);
        const object = JSON.parse(message);
        if (object.method === "Target.attachedToTarget") {
          const sessionId = object.params.sessionId;
          const session = new CdpSession_js_1.CdpCDPSession(this, object.params.targetInfo.type, sessionId, object.sessionId, this.#rawErrors);
          this.#sessions.set(sessionId, session);
          this.emit(CDPSession_js_1.CDPSessionEvent.SessionAttached, session);
          const parentSession = this.#sessions.get(object.sessionId);
          if (parentSession) {
            parentSession.emit(CDPSession_js_1.CDPSessionEvent.SessionAttached, session);
          }
        } else if (object.method === "Target.detachedFromTarget") {
          const session = this.#sessions.get(object.params.sessionId);
          if (session) {
            session.onClosed();
            this.#sessions.delete(object.params.sessionId);
            this.emit(CDPSession_js_1.CDPSessionEvent.SessionDetached, session);
            const parentSession = this.#sessions.get(object.sessionId);
            if (parentSession) {
              parentSession.emit(CDPSession_js_1.CDPSessionEvent.SessionDetached, session);
            }
          }
        }
        if (object.sessionId) {
          const session = this.#sessions.get(object.sessionId);
          if (session) {
            session.onMessage(object);
          }
        } else if (object.id) {
          if (object.error) {
            if (this.#rawErrors) {
              this.#callbacks.rejectRaw(object.id, object.error);
            } else {
              this.#callbacks.reject(object.id, (0, ErrorLike_js_1.createProtocolErrorMessage)(object), object.error.message);
            }
          } else {
            this.#callbacks.resolve(object.id, object.result);
          }
        } else {
          this.emit(object.method, object.params);
        }
      }
      #onClose() {
        if (this.#closed) {
          return;
        }
        this.#closed = true;
        this.#transport.onmessage = void 0;
        this.#transport.onclose = void 0;
        this.#callbacks.clear();
        for (const session of this.#sessions.values()) {
          session.onClosed();
        }
        this.#sessions.clear();
        this.emit(CDPSession_js_1.CDPSessionEvent.Disconnected, void 0);
      }
      dispose() {
        this.#onClose();
        this.#transport.close();
      }
      /**
       * @internal
       */
      isAutoAttached(targetId) {
        return !this.#manuallyAttached.has(targetId);
      }
      /**
       * @internal
       */
      async _createSession(targetInfo, isAutoAttachEmulated = true) {
        if (!isAutoAttachEmulated) {
          this.#manuallyAttached.add(targetInfo.targetId);
        }
        const { sessionId } = await this.send("Target.attachToTarget", {
          targetId: targetInfo.targetId,
          flatten: true
        });
        this.#manuallyAttached.delete(targetInfo.targetId);
        const session = this.#sessions.get(sessionId);
        if (!session) {
          throw new Error("CDPSession creation failed.");
        }
        return session;
      }
      /**
       * @param targetInfo - The target info
       * @returns The CDP session that is created
       */
      async createSession(targetInfo) {
        return await this._createSession(targetInfo, false);
      }
      /**
       * @internal
       */
      getPendingProtocolErrors() {
        const result = [];
        result.push(...this.#callbacks.getPendingProtocolErrors());
        for (const session of this.#sessions.values()) {
          result.push(...session.getPendingProtocolErrors());
        }
        return result;
      }
    };
    exports2.Connection = Connection;
    function isTargetClosedError(error) {
      return error instanceof Errors_js_1.TargetCloseError;
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Coverage.js
var require_Coverage = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Coverage.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CSSCoverage = exports2.JSCoverage = exports2.Coverage = void 0;
    var EventEmitter_js_1 = require_EventEmitter();
    var util_js_1 = require_util();
    var assert_js_1 = require_assert();
    var disposable_js_1 = require_disposable();
    var Coverage = class {
      #jsCoverage;
      #cssCoverage;
      /**
       * @internal
       */
      constructor(client2) {
        this.#jsCoverage = new JSCoverage(client2);
        this.#cssCoverage = new CSSCoverage(client2);
      }
      /**
       * @internal
       */
      updateClient(client2) {
        this.#jsCoverage.updateClient(client2);
        this.#cssCoverage.updateClient(client2);
      }
      /**
       * @param options - Set of configurable options for coverage defaults to
       * `resetOnNavigation : true, reportAnonymousScripts : false,`
       * `includeRawScriptCoverage : false, useBlockCoverage : true`
       * @returns Promise that resolves when coverage is started.
       *
       * @remarks
       * Anonymous scripts are ones that don't have an associated url. These are
       * scripts that are dynamically created on the page using `eval` or
       * `new Function`. If `reportAnonymousScripts` is set to `true`, anonymous
       * scripts URL will start with `debugger://VM` (unless a magic //# sourceURL
       * comment is present, in which case that will the be URL).
       */
      async startJSCoverage(options = {}) {
        return await this.#jsCoverage.start(options);
      }
      /**
       * Promise that resolves to the array of coverage reports for
       * all scripts.
       *
       * @remarks
       * JavaScript Coverage doesn't include anonymous scripts by default.
       * However, scripts with sourceURLs are reported.
       */
      async stopJSCoverage() {
        return await this.#jsCoverage.stop();
      }
      /**
       * @param options - Set of configurable options for coverage, defaults to
       * `resetOnNavigation : true`
       * @returns Promise that resolves when coverage is started.
       */
      async startCSSCoverage(options = {}) {
        return await this.#cssCoverage.start(options);
      }
      /**
       * Promise that resolves to the array of coverage reports
       * for all stylesheets.
       *
       * @remarks
       * CSS Coverage doesn't include dynamically injected style tags
       * without sourceURLs.
       */
      async stopCSSCoverage() {
        return await this.#cssCoverage.stop();
      }
    };
    exports2.Coverage = Coverage;
    var JSCoverage = class {
      #client;
      #enabled = false;
      #scriptURLs = /* @__PURE__ */ new Map();
      #scriptSources = /* @__PURE__ */ new Map();
      #subscriptions;
      #resetOnNavigation = false;
      #reportAnonymousScripts = false;
      #includeRawScriptCoverage = false;
      /**
       * @internal
       */
      constructor(client2) {
        this.#client = client2;
      }
      /**
       * @internal
       */
      updateClient(client2) {
        this.#client = client2;
      }
      async start(options = {}) {
        (0, assert_js_1.assert)(!this.#enabled, "JSCoverage is already enabled");
        const { resetOnNavigation = true, reportAnonymousScripts = false, includeRawScriptCoverage = false, useBlockCoverage = true } = options;
        this.#resetOnNavigation = resetOnNavigation;
        this.#reportAnonymousScripts = reportAnonymousScripts;
        this.#includeRawScriptCoverage = includeRawScriptCoverage;
        this.#enabled = true;
        this.#scriptURLs.clear();
        this.#scriptSources.clear();
        this.#subscriptions = new disposable_js_1.DisposableStack();
        const clientEmitter = this.#subscriptions.use(new EventEmitter_js_1.EventEmitter(this.#client));
        clientEmitter.on("Debugger.scriptParsed", this.#onScriptParsed.bind(this));
        clientEmitter.on("Runtime.executionContextsCleared", this.#onExecutionContextsCleared.bind(this));
        await Promise.all([
          this.#client.send("Profiler.enable"),
          this.#client.send("Profiler.startPreciseCoverage", {
            callCount: this.#includeRawScriptCoverage,
            detailed: useBlockCoverage
          }),
          this.#client.send("Debugger.enable"),
          this.#client.send("Debugger.setSkipAllPauses", { skip: true })
        ]);
      }
      #onExecutionContextsCleared() {
        if (!this.#resetOnNavigation) {
          return;
        }
        this.#scriptURLs.clear();
        this.#scriptSources.clear();
      }
      async #onScriptParsed(event) {
        if (util_js_1.PuppeteerURL.isPuppeteerURL(event.url)) {
          return;
        }
        if (!event.url && !this.#reportAnonymousScripts) {
          return;
        }
        try {
          const response = await this.#client.send("Debugger.getScriptSource", {
            scriptId: event.scriptId
          });
          this.#scriptURLs.set(event.scriptId, event.url);
          this.#scriptSources.set(event.scriptId, response.scriptSource);
        } catch (error) {
          (0, util_js_1.debugError)(error);
        }
      }
      async stop() {
        (0, assert_js_1.assert)(this.#enabled, "JSCoverage is not enabled");
        this.#enabled = false;
        const result = await Promise.all([
          this.#client.send("Profiler.takePreciseCoverage"),
          this.#client.send("Profiler.stopPreciseCoverage"),
          this.#client.send("Profiler.disable"),
          this.#client.send("Debugger.disable")
        ]);
        this.#subscriptions?.dispose();
        const coverage = [];
        const profileResponse = result[0];
        for (const entry of profileResponse.result) {
          let url = this.#scriptURLs.get(entry.scriptId);
          if (!url && this.#reportAnonymousScripts) {
            url = "debugger://VM" + entry.scriptId;
          }
          const text = this.#scriptSources.get(entry.scriptId);
          if (text === void 0 || url === void 0) {
            continue;
          }
          const flattenRanges = [];
          for (const func of entry.functions) {
            flattenRanges.push(...func.ranges);
          }
          const ranges = convertToDisjointRanges(flattenRanges);
          if (!this.#includeRawScriptCoverage) {
            coverage.push({ url, ranges, text });
          } else {
            coverage.push({ url, ranges, text, rawScriptCoverage: entry });
          }
        }
        return coverage;
      }
    };
    exports2.JSCoverage = JSCoverage;
    var CSSCoverage = class {
      #client;
      #enabled = false;
      #stylesheetURLs = /* @__PURE__ */ new Map();
      #stylesheetSources = /* @__PURE__ */ new Map();
      #eventListeners;
      #resetOnNavigation = false;
      constructor(client2) {
        this.#client = client2;
      }
      /**
       * @internal
       */
      updateClient(client2) {
        this.#client = client2;
      }
      async start(options = {}) {
        (0, assert_js_1.assert)(!this.#enabled, "CSSCoverage is already enabled");
        const { resetOnNavigation = true } = options;
        this.#resetOnNavigation = resetOnNavigation;
        this.#enabled = true;
        this.#stylesheetURLs.clear();
        this.#stylesheetSources.clear();
        this.#eventListeners = new disposable_js_1.DisposableStack();
        const clientEmitter = this.#eventListeners.use(new EventEmitter_js_1.EventEmitter(this.#client));
        clientEmitter.on("CSS.styleSheetAdded", this.#onStyleSheet.bind(this));
        clientEmitter.on("Runtime.executionContextsCleared", this.#onExecutionContextsCleared.bind(this));
        await Promise.all([
          this.#client.send("DOM.enable"),
          this.#client.send("CSS.enable"),
          this.#client.send("CSS.startRuleUsageTracking")
        ]);
      }
      #onExecutionContextsCleared() {
        if (!this.#resetOnNavigation) {
          return;
        }
        this.#stylesheetURLs.clear();
        this.#stylesheetSources.clear();
      }
      async #onStyleSheet(event) {
        const header = event.header;
        if (!header.sourceURL) {
          return;
        }
        try {
          const response = await this.#client.send("CSS.getStyleSheetText", {
            styleSheetId: header.styleSheetId
          });
          this.#stylesheetURLs.set(header.styleSheetId, header.sourceURL);
          this.#stylesheetSources.set(header.styleSheetId, response.text);
        } catch (error) {
          (0, util_js_1.debugError)(error);
        }
      }
      async stop() {
        (0, assert_js_1.assert)(this.#enabled, "CSSCoverage is not enabled");
        this.#enabled = false;
        const ruleTrackingResponse = await this.#client.send("CSS.stopRuleUsageTracking");
        await Promise.all([
          this.#client.send("CSS.disable"),
          this.#client.send("DOM.disable")
        ]);
        this.#eventListeners?.dispose();
        const styleSheetIdToCoverage = /* @__PURE__ */ new Map();
        for (const entry of ruleTrackingResponse.ruleUsage) {
          let ranges = styleSheetIdToCoverage.get(entry.styleSheetId);
          if (!ranges) {
            ranges = [];
            styleSheetIdToCoverage.set(entry.styleSheetId, ranges);
          }
          ranges.push({
            startOffset: entry.startOffset,
            endOffset: entry.endOffset,
            count: entry.used ? 1 : 0
          });
        }
        const coverage = [];
        for (const styleSheetId of this.#stylesheetURLs.keys()) {
          const url = this.#stylesheetURLs.get(styleSheetId);
          (0, assert_js_1.assert)(typeof url !== "undefined", `Stylesheet URL is undefined (styleSheetId=${styleSheetId})`);
          const text = this.#stylesheetSources.get(styleSheetId);
          (0, assert_js_1.assert)(typeof text !== "undefined", `Stylesheet text is undefined (styleSheetId=${styleSheetId})`);
          const ranges = convertToDisjointRanges(styleSheetIdToCoverage.get(styleSheetId) || []);
          coverage.push({ url, ranges, text });
        }
        return coverage;
      }
    };
    exports2.CSSCoverage = CSSCoverage;
    function convertToDisjointRanges(nestedRanges) {
      const points = [];
      for (const range of nestedRanges) {
        points.push({ offset: range.startOffset, type: 0, range });
        points.push({ offset: range.endOffset, type: 1, range });
      }
      points.sort((a, b) => {
        if (a.offset !== b.offset) {
          return a.offset - b.offset;
        }
        if (a.type !== b.type) {
          return b.type - a.type;
        }
        const aLength = a.range.endOffset - a.range.startOffset;
        const bLength = b.range.endOffset - b.range.startOffset;
        if (a.type === 0) {
          return bLength - aLength;
        }
        return aLength - bLength;
      });
      const hitCountStack = [];
      const results = [];
      let lastOffset = 0;
      for (const point of points) {
        if (hitCountStack.length && lastOffset < point.offset && hitCountStack[hitCountStack.length - 1] > 0) {
          const lastResult = results[results.length - 1];
          if (lastResult && lastResult.end === lastOffset) {
            lastResult.end = point.offset;
          } else {
            results.push({ start: lastOffset, end: point.offset });
          }
        }
        lastOffset = point.offset;
        if (point.type === 0) {
          hitCountStack.push(point.range.count);
        } else {
          hitCountStack.pop();
        }
      }
      return results.filter((range) => {
        return range.end - range.start > 0;
      });
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Dialog.js
var require_Dialog2 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Dialog.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CdpDialog = void 0;
    var Dialog_js_1 = require_Dialog();
    var CdpDialog = class extends Dialog_js_1.Dialog {
      #client;
      constructor(client2, type, message, defaultValue = "") {
        super(type, message, defaultValue);
        this.#client = client2;
      }
      async handle(options) {
        await this.#client.send("Page.handleJavaScriptDialog", {
          accept: options.accept,
          promptText: options.text
        });
      }
    };
    exports2.CdpDialog = CdpDialog;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/EmulationManager.js
var require_EmulationManager = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/EmulationManager.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    var __setFunctionName2 = exports2 && exports2.__setFunctionName || function(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 });
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.EmulationManager = exports2.EmulatedState = void 0;
    var CDPSession_js_1 = require_CDPSession();
    var util_js_1 = require_util();
    var assert_js_1 = require_assert();
    var decorators_js_1 = require_decorators();
    var ErrorLike_js_1 = require_ErrorLike();
    var EmulatedState = class {
      #state;
      #clientProvider;
      #updater;
      constructor(initialState, clientProvider, updater) {
        this.#state = initialState;
        this.#clientProvider = clientProvider;
        this.#updater = updater;
        this.#clientProvider.registerState(this);
      }
      async setState(state) {
        this.#state = state;
        await this.sync();
      }
      get state() {
        return this.#state;
      }
      async sync() {
        await Promise.all(this.#clientProvider.clients().map((client2) => {
          return this.#updater(client2, this.#state);
        }));
      }
    };
    exports2.EmulatedState = EmulatedState;
    var EmulationManager = (() => {
      let _instanceExtraInitializers = [];
      let _private_applyViewport_decorators;
      let _private_applyViewport_descriptor;
      let _private_emulateIdleState_decorators;
      let _private_emulateIdleState_descriptor;
      let _private_emulateTimezone_decorators;
      let _private_emulateTimezone_descriptor;
      let _private_emulateVisionDeficiency_decorators;
      let _private_emulateVisionDeficiency_descriptor;
      let _private_emulateCpuThrottling_decorators;
      let _private_emulateCpuThrottling_descriptor;
      let _private_emulateMediaFeatures_decorators;
      let _private_emulateMediaFeatures_descriptor;
      let _private_emulateMediaType_decorators;
      let _private_emulateMediaType_descriptor;
      let _private_setGeolocation_decorators;
      let _private_setGeolocation_descriptor;
      let _private_setDefaultBackgroundColor_decorators;
      let _private_setDefaultBackgroundColor_descriptor;
      let _private_setJavaScriptEnabled_decorators;
      let _private_setJavaScriptEnabled_descriptor;
      let _private_emulateFocus_decorators;
      let _private_emulateFocus_descriptor;
      return class EmulationManager {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? /* @__PURE__ */ Object.create(null) : void 0;
          _private_applyViewport_decorators = [decorators_js_1.invokeAtMostOnceForArguments];
          _private_emulateIdleState_decorators = [decorators_js_1.invokeAtMostOnceForArguments];
          _private_emulateTimezone_decorators = [decorators_js_1.invokeAtMostOnceForArguments];
          _private_emulateVisionDeficiency_decorators = [decorators_js_1.invokeAtMostOnceForArguments];
          _private_emulateCpuThrottling_decorators = [decorators_js_1.invokeAtMostOnceForArguments];
          _private_emulateMediaFeatures_decorators = [decorators_js_1.invokeAtMostOnceForArguments];
          _private_emulateMediaType_decorators = [decorators_js_1.invokeAtMostOnceForArguments];
          _private_setGeolocation_decorators = [decorators_js_1.invokeAtMostOnceForArguments];
          _private_setDefaultBackgroundColor_decorators = [decorators_js_1.invokeAtMostOnceForArguments];
          _private_setJavaScriptEnabled_decorators = [decorators_js_1.invokeAtMostOnceForArguments];
          _private_emulateFocus_decorators = [decorators_js_1.invokeAtMostOnceForArguments];
          __esDecorate2(this, _private_applyViewport_descriptor = { value: __setFunctionName2(async function(client2, viewportState) {
            if (!viewportState.viewport) {
              await Promise.all([
                client2.send("Emulation.clearDeviceMetricsOverride"),
                client2.send("Emulation.setTouchEmulationEnabled", {
                  enabled: false
                })
              ]).catch(util_js_1.debugError);
              return;
            }
            const { viewport } = viewportState;
            const mobile = viewport.isMobile || false;
            const width = viewport.width;
            const height = viewport.height;
            const deviceScaleFactor = viewport.deviceScaleFactor ?? 1;
            const screenOrientation = viewport.isLandscape ? { angle: 90, type: "landscapePrimary" } : { angle: 0, type: "portraitPrimary" };
            const hasTouch = viewport.hasTouch || false;
            await Promise.all([
              client2.send("Emulation.setDeviceMetricsOverride", {
                mobile,
                width,
                height,
                deviceScaleFactor,
                screenOrientation
              }).catch((err) => {
                if (err.message.includes("Target does not support metrics override")) {
                  (0, util_js_1.debugError)(err);
                  return;
                }
                throw err;
              }),
              client2.send("Emulation.setTouchEmulationEnabled", {
                enabled: hasTouch
              })
            ]);
          }, "#applyViewport") }, _private_applyViewport_decorators, { kind: "method", name: "#applyViewport", static: false, private: true, access: { has: (obj) => #applyViewport in obj, get: (obj) => obj.#applyViewport }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, _private_emulateIdleState_descriptor = { value: __setFunctionName2(async function(client2, idleStateState) {
            if (!idleStateState.active) {
              return;
            }
            if (idleStateState.overrides) {
              await client2.send("Emulation.setIdleOverride", {
                isUserActive: idleStateState.overrides.isUserActive,
                isScreenUnlocked: idleStateState.overrides.isScreenUnlocked
              });
            } else {
              await client2.send("Emulation.clearIdleOverride");
            }
          }, "#emulateIdleState") }, _private_emulateIdleState_decorators, { kind: "method", name: "#emulateIdleState", static: false, private: true, access: { has: (obj) => #emulateIdleState in obj, get: (obj) => obj.#emulateIdleState }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, _private_emulateTimezone_descriptor = { value: __setFunctionName2(async function(client2, timezoneState) {
            if (!timezoneState.active) {
              return;
            }
            try {
              await client2.send("Emulation.setTimezoneOverride", {
                timezoneId: timezoneState.timezoneId || ""
              });
            } catch (error) {
              if ((0, ErrorLike_js_1.isErrorLike)(error) && error.message.includes("Invalid timezone")) {
                throw new Error(`Invalid timezone ID: ${timezoneState.timezoneId}`);
              }
              throw error;
            }
          }, "#emulateTimezone") }, _private_emulateTimezone_decorators, { kind: "method", name: "#emulateTimezone", static: false, private: true, access: { has: (obj) => #emulateTimezone in obj, get: (obj) => obj.#emulateTimezone }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, _private_emulateVisionDeficiency_descriptor = { value: __setFunctionName2(async function(client2, visionDeficiency) {
            if (!visionDeficiency.active) {
              return;
            }
            await client2.send("Emulation.setEmulatedVisionDeficiency", {
              type: visionDeficiency.visionDeficiency || "none"
            });
          }, "#emulateVisionDeficiency") }, _private_emulateVisionDeficiency_decorators, { kind: "method", name: "#emulateVisionDeficiency", static: false, private: true, access: { has: (obj) => #emulateVisionDeficiency in obj, get: (obj) => obj.#emulateVisionDeficiency }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, _private_emulateCpuThrottling_descriptor = { value: __setFunctionName2(async function(client2, state) {
            if (!state.active) {
              return;
            }
            await client2.send("Emulation.setCPUThrottlingRate", {
              rate: state.factor ?? 1
            });
          }, "#emulateCpuThrottling") }, _private_emulateCpuThrottling_decorators, { kind: "method", name: "#emulateCpuThrottling", static: false, private: true, access: { has: (obj) => #emulateCpuThrottling in obj, get: (obj) => obj.#emulateCpuThrottling }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, _private_emulateMediaFeatures_descriptor = { value: __setFunctionName2(async function(client2, state) {
            if (!state.active) {
              return;
            }
            await client2.send("Emulation.setEmulatedMedia", {
              features: state.mediaFeatures
            });
          }, "#emulateMediaFeatures") }, _private_emulateMediaFeatures_decorators, { kind: "method", name: "#emulateMediaFeatures", static: false, private: true, access: { has: (obj) => #emulateMediaFeatures in obj, get: (obj) => obj.#emulateMediaFeatures }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, _private_emulateMediaType_descriptor = { value: __setFunctionName2(async function(client2, state) {
            if (!state.active) {
              return;
            }
            await client2.send("Emulation.setEmulatedMedia", {
              media: state.type || ""
            });
          }, "#emulateMediaType") }, _private_emulateMediaType_decorators, { kind: "method", name: "#emulateMediaType", static: false, private: true, access: { has: (obj) => #emulateMediaType in obj, get: (obj) => obj.#emulateMediaType }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, _private_setGeolocation_descriptor = { value: __setFunctionName2(async function(client2, state) {
            if (!state.active) {
              return;
            }
            await client2.send("Emulation.setGeolocationOverride", state.geoLocation ? {
              longitude: state.geoLocation.longitude,
              latitude: state.geoLocation.latitude,
              accuracy: state.geoLocation.accuracy
            } : void 0);
          }, "#setGeolocation") }, _private_setGeolocation_decorators, { kind: "method", name: "#setGeolocation", static: false, private: true, access: { has: (obj) => #setGeolocation in obj, get: (obj) => obj.#setGeolocation }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, _private_setDefaultBackgroundColor_descriptor = { value: __setFunctionName2(async function(client2, state) {
            if (!state.active) {
              return;
            }
            await client2.send("Emulation.setDefaultBackgroundColorOverride", {
              color: state.color
            });
          }, "#setDefaultBackgroundColor") }, _private_setDefaultBackgroundColor_decorators, { kind: "method", name: "#setDefaultBackgroundColor", static: false, private: true, access: { has: (obj) => #setDefaultBackgroundColor in obj, get: (obj) => obj.#setDefaultBackgroundColor }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, _private_setJavaScriptEnabled_descriptor = { value: __setFunctionName2(async function(client2, state) {
            if (!state.active) {
              return;
            }
            await client2.send("Emulation.setScriptExecutionDisabled", {
              value: !state.javaScriptEnabled
            });
          }, "#setJavaScriptEnabled") }, _private_setJavaScriptEnabled_decorators, { kind: "method", name: "#setJavaScriptEnabled", static: false, private: true, access: { has: (obj) => #setJavaScriptEnabled in obj, get: (obj) => obj.#setJavaScriptEnabled }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, _private_emulateFocus_descriptor = { value: __setFunctionName2(async function(client2, state) {
            if (!state.active) {
              return;
            }
            await client2.send("Emulation.setFocusEmulationEnabled", {
              enabled: state.enabled
            });
          }, "#emulateFocus") }, _private_emulateFocus_decorators, { kind: "method", name: "#emulateFocus", static: false, private: true, access: { has: (obj) => #emulateFocus in obj, get: (obj) => obj.#emulateFocus }, metadata: _metadata }, null, _instanceExtraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #client = __runInitializers2(this, _instanceExtraInitializers);
        #emulatingMobile = false;
        #hasTouch = false;
        #states = [];
        #viewportState = new EmulatedState({
          active: false
        }, this, this.#applyViewport);
        #idleOverridesState = new EmulatedState({
          active: false
        }, this, this.#emulateIdleState);
        #timezoneState = new EmulatedState({
          active: false
        }, this, this.#emulateTimezone);
        #visionDeficiencyState = new EmulatedState({
          active: false
        }, this, this.#emulateVisionDeficiency);
        #cpuThrottlingState = new EmulatedState({
          active: false
        }, this, this.#emulateCpuThrottling);
        #mediaFeaturesState = new EmulatedState({
          active: false
        }, this, this.#emulateMediaFeatures);
        #mediaTypeState = new EmulatedState({
          active: false
        }, this, this.#emulateMediaType);
        #geoLocationState = new EmulatedState({
          active: false
        }, this, this.#setGeolocation);
        #defaultBackgroundColorState = new EmulatedState({
          active: false
        }, this, this.#setDefaultBackgroundColor);
        #javascriptEnabledState = new EmulatedState({
          javaScriptEnabled: true,
          active: false
        }, this, this.#setJavaScriptEnabled);
        #focusState = new EmulatedState({
          enabled: true,
          active: false
        }, this, this.#emulateFocus);
        #secondaryClients = /* @__PURE__ */ new Set();
        constructor(client2) {
          this.#client = client2;
        }
        updateClient(client2) {
          this.#client = client2;
          this.#secondaryClients.delete(client2);
        }
        registerState(state) {
          this.#states.push(state);
        }
        clients() {
          return [this.#client, ...Array.from(this.#secondaryClients)];
        }
        async registerSpeculativeSession(client2) {
          this.#secondaryClients.add(client2);
          client2.once(CDPSession_js_1.CDPSessionEvent.Disconnected, () => {
            this.#secondaryClients.delete(client2);
          });
          void Promise.all(this.#states.map((s) => {
            return s.sync().catch(util_js_1.debugError);
          }));
        }
        get javascriptEnabled() {
          return this.#javascriptEnabledState.state.javaScriptEnabled;
        }
        async emulateViewport(viewport) {
          const currentState = this.#viewportState.state;
          if (!viewport && !currentState.active) {
            return false;
          }
          await this.#viewportState.setState(viewport ? {
            viewport,
            active: true
          } : {
            active: false
          });
          const mobile = viewport?.isMobile || false;
          const hasTouch = viewport?.hasTouch || false;
          const reloadNeeded = this.#emulatingMobile !== mobile || this.#hasTouch !== hasTouch;
          this.#emulatingMobile = mobile;
          this.#hasTouch = hasTouch;
          return reloadNeeded;
        }
        get #applyViewport() {
          return _private_applyViewport_descriptor.value;
        }
        async emulateIdleState(overrides) {
          await this.#idleOverridesState.setState({
            active: true,
            overrides
          });
        }
        get #emulateIdleState() {
          return _private_emulateIdleState_descriptor.value;
        }
        get #emulateTimezone() {
          return _private_emulateTimezone_descriptor.value;
        }
        async emulateTimezone(timezoneId) {
          await this.#timezoneState.setState({
            timezoneId,
            active: true
          });
        }
        get #emulateVisionDeficiency() {
          return _private_emulateVisionDeficiency_descriptor.value;
        }
        async emulateVisionDeficiency(type) {
          const visionDeficiencies = /* @__PURE__ */ new Set([
            "none",
            "achromatopsia",
            "blurredVision",
            "deuteranopia",
            "protanopia",
            "reducedContrast",
            "tritanopia"
          ]);
          (0, assert_js_1.assert)(!type || visionDeficiencies.has(type), `Unsupported vision deficiency: ${type}`);
          await this.#visionDeficiencyState.setState({
            active: true,
            visionDeficiency: type
          });
        }
        get #emulateCpuThrottling() {
          return _private_emulateCpuThrottling_descriptor.value;
        }
        async emulateCPUThrottling(factor) {
          (0, assert_js_1.assert)(factor === null || factor >= 1, "Throttling rate should be greater or equal to 1");
          await this.#cpuThrottlingState.setState({
            active: true,
            factor: factor ?? void 0
          });
        }
        get #emulateMediaFeatures() {
          return _private_emulateMediaFeatures_descriptor.value;
        }
        async emulateMediaFeatures(features) {
          if (Array.isArray(features)) {
            for (const mediaFeature of features) {
              const name = mediaFeature.name;
              (0, assert_js_1.assert)(/^(?:prefers-(?:color-scheme|reduced-motion)|color-gamut)$/.test(name), "Unsupported media feature: " + name);
            }
          }
          await this.#mediaFeaturesState.setState({
            active: true,
            mediaFeatures: features
          });
        }
        get #emulateMediaType() {
          return _private_emulateMediaType_descriptor.value;
        }
        async emulateMediaType(type) {
          (0, assert_js_1.assert)(type === "screen" || type === "print" || (type ?? void 0) === void 0, "Unsupported media type: " + type);
          await this.#mediaTypeState.setState({
            type,
            active: true
          });
        }
        get #setGeolocation() {
          return _private_setGeolocation_descriptor.value;
        }
        async setGeolocation(options) {
          const { longitude, latitude, accuracy = 0 } = options;
          if (longitude < -180 || longitude > 180) {
            throw new Error(`Invalid longitude "${longitude}": precondition -180 <= LONGITUDE <= 180 failed.`);
          }
          if (latitude < -90 || latitude > 90) {
            throw new Error(`Invalid latitude "${latitude}": precondition -90 <= LATITUDE <= 90 failed.`);
          }
          if (accuracy < 0) {
            throw new Error(`Invalid accuracy "${accuracy}": precondition 0 <= ACCURACY failed.`);
          }
          await this.#geoLocationState.setState({
            active: true,
            geoLocation: {
              longitude,
              latitude,
              accuracy
            }
          });
        }
        get #setDefaultBackgroundColor() {
          return _private_setDefaultBackgroundColor_descriptor.value;
        }
        /**
         * Resets default white background
         */
        async resetDefaultBackgroundColor() {
          await this.#defaultBackgroundColorState.setState({
            active: true,
            color: void 0
          });
        }
        /**
         * Hides default white background
         */
        async setTransparentBackgroundColor() {
          await this.#defaultBackgroundColorState.setState({
            active: true,
            color: { r: 0, g: 0, b: 0, a: 0 }
          });
        }
        get #setJavaScriptEnabled() {
          return _private_setJavaScriptEnabled_descriptor.value;
        }
        async setJavaScriptEnabled(enabled) {
          await this.#javascriptEnabledState.setState({
            active: true,
            javaScriptEnabled: enabled
          });
        }
        get #emulateFocus() {
          return _private_emulateFocus_descriptor.value;
        }
        async emulateFocus(enabled) {
          await this.#focusState.setState({
            active: true,
            enabled
          });
        }
      };
    })();
    exports2.EmulationManager = EmulationManager;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/CdpPreloadScript.js
var require_CdpPreloadScript = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/CdpPreloadScript.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CdpPreloadScript = void 0;
    var CdpPreloadScript = class {
      /**
       * This is the ID of the preload script returned by
       * Page.addScriptToEvaluateOnNewDocument in the main frame.
       *
       * Sub-frames would get a different CDP ID because
       * addScriptToEvaluateOnNewDocument is called for each subframe. But
       * users only see this ID and subframe IDs are internal to Puppeteer.
       */
      #id;
      #source;
      #frameToId = /* @__PURE__ */ new WeakMap();
      constructor(mainFrame, id, source) {
        this.#id = id;
        this.#source = source;
        this.#frameToId.set(mainFrame, id);
      }
      get id() {
        return this.#id;
      }
      get source() {
        return this.#source;
      }
      getIdForFrame(frame) {
        return this.#frameToId.get(frame);
      }
      setIdForFrame(frame, identifier) {
        this.#frameToId.set(frame, identifier);
      }
    };
    exports2.CdpPreloadScript = CdpPreloadScript;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/DeviceRequestPrompt.js
var require_DeviceRequestPrompt2 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/DeviceRequestPrompt.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CdpDeviceRequestPromptManager = exports2.CdpDeviceRequestPrompt = void 0;
    var DeviceRequestPrompt_js_1 = require_DeviceRequestPrompt();
    var assert_js_1 = require_assert();
    var Deferred_js_1 = require_Deferred();
    var CdpDeviceRequestPrompt = class extends DeviceRequestPrompt_js_1.DeviceRequestPrompt {
      #client;
      #timeoutSettings;
      #id;
      #handled = false;
      #updateDevicesHandle = this.#updateDevices.bind(this);
      #waitForDevicePromises = /* @__PURE__ */ new Set();
      constructor(client2, timeoutSettings, firstEvent) {
        super();
        this.#client = client2;
        this.#timeoutSettings = timeoutSettings;
        this.#id = firstEvent.id;
        this.#client.on("DeviceAccess.deviceRequestPrompted", this.#updateDevicesHandle);
        this.#client.on("Target.detachedFromTarget", () => {
          this.#client = null;
        });
        this.#updateDevices(firstEvent);
      }
      #updateDevices(event) {
        if (event.id !== this.#id) {
          return;
        }
        for (const rawDevice of event.devices) {
          if (this.devices.some((device) => {
            return device.id === rawDevice.id;
          })) {
            continue;
          }
          const newDevice = { id: rawDevice.id, name: rawDevice.name };
          this.devices.push(newDevice);
          for (const waitForDevicePromise of this.#waitForDevicePromises) {
            if (waitForDevicePromise.filter(newDevice)) {
              waitForDevicePromise.promise.resolve(newDevice);
            }
          }
        }
      }
      async waitForDevice(filter, options = {}) {
        for (const device of this.devices) {
          if (filter(device)) {
            return device;
          }
        }
        const { timeout = this.#timeoutSettings.timeout() } = options;
        const deferred = Deferred_js_1.Deferred.create({
          message: `Waiting for \`DeviceRequestPromptDevice\` failed: ${timeout}ms exceeded`,
          timeout
        });
        if (options.signal) {
          options.signal.addEventListener("abort", () => {
            deferred.reject(options.signal?.reason);
          }, { once: true });
        }
        const handle = { filter, promise: deferred };
        this.#waitForDevicePromises.add(handle);
        try {
          return await deferred.valueOrThrow();
        } finally {
          this.#waitForDevicePromises.delete(handle);
        }
      }
      async select(device) {
        (0, assert_js_1.assert)(this.#client !== null, "Cannot select device through detached session!");
        (0, assert_js_1.assert)(this.devices.includes(device), "Cannot select unknown device!");
        (0, assert_js_1.assert)(!this.#handled, "Cannot select DeviceRequestPrompt which is already handled!");
        this.#client.off("DeviceAccess.deviceRequestPrompted", this.#updateDevicesHandle);
        this.#handled = true;
        return await this.#client.send("DeviceAccess.selectPrompt", {
          id: this.#id,
          deviceId: device.id
        });
      }
      async cancel() {
        (0, assert_js_1.assert)(this.#client !== null, "Cannot cancel prompt through detached session!");
        (0, assert_js_1.assert)(!this.#handled, "Cannot cancel DeviceRequestPrompt which is already handled!");
        this.#client.off("DeviceAccess.deviceRequestPrompted", this.#updateDevicesHandle);
        this.#handled = true;
        return await this.#client.send("DeviceAccess.cancelPrompt", { id: this.#id });
      }
    };
    exports2.CdpDeviceRequestPrompt = CdpDeviceRequestPrompt;
    var CdpDeviceRequestPromptManager = class {
      #client;
      #timeoutSettings;
      #deviceRequestPromptDeferreds = /* @__PURE__ */ new Set();
      constructor(client2, timeoutSettings) {
        this.#client = client2;
        this.#timeoutSettings = timeoutSettings;
        this.#client.on("DeviceAccess.deviceRequestPrompted", (event) => {
          this.#onDeviceRequestPrompted(event);
        });
        this.#client.on("Target.detachedFromTarget", () => {
          this.#client = null;
        });
      }
      async waitForDevicePrompt(options = {}) {
        (0, assert_js_1.assert)(this.#client !== null, "Cannot wait for device prompt through detached session!");
        const needsEnable = this.#deviceRequestPromptDeferreds.size === 0;
        let enablePromise;
        if (needsEnable) {
          enablePromise = this.#client.send("DeviceAccess.enable");
        }
        const { timeout = this.#timeoutSettings.timeout() } = options;
        const deferred = Deferred_js_1.Deferred.create({
          message: `Waiting for \`DeviceRequestPrompt\` failed: ${timeout}ms exceeded`,
          timeout
        });
        if (options.signal) {
          options.signal.addEventListener("abort", () => {
            deferred.reject(options.signal?.reason);
          }, { once: true });
        }
        this.#deviceRequestPromptDeferreds.add(deferred);
        try {
          const [result] = await Promise.all([
            deferred.valueOrThrow(),
            enablePromise
          ]);
          return result;
        } finally {
          this.#deviceRequestPromptDeferreds.delete(deferred);
        }
      }
      #onDeviceRequestPrompted(event) {
        if (!this.#deviceRequestPromptDeferreds.size) {
          return;
        }
        (0, assert_js_1.assert)(this.#client !== null);
        const devicePrompt = new CdpDeviceRequestPrompt(this.#client, this.#timeoutSettings, event);
        for (const promise of this.#deviceRequestPromptDeferreds) {
          promise.resolve(devicePrompt);
        }
        this.#deviceRequestPromptDeferreds.clear();
      }
    };
    exports2.CdpDeviceRequestPromptManager = CdpDeviceRequestPromptManager;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/utils.js
var require_utils = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/utils.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CDP_BINDING_PREFIX = void 0;
    exports2.createEvaluationError = createEvaluationError;
    exports2.createClientError = createClientError;
    exports2.valueFromJSHandle = valueFromJSHandle;
    exports2.valueFromRemoteObjectReference = valueFromRemoteObjectReference;
    exports2.valueFromPrimitiveRemoteObject = valueFromPrimitiveRemoteObject;
    exports2.addPageBinding = addPageBinding;
    exports2.pageBindingInitString = pageBindingInitString;
    var util_js_1 = require_util();
    var assert_js_1 = require_assert();
    function createEvaluationError(details) {
      let name;
      let message;
      if (!details.exception) {
        name = "Error";
        message = details.text;
      } else if ((details.exception.type !== "object" || details.exception.subtype !== "error") && !details.exception.objectId) {
        return valueFromPrimitiveRemoteObject(details.exception);
      } else {
        const detail = getErrorDetails(details);
        name = detail.name;
        message = detail.message;
      }
      const messageHeight = message.split("\n").length;
      const error = new Error(message);
      error.name = name;
      const stackLines = error.stack.split("\n");
      const messageLines = stackLines.splice(0, messageHeight);
      stackLines.shift();
      if (details.stackTrace && stackLines.length < Error.stackTraceLimit) {
        for (const frame of details.stackTrace.callFrames.reverse()) {
          if (util_js_1.PuppeteerURL.isPuppeteerURL(frame.url) && frame.url !== util_js_1.PuppeteerURL.INTERNAL_URL) {
            const url = util_js_1.PuppeteerURL.parse(frame.url);
            stackLines.unshift(`    at ${frame.functionName || url.functionName} (${url.functionName} at ${url.siteString}, <anonymous>:${frame.lineNumber}:${frame.columnNumber})`);
          } else {
            stackLines.push(`    at ${frame.functionName || "<anonymous>"} (${frame.url}:${frame.lineNumber}:${frame.columnNumber})`);
          }
          if (stackLines.length >= Error.stackTraceLimit) {
            break;
          }
        }
      }
      error.stack = [...messageLines, ...stackLines].join("\n");
      return error;
    }
    var getErrorDetails = (details) => {
      let name = "";
      let message;
      const lines = details.exception?.description?.split("\n    at ") ?? [];
      const size = Math.min(details.stackTrace?.callFrames.length ?? 0, lines.length - 1);
      lines.splice(-size, size);
      if (details.exception?.className) {
        name = details.exception.className;
      }
      message = lines.join("\n");
      if (name && message.startsWith(`${name}: `)) {
        message = message.slice(name.length + 2);
      }
      return { message, name };
    };
    function createClientError(details) {
      let name;
      let message;
      if (!details.exception) {
        name = "Error";
        message = details.text;
      } else if ((details.exception.type !== "object" || details.exception.subtype !== "error") && !details.exception.objectId) {
        return valueFromPrimitiveRemoteObject(details.exception);
      } else {
        const detail = getErrorDetails(details);
        name = detail.name;
        message = detail.message;
      }
      const error = new Error(message);
      error.name = name;
      const messageHeight = error.message.split("\n").length;
      const messageLines = error.stack.split("\n").splice(0, messageHeight);
      const stackLines = [];
      if (details.stackTrace) {
        for (const frame of details.stackTrace.callFrames) {
          stackLines.push(`    at ${frame.functionName || "<anonymous>"} (${frame.url}:${frame.lineNumber + 1}:${frame.columnNumber + 1})`);
          if (stackLines.length >= Error.stackTraceLimit) {
            break;
          }
        }
      }
      error.stack = [...messageLines, ...stackLines].join("\n");
      return error;
    }
    function valueFromJSHandle(handle) {
      const remoteObject = handle.remoteObject();
      if (remoteObject.objectId) {
        return valueFromRemoteObjectReference(handle);
      } else {
        return valueFromPrimitiveRemoteObject(remoteObject);
      }
    }
    function valueFromRemoteObjectReference(handle) {
      const remoteObject = handle.remoteObject();
      (0, assert_js_1.assert)(remoteObject.objectId, "Cannot extract value when no objectId is given");
      const description = remoteObject.description ?? "";
      if (remoteObject.subtype === "error" && description) {
        const newlineIdx = description.indexOf("\n");
        if (newlineIdx === -1) {
          return description;
        }
        return description.slice(0, newlineIdx);
      }
      return `[${remoteObject.subtype || remoteObject.type} ${remoteObject.className}]`;
    }
    function valueFromPrimitiveRemoteObject(remoteObject) {
      (0, assert_js_1.assert)(!remoteObject.objectId, "Cannot extract value when objectId is given");
      if (remoteObject.unserializableValue) {
        if (remoteObject.type === "bigint") {
          return BigInt(remoteObject.unserializableValue.replace("n", ""));
        }
        switch (remoteObject.unserializableValue) {
          case "-0":
            return -0;
          case "NaN":
            return NaN;
          case "Infinity":
            return Infinity;
          case "-Infinity":
            return -Infinity;
          default:
            throw new Error("Unsupported unserializable value: " + remoteObject.unserializableValue);
        }
      }
      return remoteObject.value;
    }
    function addPageBinding(type, name, prefix) {
      if (globalThis[name]) {
        return;
      }
      Object.assign(globalThis, {
        [name](...args2) {
          const callPuppeteer = globalThis[name];
          callPuppeteer.args ??= /* @__PURE__ */ new Map();
          callPuppeteer.callbacks ??= /* @__PURE__ */ new Map();
          const seq = (callPuppeteer.lastSeq ?? 0) + 1;
          callPuppeteer.lastSeq = seq;
          callPuppeteer.args.set(seq, args2);
          globalThis[prefix + name](JSON.stringify({
            type,
            name,
            seq,
            args: args2,
            isTrivial: !args2.some((value) => {
              return value instanceof Node;
            })
          }));
          return new Promise((resolve5, reject) => {
            callPuppeteer.callbacks.set(seq, {
              resolve(value) {
                callPuppeteer.args.delete(seq);
                resolve5(value);
              },
              reject(value) {
                callPuppeteer.args.delete(seq);
                reject(value);
              }
            });
          });
        }
      });
    }
    exports2.CDP_BINDING_PREFIX = "puppeteer_";
    function pageBindingInitString(type, name) {
      return (0, util_js_1.evaluationString)(addPageBinding, type, name, exports2.CDP_BINDING_PREFIX);
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/JSHandle.js
var require_JSHandle2 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/JSHandle.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CdpJSHandle = void 0;
    exports2.releaseObject = releaseObject;
    var JSHandle_js_1 = require_JSHandle();
    var util_js_1 = require_util();
    var utils_js_1 = require_utils();
    var CdpJSHandle = class extends JSHandle_js_1.JSHandle {
      #disposed = false;
      #remoteObject;
      #world;
      constructor(world, remoteObject) {
        super();
        this.#world = world;
        this.#remoteObject = remoteObject;
      }
      get disposed() {
        return this.#disposed;
      }
      get realm() {
        return this.#world;
      }
      get client() {
        return this.realm.environment.client;
      }
      async jsonValue() {
        if (!this.#remoteObject.objectId) {
          return (0, utils_js_1.valueFromPrimitiveRemoteObject)(this.#remoteObject);
        }
        const value = await this.evaluate((object) => {
          return object;
        });
        if (value === void 0) {
          throw new Error("Could not serialize referenced object");
        }
        return value;
      }
      /**
       * Either `null` or the handle itself if the handle is an
       * instance of {@link ElementHandle}.
       */
      asElement() {
        return null;
      }
      async dispose() {
        if (this.#disposed) {
          return;
        }
        this.#disposed = true;
        await releaseObject(this.client, this.#remoteObject);
      }
      toString() {
        if (!this.#remoteObject.objectId) {
          return "JSHandle:" + (0, utils_js_1.valueFromPrimitiveRemoteObject)(this.#remoteObject);
        }
        const type = this.#remoteObject.subtype || this.#remoteObject.type;
        return "JSHandle@" + type;
      }
      get id() {
        return this.#remoteObject.objectId;
      }
      remoteObject() {
        return this.#remoteObject;
      }
      async getProperties() {
        const response = await this.client.send("Runtime.getProperties", {
          objectId: this.#remoteObject.objectId,
          ownProperties: true
        });
        const result = /* @__PURE__ */ new Map();
        for (const property of response.result) {
          if (!property.enumerable || !property.value) {
            continue;
          }
          result.set(property.name, this.#world.createCdpHandle(property.value));
        }
        return result;
      }
    };
    exports2.CdpJSHandle = CdpJSHandle;
    async function releaseObject(client2, remoteObject) {
      if (!remoteObject.objectId) {
        return;
      }
      await client2.send("Runtime.releaseObject", { objectId: remoteObject.objectId }).catch((error) => {
        (0, util_js_1.debugError)(error);
      });
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ElementHandle.js
var require_ElementHandle2 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ElementHandle.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CdpElementHandle = void 0;
    var ElementHandle_js_1 = require_ElementHandle();
    var util_js_1 = require_util();
    var environment_js_1 = require_environment();
    var assert_js_1 = require_assert();
    var AsyncIterableUtil_js_1 = require_AsyncIterableUtil();
    var decorators_js_1 = require_decorators();
    var JSHandle_js_1 = require_JSHandle2();
    var NON_ELEMENT_NODE_ROLES = /* @__PURE__ */ new Set(["StaticText", "InlineTextBox"]);
    var CdpElementHandle = (() => {
      let _classSuper = ElementHandle_js_1.ElementHandle;
      let _instanceExtraInitializers = [];
      let _contentFrame_decorators;
      let _scrollIntoView_decorators;
      let _uploadFile_decorators;
      let _autofill_decorators;
      return class CdpElementHandle extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          _contentFrame_decorators = [(0, decorators_js_1.throwIfDisposed)()];
          _scrollIntoView_decorators = [(0, decorators_js_1.throwIfDisposed)(), ElementHandle_js_1.bindIsolatedHandle];
          _uploadFile_decorators = [(0, decorators_js_1.throwIfDisposed)(), ElementHandle_js_1.bindIsolatedHandle];
          _autofill_decorators = [(0, decorators_js_1.throwIfDisposed)()];
          __esDecorate2(this, null, _contentFrame_decorators, { kind: "method", name: "contentFrame", static: false, private: false, access: { has: (obj) => "contentFrame" in obj, get: (obj) => obj.contentFrame }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _scrollIntoView_decorators, { kind: "method", name: "scrollIntoView", static: false, private: false, access: { has: (obj) => "scrollIntoView" in obj, get: (obj) => obj.scrollIntoView }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _uploadFile_decorators, { kind: "method", name: "uploadFile", static: false, private: false, access: { has: (obj) => "uploadFile" in obj, get: (obj) => obj.uploadFile }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _autofill_decorators, { kind: "method", name: "autofill", static: false, private: false, access: { has: (obj) => "autofill" in obj, get: (obj) => obj.autofill }, metadata: _metadata }, null, _instanceExtraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #backendNodeId = __runInitializers2(this, _instanceExtraInitializers);
        constructor(world, remoteObject) {
          super(new JSHandle_js_1.CdpJSHandle(world, remoteObject));
        }
        get realm() {
          return this.handle.realm;
        }
        get client() {
          return this.handle.client;
        }
        remoteObject() {
          return this.handle.remoteObject();
        }
        get #frameManager() {
          return this.frame._frameManager;
        }
        get frame() {
          return this.realm.environment;
        }
        async contentFrame() {
          const nodeInfo = await this.client.send("DOM.describeNode", {
            objectId: this.id
          });
          if (typeof nodeInfo.node.frameId !== "string") {
            return null;
          }
          return this.#frameManager.frame(nodeInfo.node.frameId);
        }
        async scrollIntoView() {
          await this.assertConnectedElement();
          try {
            await this.client.send("DOM.scrollIntoViewIfNeeded", {
              objectId: this.id
            });
          } catch (error) {
            (0, util_js_1.debugError)(error);
            await super.scrollIntoView();
          }
        }
        async uploadFile(...files) {
          const isMultiple = await this.evaluate((element) => {
            return element.multiple;
          });
          (0, assert_js_1.assert)(files.length <= 1 || isMultiple, "Multiple file uploads only work with <input type=file multiple>");
          const path2 = environment_js_1.environment.value.path;
          if (path2) {
            files = files.map((filePath) => {
              if (path2.win32.isAbsolute(filePath) || path2.posix.isAbsolute(filePath)) {
                return filePath;
              } else {
                return path2.resolve(filePath);
              }
            });
          }
          if (files.length === 0) {
            await this.evaluate((element) => {
              element.files = new DataTransfer().files;
              element.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
              element.dispatchEvent(new Event("change", { bubbles: true }));
            });
            return;
          }
          const { node: { backendNodeId } } = await this.client.send("DOM.describeNode", {
            objectId: this.id
          });
          await this.client.send("DOM.setFileInputFiles", {
            objectId: this.id,
            files,
            backendNodeId
          });
        }
        async autofill(data) {
          const nodeInfo = await this.client.send("DOM.describeNode", {
            objectId: this.handle.id
          });
          const fieldId = nodeInfo.node.backendNodeId;
          const frameId = this.frame._id;
          await this.client.send("Autofill.trigger", {
            fieldId,
            frameId,
            card: data.creditCard
          });
        }
        async *queryAXTree(name, role) {
          const { nodes } = await this.client.send("Accessibility.queryAXTree", {
            objectId: this.id,
            accessibleName: name,
            role
          });
          const results = nodes.filter((node) => {
            if (node.ignored) {
              return false;
            }
            if (!node.role) {
              return false;
            }
            if (NON_ELEMENT_NODE_ROLES.has(node.role.value)) {
              return false;
            }
            return true;
          });
          return yield* AsyncIterableUtil_js_1.AsyncIterableUtil.map(results, (node) => {
            return this.realm.adoptBackendNode(node.backendDOMNodeId);
          });
        }
        async backendNodeId() {
          if (this.#backendNodeId) {
            return this.#backendNodeId;
          }
          const { node } = await this.client.send("DOM.describeNode", {
            objectId: this.handle.id
          });
          this.#backendNodeId = node.backendNodeId;
          return this.#backendNodeId;
        }
      };
    })();
    exports2.CdpElementHandle = CdpElementHandle;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ExecutionContext.js
var require_ExecutionContext = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ExecutionContext.js"(exports2) {
    "use strict";
    init_prefix();
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ExecutionContext = void 0;
    var CDPSession_js_1 = require_CDPSession();
    var AriaQueryHandler_js_1 = require_AriaQueryHandler();
    var EventEmitter_js_1 = require_EventEmitter();
    var LazyArg_js_1 = require_LazyArg();
    var ScriptInjector_js_1 = require_ScriptInjector();
    var util_js_1 = require_util();
    var AsyncIterableUtil_js_1 = require_AsyncIterableUtil();
    var disposable_js_1 = require_disposable();
    var Function_js_1 = require_Function();
    var Mutex_js_1 = require_Mutex();
    var Binding_js_1 = require_Binding();
    var ElementHandle_js_1 = require_ElementHandle2();
    var JSHandle_js_1 = require_JSHandle2();
    var utils_js_1 = require_utils();
    var ariaQuerySelectorBinding = new Binding_js_1.Binding("__ariaQuerySelector", AriaQueryHandler_js_1.ARIAQueryHandler.queryOne, "");
    var ariaQuerySelectorAllBinding = new Binding_js_1.Binding("__ariaQuerySelectorAll", (async (element, selector) => {
      const results = AriaQueryHandler_js_1.ARIAQueryHandler.queryAll(element, selector);
      return await element.realm.evaluateHandle((...elements) => {
        return elements;
      }, ...await AsyncIterableUtil_js_1.AsyncIterableUtil.collect(results));
    }), "");
    var ExecutionContext = class extends EventEmitter_js_1.EventEmitter {
      #client;
      #world;
      #id;
      #name;
      #disposables = new disposable_js_1.DisposableStack();
      constructor(client2, contextPayload, world) {
        super();
        this.#client = client2;
        this.#world = world;
        this.#id = contextPayload.id;
        if (contextPayload.name) {
          this.#name = contextPayload.name;
        }
        const clientEmitter = this.#disposables.use(new EventEmitter_js_1.EventEmitter(this.#client));
        clientEmitter.on("Runtime.bindingCalled", this.#onBindingCalled.bind(this));
        clientEmitter.on("Runtime.executionContextDestroyed", async (event) => {
          if (event.executionContextId === this.#id) {
            this[disposable_js_1.disposeSymbol]();
          }
        });
        clientEmitter.on("Runtime.executionContextsCleared", async () => {
          this[disposable_js_1.disposeSymbol]();
        });
        clientEmitter.on("Runtime.consoleAPICalled", this.#onConsoleAPI.bind(this));
        clientEmitter.on(CDPSession_js_1.CDPSessionEvent.Disconnected, () => {
          this[disposable_js_1.disposeSymbol]();
        });
      }
      // Contains mapping from functions that should be bound to Puppeteer functions.
      #bindings = /* @__PURE__ */ new Map();
      // If multiple waitFor are set up asynchronously, we need to wait for the
      // first one to set up the binding in the page before running the others.
      #mutex = new Mutex_js_1.Mutex();
      async #addBinding(binding) {
        const env_1 = { stack: [], error: void 0, hasError: false };
        try {
          if (this.#bindings.has(binding.name)) {
            return;
          }
          const _ = __addDisposableResource2(env_1, await this.#mutex.acquire(), false);
          try {
            await this.#client.send("Runtime.addBinding", this.#name ? {
              name: utils_js_1.CDP_BINDING_PREFIX + binding.name,
              executionContextName: this.#name
            } : {
              name: utils_js_1.CDP_BINDING_PREFIX + binding.name,
              executionContextId: this.#id
            });
            await this.evaluate(utils_js_1.addPageBinding, "internal", binding.name, utils_js_1.CDP_BINDING_PREFIX);
            this.#bindings.set(binding.name, binding);
          } catch (error) {
            if (error instanceof Error) {
              if (error.message.includes("Execution context was destroyed")) {
                return;
              }
              if (error.message.includes("Cannot find context with specified id")) {
                return;
              }
            }
            (0, util_js_1.debugError)(error);
          }
        } catch (e_1) {
          env_1.error = e_1;
          env_1.hasError = true;
        } finally {
          __disposeResources2(env_1);
        }
      }
      async #onBindingCalled(event) {
        if (event.executionContextId !== this.#id) {
          return;
        }
        let payload;
        try {
          payload = JSON.parse(event.payload);
        } catch {
          return;
        }
        const { type, name, seq, args: args2, isTrivial } = payload;
        if (type !== "internal") {
          this.emit("bindingcalled", event);
          return;
        }
        if (!this.#bindings.has(name)) {
          this.emit("bindingcalled", event);
          return;
        }
        try {
          const binding = this.#bindings.get(name);
          await binding?.run(this, seq, args2, isTrivial);
        } catch (err) {
          (0, util_js_1.debugError)(err);
        }
      }
      get id() {
        return this.#id;
      }
      #onConsoleAPI(event) {
        if (event.executionContextId !== this.#id) {
          return;
        }
        this.emit("consoleapicalled", event);
      }
      #bindingsInstalled = false;
      #puppeteerUtil;
      get puppeteerUtil() {
        let promise = Promise.resolve();
        if (!this.#bindingsInstalled) {
          promise = Promise.all([
            this.#addBindingWithoutThrowing(ariaQuerySelectorBinding),
            this.#addBindingWithoutThrowing(ariaQuerySelectorAllBinding)
          ]);
          this.#bindingsInstalled = true;
        }
        ScriptInjector_js_1.scriptInjector.inject((script) => {
          if (this.#puppeteerUtil) {
            void this.#puppeteerUtil.then((handle) => {
              void handle.dispose();
            });
          }
          this.#puppeteerUtil = promise.then(() => {
            return this.evaluateHandle(script);
          });
        }, !this.#puppeteerUtil);
        return this.#puppeteerUtil;
      }
      async #addBindingWithoutThrowing(binding) {
        try {
          await this.#addBinding(binding);
        } catch (err) {
          (0, util_js_1.debugError)(err);
        }
      }
      /**
       * Evaluates the given function.
       *
       * @example
       *
       * ```ts
       * const executionContext = await page.mainFrame().executionContext();
       * const result = await executionContext.evaluate(() => Promise.resolve(8 * 7))* ;
       * console.log(result); // prints "56"
       * ```
       *
       * @example
       * A string can also be passed in instead of a function:
       *
       * ```ts
       * console.log(await executionContext.evaluate('1 + 2')); // prints "3"
       * ```
       *
       * @example
       * Handles can also be passed as `args`. They resolve to their referenced object:
       *
       * ```ts
       * const oneHandle = await executionContext.evaluateHandle(() => 1);
       * const twoHandle = await executionContext.evaluateHandle(() => 2);
       * const result = await executionContext.evaluate(
       *   (a, b) => a + b,
       *   oneHandle,
       *   twoHandle,
       * );
       * await oneHandle.dispose();
       * await twoHandle.dispose();
       * console.log(result); // prints '3'.
       * ```
       *
       * @param pageFunction - The function to evaluate.
       * @param args - Additional arguments to pass into the function.
       * @returns The result of evaluating the function. If the result is an object,
       * a vanilla object containing the serializable properties of the result is
       * returned.
       */
      async evaluate(pageFunction, ...args2) {
        return await this.#evaluate(true, pageFunction, ...args2);
      }
      /**
       * Evaluates the given function.
       *
       * Unlike {@link ExecutionContext.evaluate | evaluate}, this method returns a
       * handle to the result of the function.
       *
       * This method may be better suited if the object cannot be serialized (e.g.
       * `Map`) and requires further manipulation.
       *
       * @example
       *
       * ```ts
       * const context = await page.mainFrame().executionContext();
       * const handle: JSHandle<typeof globalThis> = await context.evaluateHandle(
       *   () => Promise.resolve(self),
       * );
       * ```
       *
       * @example
       * A string can also be passed in instead of a function.
       *
       * ```ts
       * const handle: JSHandle<number> = await context.evaluateHandle('1 + 2');
       * ```
       *
       * @example
       * Handles can also be passed as `args`. They resolve to their referenced object:
       *
       * ```ts
       * const bodyHandle: ElementHandle<HTMLBodyElement> =
       *   await context.evaluateHandle(() => {
       *     return document.body;
       *   });
       * const stringHandle: JSHandle<string> = await context.evaluateHandle(
       *   body => body.innerHTML,
       *   body,
       * );
       * console.log(await stringHandle.jsonValue()); // prints body's innerHTML
       * // Always dispose your garbage! :)
       * await bodyHandle.dispose();
       * await stringHandle.dispose();
       * ```
       *
       * @param pageFunction - The function to evaluate.
       * @param args - Additional arguments to pass into the function.
       * @returns A {@link JSHandle | handle} to the result of evaluating the
       * function. If the result is a `Node`, then this will return an
       * {@link ElementHandle | element handle}.
       */
      async evaluateHandle(pageFunction, ...args2) {
        return await this.#evaluate(false, pageFunction, ...args2);
      }
      async #evaluate(returnByValue, pageFunction, ...args2) {
        const sourceUrlComment = (0, util_js_1.getSourceUrlComment)((0, util_js_1.getSourcePuppeteerURLIfAvailable)(pageFunction)?.toString() ?? util_js_1.PuppeteerURL.INTERNAL_URL);
        if ((0, util_js_1.isString)(pageFunction)) {
          const contextId = this.#id;
          const expression = pageFunction;
          const expressionWithSourceUrl = util_js_1.SOURCE_URL_REGEX.test(expression) ? expression : `${expression}
${sourceUrlComment}
`;
          const { exceptionDetails: exceptionDetails2, result: remoteObject2 } = await this.#client.send("Runtime.evaluate", {
            expression: expressionWithSourceUrl,
            contextId,
            returnByValue,
            awaitPromise: true,
            userGesture: true
          }).catch(rewriteError);
          if (exceptionDetails2) {
            throw (0, utils_js_1.createEvaluationError)(exceptionDetails2);
          }
          if (returnByValue) {
            return (0, utils_js_1.valueFromPrimitiveRemoteObject)(remoteObject2);
          }
          return this.#world.createCdpHandle(remoteObject2);
        }
        const functionDeclaration = (0, Function_js_1.stringifyFunction)(pageFunction);
        const functionDeclarationWithSourceUrl = util_js_1.SOURCE_URL_REGEX.test(functionDeclaration) ? functionDeclaration : `${functionDeclaration}
${sourceUrlComment}
`;
        let callFunctionOnPromise;
        try {
          callFunctionOnPromise = this.#client.send("Runtime.callFunctionOn", {
            functionDeclaration: functionDeclarationWithSourceUrl,
            executionContextId: this.#id,
            // LazyArgs are used only internally and should not affect the order
            // evaluate calls for the public APIs.
            arguments: args2.some((arg) => {
              return arg instanceof LazyArg_js_1.LazyArg;
            }) ? await Promise.all(args2.map((arg) => {
              return convertArgumentAsync(this, arg);
            })) : args2.map((arg) => {
              return convertArgument(this, arg);
            }),
            returnByValue,
            awaitPromise: true,
            userGesture: true
          });
        } catch (error) {
          if (error instanceof TypeError && error.message.startsWith("Converting circular structure to JSON")) {
            error.message += " Recursive objects are not allowed.";
          }
          throw error;
        }
        const { exceptionDetails, result: remoteObject } = await callFunctionOnPromise.catch(rewriteError);
        if (exceptionDetails) {
          throw (0, utils_js_1.createEvaluationError)(exceptionDetails);
        }
        if (returnByValue) {
          return (0, utils_js_1.valueFromPrimitiveRemoteObject)(remoteObject);
        }
        return this.#world.createCdpHandle(remoteObject);
        async function convertArgumentAsync(context, arg) {
          if (arg instanceof LazyArg_js_1.LazyArg) {
            arg = await arg.get(context);
          }
          return convertArgument(context, arg);
        }
        function convertArgument(context, arg) {
          if (typeof arg === "bigint") {
            return { unserializableValue: `${arg.toString()}n` };
          }
          if (Object.is(arg, -0)) {
            return { unserializableValue: "-0" };
          }
          if (Object.is(arg, Infinity)) {
            return { unserializableValue: "Infinity" };
          }
          if (Object.is(arg, -Infinity)) {
            return { unserializableValue: "-Infinity" };
          }
          if (Object.is(arg, NaN)) {
            return { unserializableValue: "NaN" };
          }
          const objectHandle = arg && (arg instanceof JSHandle_js_1.CdpJSHandle || arg instanceof ElementHandle_js_1.CdpElementHandle) ? arg : null;
          if (objectHandle) {
            if (objectHandle.realm !== context.#world) {
              throw new Error("JSHandles can be evaluated only in the context they were created!");
            }
            if (objectHandle.disposed) {
              throw new Error("JSHandle is disposed!");
            }
            if (objectHandle.remoteObject().unserializableValue) {
              return {
                unserializableValue: objectHandle.remoteObject().unserializableValue
              };
            }
            if (!objectHandle.remoteObject().objectId) {
              return { value: objectHandle.remoteObject().value };
            }
            return { objectId: objectHandle.remoteObject().objectId };
          }
          return { value: arg };
        }
      }
      [disposable_js_1.disposeSymbol]() {
        this.#disposables.dispose();
        this.emit("disposed", void 0);
      }
    };
    exports2.ExecutionContext = ExecutionContext;
    var rewriteError = (error) => {
      if (error.message.includes("Object reference chain is too long")) {
        return { result: { type: "undefined" } };
      }
      if (error.message.includes("Object couldn't be returned by value")) {
        return { result: { type: "undefined" } };
      }
      if (error.message.endsWith("Cannot find context with specified id") || error.message.endsWith("Inspected target navigated or closed")) {
        throw new Error("Execution context was destroyed, most likely because of a navigation.");
      }
      throw error;
    };
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/FrameManagerEvents.js
var require_FrameManagerEvents = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/FrameManagerEvents.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.FrameManagerEvent = void 0;
    var FrameManagerEvent;
    (function(FrameManagerEvent2) {
      FrameManagerEvent2.FrameAttached = /* @__PURE__ */ Symbol("FrameManager.FrameAttached");
      FrameManagerEvent2.FrameNavigated = /* @__PURE__ */ Symbol("FrameManager.FrameNavigated");
      FrameManagerEvent2.FrameDetached = /* @__PURE__ */ Symbol("FrameManager.FrameDetached");
      FrameManagerEvent2.FrameSwapped = /* @__PURE__ */ Symbol("FrameManager.FrameSwapped");
      FrameManagerEvent2.LifecycleEvent = /* @__PURE__ */ Symbol("FrameManager.LifecycleEvent");
      FrameManagerEvent2.FrameNavigatedWithinDocument = /* @__PURE__ */ Symbol("FrameManager.FrameNavigatedWithinDocument");
      FrameManagerEvent2.ConsoleApiCalled = /* @__PURE__ */ Symbol("FrameManager.ConsoleApiCalled");
      FrameManagerEvent2.BindingCalled = /* @__PURE__ */ Symbol("FrameManager.BindingCalled");
    })(FrameManagerEvent || (exports2.FrameManagerEvent = FrameManagerEvent = {}));
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/IsolatedWorld.js
var require_IsolatedWorld = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/IsolatedWorld.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.IsolatedWorld = void 0;
    var rxjs_js_1 = require_rxjs();
    var Realm_js_1 = require_Realm();
    var EventEmitter_js_1 = require_EventEmitter();
    var util_js_1 = require_util();
    var disposable_js_1 = require_disposable();
    var ElementHandle_js_1 = require_ElementHandle2();
    var JSHandle_js_1 = require_JSHandle2();
    var IsolatedWorld = class extends Realm_js_1.Realm {
      #context;
      #emitter = new EventEmitter_js_1.EventEmitter();
      #frameOrWorker;
      constructor(frameOrWorker, timeoutSettings) {
        super(timeoutSettings);
        this.#frameOrWorker = frameOrWorker;
      }
      get environment() {
        return this.#frameOrWorker;
      }
      get client() {
        return this.#frameOrWorker.client;
      }
      get emitter() {
        return this.#emitter;
      }
      setContext(context) {
        this.#context?.[disposable_js_1.disposeSymbol]();
        context.once("disposed", this.#onContextDisposed.bind(this));
        context.on("consoleapicalled", this.#onContextConsoleApiCalled.bind(this));
        context.on("bindingcalled", this.#onContextBindingCalled.bind(this));
        this.#context = context;
        this.#emitter.emit("context", context);
        void this.taskManager.rerunAll();
      }
      #onContextDisposed() {
        this.#context = void 0;
        if ("clearDocumentHandle" in this.#frameOrWorker) {
          this.#frameOrWorker.clearDocumentHandle();
        }
      }
      #onContextConsoleApiCalled(event) {
        this.#emitter.emit("consoleapicalled", event);
      }
      #onContextBindingCalled(event) {
        this.#emitter.emit("bindingcalled", event);
      }
      hasContext() {
        return !!this.#context;
      }
      get context() {
        return this.#context;
      }
      #executionContext() {
        if (this.disposed) {
          throw new Error(`Execution context is not available in detached frame or worker "${this.environment.url()}" (are you trying to evaluate?)`);
        }
        return this.#context;
      }
      /**
       * Waits for the next context to be set on the isolated world.
       */
      async #waitForExecutionContext() {
        const error = new Error("Execution context was destroyed");
        const result = await (0, rxjs_js_1.firstValueFrom)((0, util_js_1.fromEmitterEvent)(this.#emitter, "context").pipe((0, rxjs_js_1.raceWith)((0, util_js_1.fromEmitterEvent)(this.#emitter, "disposed").pipe((0, rxjs_js_1.map)(() => {
          throw error;
        })), (0, util_js_1.timeout)(this.timeoutSettings.timeout()))));
        return result;
      }
      async evaluateHandle(pageFunction, ...args2) {
        pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.evaluateHandle.name, pageFunction);
        let context = this.#executionContext();
        if (!context) {
          context = await this.#waitForExecutionContext();
        }
        return await context.evaluateHandle(pageFunction, ...args2);
      }
      async evaluate(pageFunction, ...args2) {
        pageFunction = (0, util_js_1.withSourcePuppeteerURLIfNone)(this.evaluate.name, pageFunction);
        let context = this.#executionContext();
        if (!context) {
          context = await this.#waitForExecutionContext();
        }
        return await context.evaluate(pageFunction, ...args2);
      }
      async adoptBackendNode(backendNodeId) {
        let context = this.#executionContext();
        if (!context) {
          context = await this.#waitForExecutionContext();
        }
        const { object } = await this.client.send("DOM.resolveNode", {
          backendNodeId,
          executionContextId: context.id
        });
        return this.createCdpHandle(object);
      }
      async adoptHandle(handle) {
        if (handle.realm === this) {
          return await handle.evaluateHandle((value) => {
            return value;
          });
        }
        const nodeInfo = await this.client.send("DOM.describeNode", {
          objectId: handle.id
        });
        return await this.adoptBackendNode(nodeInfo.node.backendNodeId);
      }
      async transferHandle(handle) {
        if (handle.realm === this) {
          return handle;
        }
        if (handle.remoteObject().objectId === void 0) {
          return handle;
        }
        const info = await this.client.send("DOM.describeNode", {
          objectId: handle.remoteObject().objectId
        });
        const newHandle = await this.adoptBackendNode(info.node.backendNodeId);
        await handle.dispose();
        return newHandle;
      }
      /**
       * @internal
       */
      createCdpHandle(remoteObject) {
        if (remoteObject.subtype === "node") {
          return new ElementHandle_js_1.CdpElementHandle(this, remoteObject);
        }
        return new JSHandle_js_1.CdpJSHandle(this, remoteObject);
      }
      [disposable_js_1.disposeSymbol]() {
        this.#context?.[disposable_js_1.disposeSymbol]();
        this.#emitter.emit("disposed", void 0);
        super[disposable_js_1.disposeSymbol]();
        this.#emitter.removeAllListeners();
      }
    };
    exports2.IsolatedWorld = IsolatedWorld;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/IsolatedWorlds.js
var require_IsolatedWorlds = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/IsolatedWorlds.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PUPPETEER_WORLD = exports2.MAIN_WORLD = void 0;
    exports2.MAIN_WORLD = /* @__PURE__ */ Symbol("mainWorld");
    exports2.PUPPETEER_WORLD = /* @__PURE__ */ Symbol("puppeteerWorld");
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/LifecycleWatcher.js
var require_LifecycleWatcher = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/LifecycleWatcher.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LifecycleWatcher = void 0;
    var Frame_js_1 = require_Frame();
    var EventEmitter_js_1 = require_EventEmitter();
    var NetworkManagerEvents_js_1 = require_NetworkManagerEvents();
    var assert_js_1 = require_assert();
    var Deferred_js_1 = require_Deferred();
    var disposable_js_1 = require_disposable();
    var FrameManagerEvents_js_1 = require_FrameManagerEvents();
    var puppeteerToProtocolLifecycle = /* @__PURE__ */ new Map([
      ["load", "load"],
      ["domcontentloaded", "DOMContentLoaded"],
      ["networkidle0", "networkIdle"],
      ["networkidle2", "networkAlmostIdle"]
    ]);
    var LifecycleWatcher = class {
      #expectedLifecycle;
      #frame;
      #timeout;
      #navigationRequest = null;
      #subscriptions = new disposable_js_1.DisposableStack();
      #initialLoaderId;
      #terminationDeferred;
      #sameDocumentNavigationDeferred = Deferred_js_1.Deferred.create();
      #lifecycleDeferred = Deferred_js_1.Deferred.create();
      #newDocumentNavigationDeferred = Deferred_js_1.Deferred.create();
      #error = new Error("LifecycleWatcher terminated");
      #hasSameDocumentNavigation;
      #swapped;
      #navigationResponseReceived;
      constructor(networkManager, frame, waitUntil, timeout, signal) {
        if (Array.isArray(waitUntil)) {
          waitUntil = waitUntil.slice();
        } else if (typeof waitUntil === "string") {
          waitUntil = [waitUntil];
        }
        this.#initialLoaderId = frame._loaderId;
        this.#expectedLifecycle = waitUntil.map((value) => {
          const protocolEvent = puppeteerToProtocolLifecycle.get(value);
          (0, assert_js_1.assert)(protocolEvent, "Unknown value for options.waitUntil: " + value);
          return protocolEvent;
        });
        signal?.addEventListener("abort", () => {
          if (signal.reason instanceof Error) {
            signal.reason.cause = this.#error;
          }
          this.#terminationDeferred.reject(signal.reason);
        });
        this.#frame = frame;
        this.#timeout = timeout;
        const frameManagerEmitter = this.#subscriptions.use(new EventEmitter_js_1.EventEmitter(frame._frameManager));
        frameManagerEmitter.on(FrameManagerEvents_js_1.FrameManagerEvent.LifecycleEvent, this.#checkLifecycleComplete.bind(this));
        const frameEmitter = this.#subscriptions.use(new EventEmitter_js_1.EventEmitter(frame));
        frameEmitter.on(Frame_js_1.FrameEvent.FrameNavigatedWithinDocument, this.#navigatedWithinDocument.bind(this));
        frameEmitter.on(Frame_js_1.FrameEvent.FrameNavigated, this.#navigated.bind(this));
        frameEmitter.on(Frame_js_1.FrameEvent.FrameSwapped, this.#frameSwapped.bind(this));
        frameEmitter.on(Frame_js_1.FrameEvent.FrameSwappedByActivation, this.#frameSwapped.bind(this));
        frameEmitter.on(Frame_js_1.FrameEvent.FrameDetached, this.#onFrameDetached.bind(this));
        const networkManagerEmitter = this.#subscriptions.use(new EventEmitter_js_1.EventEmitter(networkManager));
        networkManagerEmitter.on(NetworkManagerEvents_js_1.NetworkManagerEvent.Request, this.#onRequest.bind(this));
        networkManagerEmitter.on(NetworkManagerEvents_js_1.NetworkManagerEvent.Response, this.#onResponse.bind(this));
        networkManagerEmitter.on(NetworkManagerEvents_js_1.NetworkManagerEvent.RequestFailed, this.#onRequestFailed.bind(this));
        this.#terminationDeferred = Deferred_js_1.Deferred.create({
          timeout: this.#timeout,
          message: `Navigation timeout of ${this.#timeout} ms exceeded`
        });
        this.#checkLifecycleComplete();
      }
      #onRequest(request) {
        if (request.frame() !== this.#frame || !request.isNavigationRequest()) {
          return;
        }
        this.#navigationRequest = request;
        this.#navigationResponseReceived?.resolve();
        this.#navigationResponseReceived = Deferred_js_1.Deferred.create();
        if (request.response() !== null) {
          this.#navigationResponseReceived?.resolve();
        }
      }
      #onRequestFailed(request) {
        if (this.#navigationRequest?.id !== request.id) {
          return;
        }
        this.#navigationResponseReceived?.resolve();
      }
      #onResponse(response) {
        if (this.#navigationRequest?.id !== response.request().id) {
          return;
        }
        this.#navigationResponseReceived?.resolve();
      }
      #onFrameDetached(frame) {
        if (this.#frame === frame) {
          this.#error.message = "Navigating frame was detached";
          this.#terminationDeferred.resolve(this.#error);
          return;
        }
        this.#checkLifecycleComplete();
      }
      async navigationResponse() {
        await this.#navigationResponseReceived?.valueOrThrow();
        return this.#navigationRequest ? this.#navigationRequest.response() : null;
      }
      sameDocumentNavigationPromise() {
        return this.#sameDocumentNavigationDeferred.valueOrThrow();
      }
      newDocumentNavigationPromise() {
        return this.#newDocumentNavigationDeferred.valueOrThrow();
      }
      lifecyclePromise() {
        return this.#lifecycleDeferred.valueOrThrow();
      }
      terminationPromise() {
        return this.#terminationDeferred.valueOrThrow();
      }
      #navigatedWithinDocument() {
        this.#hasSameDocumentNavigation = true;
        this.#checkLifecycleComplete();
      }
      #navigated(navigationType) {
        if (navigationType === "BackForwardCacheRestore") {
          return this.#frameSwapped();
        }
        this.#checkLifecycleComplete();
      }
      #frameSwapped() {
        this.#swapped = true;
        this.#checkLifecycleComplete();
      }
      #checkLifecycleComplete() {
        if (!checkLifecycle(this.#frame, this.#expectedLifecycle)) {
          return;
        }
        this.#lifecycleDeferred.resolve();
        if (this.#hasSameDocumentNavigation) {
          this.#sameDocumentNavigationDeferred.resolve(void 0);
        }
        if (this.#swapped || this.#frame._loaderId !== this.#initialLoaderId) {
          this.#newDocumentNavigationDeferred.resolve(void 0);
        }
        function checkLifecycle(frame, expectedLifecycle) {
          for (const event of expectedLifecycle) {
            if (!frame._lifecycleEvents.has(event)) {
              return false;
            }
          }
          for (const child of frame.childFrames()) {
            if (child._hasStartedLoading && !checkLifecycle(child, expectedLifecycle)) {
              return false;
            }
          }
          return true;
        }
      }
      dispose() {
        this.#subscriptions.dispose();
        this.#error.cause = new Error("LifecycleWatcher disposed");
        this.#terminationDeferred.resolve(this.#error);
      }
    };
    exports2.LifecycleWatcher = LifecycleWatcher;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Frame.js
var require_Frame2 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Frame.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CdpFrame = void 0;
    exports2.referrerPolicyToProtocol = referrerPolicyToProtocol;
    var Frame_js_1 = require_Frame();
    var Errors_js_1 = require_Errors();
    var util_js_1 = require_util();
    var Deferred_js_1 = require_Deferred();
    var disposable_js_1 = require_disposable();
    var ErrorLike_js_1 = require_ErrorLike();
    var Accessibility_js_1 = require_Accessibility();
    var FrameManagerEvents_js_1 = require_FrameManagerEvents();
    var IsolatedWorld_js_1 = require_IsolatedWorld();
    var IsolatedWorlds_js_1 = require_IsolatedWorlds();
    var LifecycleWatcher_js_1 = require_LifecycleWatcher();
    var utils_js_1 = require_utils();
    var CdpFrame = (() => {
      let _classSuper = Frame_js_1.Frame;
      let _instanceExtraInitializers = [];
      let _goto_decorators;
      let _waitForNavigation_decorators;
      let _setContent_decorators;
      let _addPreloadScript_decorators;
      let _addExposedFunctionBinding_decorators;
      let _removeExposedFunctionBinding_decorators;
      let _waitForDevicePrompt_decorators;
      return class CdpFrame extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          __esDecorate2(this, null, _goto_decorators, { kind: "method", name: "goto", static: false, private: false, access: { has: (obj) => "goto" in obj, get: (obj) => obj.goto }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _waitForNavigation_decorators, { kind: "method", name: "waitForNavigation", static: false, private: false, access: { has: (obj) => "waitForNavigation" in obj, get: (obj) => obj.waitForNavigation }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _setContent_decorators, { kind: "method", name: "setContent", static: false, private: false, access: { has: (obj) => "setContent" in obj, get: (obj) => obj.setContent }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _addPreloadScript_decorators, { kind: "method", name: "addPreloadScript", static: false, private: false, access: { has: (obj) => "addPreloadScript" in obj, get: (obj) => obj.addPreloadScript }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _addExposedFunctionBinding_decorators, { kind: "method", name: "addExposedFunctionBinding", static: false, private: false, access: { has: (obj) => "addExposedFunctionBinding" in obj, get: (obj) => obj.addExposedFunctionBinding }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _removeExposedFunctionBinding_decorators, { kind: "method", name: "removeExposedFunctionBinding", static: false, private: false, access: { has: (obj) => "removeExposedFunctionBinding" in obj, get: (obj) => obj.removeExposedFunctionBinding }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _waitForDevicePrompt_decorators, { kind: "method", name: "waitForDevicePrompt", static: false, private: false, access: { has: (obj) => "waitForDevicePrompt" in obj, get: (obj) => obj.waitForDevicePrompt }, metadata: _metadata }, null, _instanceExtraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #url = (__runInitializers2(this, _instanceExtraInitializers), "");
        #detached = false;
        #client;
        _frameManager;
        _loaderId = "";
        _lifecycleEvents = /* @__PURE__ */ new Set();
        _id;
        _parentId;
        accessibility;
        worlds;
        constructor(frameManager, frameId, parentFrameId, client2) {
          super();
          this._frameManager = frameManager;
          this.#url = "";
          this._id = frameId;
          this._parentId = parentFrameId;
          this.#detached = false;
          this.#client = client2;
          this._loaderId = "";
          this.worlds = {
            [IsolatedWorlds_js_1.MAIN_WORLD]: new IsolatedWorld_js_1.IsolatedWorld(this, this._frameManager.timeoutSettings),
            [IsolatedWorlds_js_1.PUPPETEER_WORLD]: new IsolatedWorld_js_1.IsolatedWorld(this, this._frameManager.timeoutSettings)
          };
          this.accessibility = new Accessibility_js_1.Accessibility(this.worlds[IsolatedWorlds_js_1.MAIN_WORLD], frameId);
          this.on(Frame_js_1.FrameEvent.FrameSwappedByActivation, () => {
            this._onLoadingStarted();
            this._onLoadingStopped();
          });
          this.worlds[IsolatedWorlds_js_1.MAIN_WORLD].emitter.on("consoleapicalled", this.#onMainWorldConsoleApiCalled.bind(this));
          this.worlds[IsolatedWorlds_js_1.MAIN_WORLD].emitter.on("bindingcalled", this.#onMainWorldBindingCalled.bind(this));
        }
        #onMainWorldConsoleApiCalled(event) {
          this._frameManager.emit(FrameManagerEvents_js_1.FrameManagerEvent.ConsoleApiCalled, [
            this.worlds[IsolatedWorlds_js_1.MAIN_WORLD],
            event
          ]);
        }
        #onMainWorldBindingCalled(event) {
          this._frameManager.emit(FrameManagerEvents_js_1.FrameManagerEvent.BindingCalled, [
            this.worlds[IsolatedWorlds_js_1.MAIN_WORLD],
            event
          ]);
        }
        /**
         * This is used internally in DevTools.
         *
         * @internal
         */
        _client() {
          return this.#client;
        }
        /**
         * Updates the frame ID with the new ID. This happens when the main frame is
         * replaced by a different frame.
         */
        updateId(id) {
          this._id = id;
        }
        updateClient(client2) {
          this.#client = client2;
        }
        page() {
          return this._frameManager.page();
        }
        async goto(url, options = {}) {
          const { referer = this._frameManager.networkManager.extraHTTPHeaders()["referer"], referrerPolicy = this._frameManager.networkManager.extraHTTPHeaders()["referer-policy"], waitUntil = ["load"], timeout = this._frameManager.timeoutSettings.navigationTimeout() } = options;
          let ensureNewDocumentNavigation = false;
          const watcher = new LifecycleWatcher_js_1.LifecycleWatcher(this._frameManager.networkManager, this, waitUntil, timeout);
          let error = await Deferred_js_1.Deferred.race([
            navigate(this.#client, url, referer, referrerPolicy ? referrerPolicyToProtocol(referrerPolicy) : void 0, this._id),
            watcher.terminationPromise()
          ]);
          if (!error) {
            error = await Deferred_js_1.Deferred.race([
              watcher.terminationPromise(),
              ensureNewDocumentNavigation ? watcher.newDocumentNavigationPromise() : watcher.sameDocumentNavigationPromise()
            ]);
          }
          try {
            if (error) {
              throw error;
            }
            return await watcher.navigationResponse();
          } finally {
            watcher.dispose();
          }
          async function navigate(client2, url2, referrer, referrerPolicy2, frameId) {
            try {
              const response = await client2.send("Page.navigate", {
                url: url2,
                referrer,
                frameId,
                referrerPolicy: referrerPolicy2
              });
              ensureNewDocumentNavigation = !!response.loaderId;
              if (response.errorText === "net::ERR_HTTP_RESPONSE_CODE_FAILURE") {
                return null;
              }
              return response.errorText ? new Error(`${response.errorText} at ${url2}`) : null;
            } catch (error2) {
              if ((0, ErrorLike_js_1.isErrorLike)(error2)) {
                return error2;
              }
              throw error2;
            }
          }
        }
        async waitForNavigation(options = {}) {
          const { waitUntil = ["load"], timeout = this._frameManager.timeoutSettings.navigationTimeout(), signal } = options;
          const watcher = new LifecycleWatcher_js_1.LifecycleWatcher(this._frameManager.networkManager, this, waitUntil, timeout, signal);
          const error = await Deferred_js_1.Deferred.race([
            watcher.terminationPromise(),
            ...options.ignoreSameDocumentNavigation ? [] : [watcher.sameDocumentNavigationPromise()],
            watcher.newDocumentNavigationPromise()
          ]);
          try {
            if (error) {
              throw error;
            }
            const result = await Deferred_js_1.Deferred.race([watcher.terminationPromise(), watcher.navigationResponse()]);
            if (result instanceof Error) {
              throw error;
            }
            return result || null;
          } finally {
            watcher.dispose();
          }
        }
        get client() {
          return this.#client;
        }
        mainRealm() {
          return this.worlds[IsolatedWorlds_js_1.MAIN_WORLD];
        }
        isolatedRealm() {
          return this.worlds[IsolatedWorlds_js_1.PUPPETEER_WORLD];
        }
        async setContent(html, options = {}) {
          const { waitUntil = ["load"], timeout = this._frameManager.timeoutSettings.navigationTimeout() } = options;
          await this.setFrameContent(html);
          const watcher = new LifecycleWatcher_js_1.LifecycleWatcher(this._frameManager.networkManager, this, waitUntil, timeout);
          const error = await Deferred_js_1.Deferred.race([
            watcher.terminationPromise(),
            watcher.lifecyclePromise()
          ]);
          watcher.dispose();
          if (error) {
            throw error;
          }
        }
        url() {
          return this.#url;
        }
        parentFrame() {
          return this._frameManager._frameTree.parentFrame(this._id) || null;
        }
        childFrames() {
          return this._frameManager._frameTree.childFrames(this._id);
        }
        #deviceRequestPromptManager() {
          return this._frameManager._deviceRequestPromptManager(this.#client);
        }
        async addPreloadScript(preloadScript) {
          const parentFrame = this.parentFrame();
          if (parentFrame && this.#client === parentFrame.client) {
            return;
          }
          if (preloadScript.getIdForFrame(this)) {
            return;
          }
          const { identifier } = await this.#client.send("Page.addScriptToEvaluateOnNewDocument", {
            source: preloadScript.source
          });
          preloadScript.setIdForFrame(this, identifier);
        }
        async addExposedFunctionBinding(binding) {
          if (this !== this._frameManager.mainFrame() && !this._hasStartedLoading) {
            return;
          }
          await Promise.all([
            this.#client.send("Runtime.addBinding", {
              name: utils_js_1.CDP_BINDING_PREFIX + binding.name
            }),
            this.evaluate(binding.initSource).catch(util_js_1.debugError)
          ]);
        }
        async removeExposedFunctionBinding(binding) {
          if (this !== this._frameManager.mainFrame() && !this._hasStartedLoading) {
            return;
          }
          await Promise.all([
            this.#client.send("Runtime.removeBinding", {
              name: utils_js_1.CDP_BINDING_PREFIX + binding.name
            }),
            this.evaluate((name) => {
              globalThis[name] = void 0;
            }, binding.name).catch(util_js_1.debugError)
          ]);
        }
        async waitForDevicePrompt(options = {}) {
          return await this.#deviceRequestPromptManager().waitForDevicePrompt(options);
        }
        _navigated(framePayload) {
          this._name = framePayload.name;
          this.#url = `${framePayload.url}${framePayload.urlFragment || ""}`;
        }
        _navigatedWithinDocument(url) {
          this.#url = url;
        }
        _onLifecycleEvent(loaderId, name) {
          if (name === "init") {
            this._loaderId = loaderId;
            this._lifecycleEvents.clear();
          }
          this._lifecycleEvents.add(name);
        }
        _onLoadingStopped() {
          this._lifecycleEvents.add("DOMContentLoaded");
          this._lifecycleEvents.add("load");
        }
        _onLoadingStarted() {
          this._hasStartedLoading = true;
        }
        get detached() {
          return this.#detached;
        }
        [(_goto_decorators = [Frame_js_1.throwIfDetached], _waitForNavigation_decorators = [Frame_js_1.throwIfDetached], _setContent_decorators = [Frame_js_1.throwIfDetached], _addPreloadScript_decorators = [Frame_js_1.throwIfDetached], _addExposedFunctionBinding_decorators = [Frame_js_1.throwIfDetached], _removeExposedFunctionBinding_decorators = [Frame_js_1.throwIfDetached], _waitForDevicePrompt_decorators = [Frame_js_1.throwIfDetached], disposable_js_1.disposeSymbol)]() {
          if (this.#detached) {
            return;
          }
          this.#detached = true;
          this.worlds[IsolatedWorlds_js_1.MAIN_WORLD][disposable_js_1.disposeSymbol]();
          this.worlds[IsolatedWorlds_js_1.PUPPETEER_WORLD][disposable_js_1.disposeSymbol]();
        }
        exposeFunction() {
          throw new Errors_js_1.UnsupportedOperation();
        }
        async frameElement() {
          const parent = this.parentFrame();
          if (!parent) {
            return null;
          }
          const { backendNodeId } = await parent.client.send("DOM.getFrameOwner", {
            frameId: this._id
          });
          return await parent.mainRealm().adoptBackendNode(backendNodeId);
        }
      };
    })();
    exports2.CdpFrame = CdpFrame;
    function referrerPolicyToProtocol(referrerPolicy) {
      return referrerPolicy.replaceAll(/-./g, (match) => {
        return match[1].toUpperCase();
      });
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/FrameTree.js
var require_FrameTree = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/FrameTree.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.FrameTree = void 0;
    var Deferred_js_1 = require_Deferred();
    var FrameTree = class {
      #frames = /* @__PURE__ */ new Map();
      // frameID -> parentFrameID
      #parentIds = /* @__PURE__ */ new Map();
      // frameID -> childFrameIDs
      #childIds = /* @__PURE__ */ new Map();
      #mainFrame;
      #isMainFrameStale = false;
      #waitRequests = /* @__PURE__ */ new Map();
      getMainFrame() {
        return this.#mainFrame;
      }
      getById(frameId) {
        return this.#frames.get(frameId);
      }
      /**
       * Returns a promise that is resolved once the frame with
       * the given ID is added to the tree.
       */
      waitForFrame(frameId) {
        const frame = this.getById(frameId);
        if (frame) {
          return Promise.resolve(frame);
        }
        const deferred = Deferred_js_1.Deferred.create();
        const callbacks = this.#waitRequests.get(frameId) || /* @__PURE__ */ new Set();
        callbacks.add(deferred);
        return deferred.valueOrThrow();
      }
      frames() {
        return Array.from(this.#frames.values());
      }
      addFrame(frame) {
        this.#frames.set(frame._id, frame);
        if (frame._parentId) {
          this.#parentIds.set(frame._id, frame._parentId);
          if (!this.#childIds.has(frame._parentId)) {
            this.#childIds.set(frame._parentId, /* @__PURE__ */ new Set());
          }
          this.#childIds.get(frame._parentId).add(frame._id);
        } else if (!this.#mainFrame || this.#isMainFrameStale) {
          this.#mainFrame = frame;
          this.#isMainFrameStale = false;
        }
        this.#waitRequests.get(frame._id)?.forEach((request) => {
          return request.resolve(frame);
        });
      }
      removeFrame(frame) {
        this.#frames.delete(frame._id);
        this.#parentIds.delete(frame._id);
        if (frame._parentId) {
          this.#childIds.get(frame._parentId)?.delete(frame._id);
        } else {
          this.#isMainFrameStale = true;
        }
      }
      childFrames(frameId) {
        const childIds = this.#childIds.get(frameId);
        if (!childIds) {
          return [];
        }
        return Array.from(childIds).map((id) => {
          return this.getById(id);
        }).filter((frame) => {
          return frame !== void 0;
        });
      }
      parentFrame(frameId) {
        const parentId = this.#parentIds.get(frameId);
        return parentId ? this.getById(parentId) : void 0;
      }
    };
    exports2.FrameTree = FrameTree;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/HTTPRequest.js
var require_HTTPRequest2 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/HTTPRequest.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CdpHTTPRequest = void 0;
    var HTTPRequest_js_1 = require_HTTPRequest();
    var util_js_1 = require_util();
    var encoding_js_1 = require_encoding();
    var CdpHTTPRequest = class extends HTTPRequest_js_1.HTTPRequest {
      id;
      #client;
      #isNavigationRequest;
      #url;
      #resourceType;
      #method;
      #hasPostData = false;
      #postData;
      #headers = {};
      #frame;
      #initiator;
      get client() {
        return this.#client;
      }
      set client(newClient) {
        this.#client = newClient;
      }
      constructor(client2, frame, interceptionId, allowInterception, data, redirectChain) {
        super();
        this.#client = client2;
        this.id = data.requestId;
        this.#isNavigationRequest = data.requestId === data.loaderId && data.type === "Document";
        this._interceptionId = interceptionId;
        this.#url = data.request.url + (data.request.urlFragment ?? "");
        this.#resourceType = (data.type || "other").toLowerCase();
        this.#method = data.request.method;
        if (data.request.postDataEntries && data.request.postDataEntries.length > 0) {
          this.#postData = new TextDecoder().decode((0, encoding_js_1.mergeUint8Arrays)(data.request.postDataEntries.map((entry) => {
            return entry.bytes ? (0, encoding_js_1.stringToTypedArray)(entry.bytes, true) : null;
          }).filter((entry) => {
            return entry !== null;
          })));
        } else {
          this.#postData = data.request.postData;
        }
        this.#hasPostData = data.request.hasPostData ?? false;
        this.#frame = frame;
        this._redirectChain = redirectChain;
        this.#initiator = data.initiator;
        this.interception.enabled = allowInterception;
        this.updateHeaders(data.request.headers);
      }
      updateHeaders(headers) {
        for (const [key, value] of Object.entries(headers)) {
          this.#headers[key.toLowerCase()] = value;
        }
      }
      url() {
        return this.#url;
      }
      resourceType() {
        return this.#resourceType;
      }
      method() {
        return this.#method;
      }
      postData() {
        return this.#postData;
      }
      hasPostData() {
        return this.#hasPostData;
      }
      async fetchPostData() {
        try {
          const result = await this.#client.send("Network.getRequestPostData", {
            requestId: this.id
          });
          return result.postData;
        } catch (err) {
          (0, util_js_1.debugError)(err);
          return;
        }
      }
      headers() {
        return structuredClone(this.#headers);
      }
      response() {
        return this._response;
      }
      frame() {
        return this.#frame;
      }
      isNavigationRequest() {
        return this.#isNavigationRequest;
      }
      initiator() {
        return this.#initiator;
      }
      redirectChain() {
        return this._redirectChain.slice();
      }
      failure() {
        if (!this._failureText) {
          return null;
        }
        return {
          errorText: this._failureText
        };
      }
      canBeIntercepted() {
        return !this.url().startsWith("data:") && !this._fromMemoryCache;
      }
      /**
       * @internal
       */
      async _continue(overrides = {}) {
        const { url, method, postData, headers } = overrides;
        this.interception.handled = true;
        const postDataBinaryBase64 = postData ? (0, encoding_js_1.stringToBase64)(postData) : void 0;
        if (this._interceptionId === void 0) {
          throw new Error("HTTPRequest is missing _interceptionId needed for Fetch.continueRequest");
        }
        await this.#client.send("Fetch.continueRequest", {
          requestId: this._interceptionId,
          url,
          method,
          postData: postDataBinaryBase64,
          headers: headers ? (0, HTTPRequest_js_1.headersArray)(headers) : void 0
        }).catch((error) => {
          this.interception.handled = false;
          return (0, HTTPRequest_js_1.handleError)(error);
        });
      }
      async _respond(response) {
        this.interception.handled = true;
        let parsedBody;
        if (response.body) {
          parsedBody = HTTPRequest_js_1.HTTPRequest.getResponse(response.body);
        }
        const responseHeaders = {};
        if (response.headers) {
          for (const header of Object.keys(response.headers)) {
            const value = response.headers[header];
            responseHeaders[header.toLowerCase()] = Array.isArray(value) ? value.map((item) => {
              return String(item);
            }) : String(value);
          }
        }
        if (response.contentType) {
          responseHeaders["content-type"] = response.contentType;
        }
        if (parsedBody?.contentLength && !("content-length" in responseHeaders)) {
          responseHeaders["content-length"] = String(parsedBody.contentLength);
        }
        const status = response.status || 200;
        if (this._interceptionId === void 0) {
          throw new Error("HTTPRequest is missing _interceptionId needed for Fetch.fulfillRequest");
        }
        await this.#client.send("Fetch.fulfillRequest", {
          requestId: this._interceptionId,
          responseCode: status,
          responsePhrase: HTTPRequest_js_1.STATUS_TEXTS[status],
          responseHeaders: (0, HTTPRequest_js_1.headersArray)(responseHeaders),
          body: parsedBody?.base64
        }).catch((error) => {
          this.interception.handled = false;
          return (0, HTTPRequest_js_1.handleError)(error);
        });
      }
      async _abort(errorReason) {
        this.interception.handled = true;
        if (this._interceptionId === void 0) {
          throw new Error("HTTPRequest is missing _interceptionId needed for Fetch.failRequest");
        }
        await this.#client.send("Fetch.failRequest", {
          requestId: this._interceptionId,
          errorReason: errorReason || "Failed"
        }).catch(HTTPRequest_js_1.handleError);
      }
    };
    exports2.CdpHTTPRequest = CdpHTTPRequest;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/SecurityDetails.js
var require_SecurityDetails = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/SecurityDetails.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SecurityDetails = void 0;
    var SecurityDetails = class {
      #subjectName;
      #issuer;
      #validFrom;
      #validTo;
      #protocol;
      #sanList;
      /**
       * @internal
       */
      constructor(securityPayload) {
        this.#subjectName = securityPayload.subjectName;
        this.#issuer = securityPayload.issuer;
        this.#validFrom = securityPayload.validFrom;
        this.#validTo = securityPayload.validTo;
        this.#protocol = securityPayload.protocol;
        this.#sanList = securityPayload.sanList;
      }
      /**
       * The name of the issuer of the certificate.
       */
      issuer() {
        return this.#issuer;
      }
      /**
       * {@link https://en.wikipedia.org/wiki/Unix_time | Unix timestamp}
       * marking the start of the certificate's validity.
       */
      validFrom() {
        return this.#validFrom;
      }
      /**
       * {@link https://en.wikipedia.org/wiki/Unix_time | Unix timestamp}
       * marking the end of the certificate's validity.
       */
      validTo() {
        return this.#validTo;
      }
      /**
       * The security protocol being used, e.g. "TLS 1.2".
       */
      protocol() {
        return this.#protocol;
      }
      /**
       * The name of the subject to which the certificate was issued.
       */
      subjectName() {
        return this.#subjectName;
      }
      /**
       * The list of {@link https://en.wikipedia.org/wiki/Subject_Alternative_Name | subject alternative names (SANs)} of the certificate.
       */
      subjectAlternativeNames() {
        return this.#sanList;
      }
    };
    exports2.SecurityDetails = SecurityDetails;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/HTTPResponse.js
var require_HTTPResponse2 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/HTTPResponse.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CdpHTTPResponse = void 0;
    var HTTPResponse_js_1 = require_HTTPResponse();
    var Errors_js_1 = require_Errors();
    var SecurityDetails_js_1 = require_SecurityDetails();
    var Deferred_js_1 = require_Deferred();
    var encoding_js_1 = require_encoding();
    var CdpHTTPResponse = class extends HTTPResponse_js_1.HTTPResponse {
      #request;
      #contentPromise = null;
      #bodyLoadedDeferred = Deferred_js_1.Deferred.create();
      #remoteAddress;
      #status;
      #statusText;
      #fromDiskCache;
      #fromServiceWorker;
      #headers = {};
      #securityDetails;
      #timing;
      constructor(request, responsePayload, extraInfo) {
        super();
        this.#request = request;
        this.#remoteAddress = {
          ip: responsePayload.remoteIPAddress,
          port: responsePayload.remotePort
        };
        this.#statusText = this.#parseStatusTextFromExtraInfo(extraInfo) || responsePayload.statusText;
        this.#fromDiskCache = !!responsePayload.fromDiskCache;
        this.#fromServiceWorker = !!responsePayload.fromServiceWorker;
        this.#status = extraInfo ? extraInfo.statusCode : responsePayload.status;
        const headers = extraInfo ? extraInfo.headers : responsePayload.headers;
        for (const [key, value] of Object.entries(headers)) {
          this.#headers[key.toLowerCase()] = value;
        }
        this.#securityDetails = responsePayload.securityDetails ? new SecurityDetails_js_1.SecurityDetails(responsePayload.securityDetails) : null;
        this.#timing = responsePayload.timing || null;
      }
      #parseStatusTextFromExtraInfo(extraInfo) {
        if (!extraInfo || !extraInfo.headersText) {
          return;
        }
        const firstLine = extraInfo.headersText.split("\r", 1)[0];
        if (!firstLine || firstLine.length > 1e3) {
          return;
        }
        const match = firstLine.match(/[^ ]* [^ ]* (.*)/);
        if (!match) {
          return;
        }
        const statusText = match[1];
        if (!statusText) {
          return;
        }
        return statusText;
      }
      _resolveBody(err) {
        if (err) {
          return this.#bodyLoadedDeferred.reject(err);
        }
        return this.#bodyLoadedDeferred.resolve();
      }
      remoteAddress() {
        return this.#remoteAddress;
      }
      url() {
        return this.#request.url();
      }
      status() {
        return this.#status;
      }
      statusText() {
        return this.#statusText;
      }
      headers() {
        return this.#headers;
      }
      securityDetails() {
        return this.#securityDetails;
      }
      timing() {
        return this.#timing;
      }
      content() {
        if (!this.#contentPromise) {
          this.#contentPromise = this.#bodyLoadedDeferred.valueOrThrow().then(async () => {
            try {
              const response = await this.#request.client.send("Network.getResponseBody", {
                requestId: this.#request.id
              });
              return (0, encoding_js_1.stringToTypedArray)(response.body, response.base64Encoded);
            } catch (error) {
              if (error instanceof Errors_js_1.ProtocolError && error.originalMessage === "No resource with given identifier found") {
                throw new Errors_js_1.ProtocolError("Could not load response body for this request. This might happen if the request is a preflight request.");
              }
              throw error;
            }
          });
        }
        return this.#contentPromise;
      }
      request() {
        return this.#request;
      }
      fromCache() {
        return this.#fromDiskCache || this.#request._fromMemoryCache;
      }
      fromServiceWorker() {
        return this.#fromServiceWorker;
      }
      frame() {
        return this.#request.frame();
      }
    };
    exports2.CdpHTTPResponse = CdpHTTPResponse;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/NetworkEventManager.js
var require_NetworkEventManager = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/NetworkEventManager.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NetworkEventManager = void 0;
    var HTTPRequest_js_1 = require_HTTPRequest2();
    var NetworkEventManager = class {
      /**
       * There are four possible orders of events:
       * A. `_onRequestWillBeSent`
       * B. `_onRequestWillBeSent`, `_onRequestPaused`
       * C. `_onRequestPaused`, `_onRequestWillBeSent`
       * D. `_onRequestPaused`, `_onRequestWillBeSent`, `_onRequestPaused`,
       * `_onRequestWillBeSent`, `_onRequestPaused`, `_onRequestPaused`
       * (see crbug.com/1196004)
       *
       * For `_onRequest` we need the event from `_onRequestWillBeSent` and
       * optionally the `interceptionId` from `_onRequestPaused`.
       *
       * If request interception is disabled, call `_onRequest` once per call to
       * `_onRequestWillBeSent`.
       * If request interception is enabled, call `_onRequest` once per call to
       * `_onRequestPaused` (once per `interceptionId`).
       *
       * Events are stored to allow for subsequent events to call `_onRequest`.
       *
       * Note that (chains of) redirect requests have the same `requestId` (!) as
       * the original request. We have to anticipate series of events like these:
       * A. `_onRequestWillBeSent`,
       * `_onRequestWillBeSent`, ...
       * B. `_onRequestWillBeSent`, `_onRequestPaused`,
       * `_onRequestWillBeSent`, `_onRequestPaused`, ...
       * C. `_onRequestWillBeSent`, `_onRequestPaused`,
       * `_onRequestPaused`, `_onRequestWillBeSent`, ...
       * D. `_onRequestPaused`, `_onRequestWillBeSent`,
       * `_onRequestPaused`, `_onRequestWillBeSent`, `_onRequestPaused`,
       * `_onRequestWillBeSent`, `_onRequestPaused`, `_onRequestPaused`, ...
       * (see crbug.com/1196004)
       */
      #requestWillBeSentMap = /* @__PURE__ */ new Map();
      #requestPausedMap = /* @__PURE__ */ new Map();
      #httpRequestsMap = /* @__PURE__ */ new Map();
      #requestWillBeSentExtraInfoMap = /* @__PURE__ */ new Map();
      /*
       * The below maps are used to reconcile Network.responseReceivedExtraInfo
       * events with their corresponding request. Each response and redirect
       * response gets an ExtraInfo event, and we don't know which will come first.
       * This means that we have to store a Response or an ExtraInfo for each
       * response, and emit the event when we get both of them. In addition, to
       * handle redirects, we have to make them Arrays to represent the chain of
       * events.
       */
      #responseReceivedExtraInfoMap = /* @__PURE__ */ new Map();
      #queuedRedirectInfoMap = /* @__PURE__ */ new Map();
      #queuedEventGroupMap = /* @__PURE__ */ new Map();
      forget(networkRequestId) {
        this.#requestWillBeSentMap.delete(networkRequestId);
        this.#requestPausedMap.delete(networkRequestId);
        this.#requestWillBeSentExtraInfoMap.delete(networkRequestId);
        this.#queuedEventGroupMap.delete(networkRequestId);
        this.#queuedRedirectInfoMap.delete(networkRequestId);
        this.#responseReceivedExtraInfoMap.delete(networkRequestId);
      }
      requestExtraInfo(networkRequestId) {
        if (!this.#requestWillBeSentExtraInfoMap.has(networkRequestId)) {
          this.#requestWillBeSentExtraInfoMap.set(networkRequestId, []);
        }
        return this.#requestWillBeSentExtraInfoMap.get(networkRequestId);
      }
      responseExtraInfo(networkRequestId) {
        if (!this.#responseReceivedExtraInfoMap.has(networkRequestId)) {
          this.#responseReceivedExtraInfoMap.set(networkRequestId, []);
        }
        return this.#responseReceivedExtraInfoMap.get(networkRequestId);
      }
      queuedRedirectInfo(fetchRequestId) {
        if (!this.#queuedRedirectInfoMap.has(fetchRequestId)) {
          this.#queuedRedirectInfoMap.set(fetchRequestId, []);
        }
        return this.#queuedRedirectInfoMap.get(fetchRequestId);
      }
      queueRedirectInfo(fetchRequestId, redirectInfo) {
        this.queuedRedirectInfo(fetchRequestId).push(redirectInfo);
      }
      takeQueuedRedirectInfo(fetchRequestId) {
        return this.queuedRedirectInfo(fetchRequestId).shift();
      }
      inFlightRequestsCount() {
        let inFlightRequestCounter = 0;
        for (const request of this.#httpRequestsMap.values()) {
          if (!request.response()) {
            inFlightRequestCounter++;
          }
        }
        return inFlightRequestCounter;
      }
      storeRequestWillBeSent(networkRequestId, event) {
        this.#requestWillBeSentMap.set(networkRequestId, event);
      }
      getRequestWillBeSent(networkRequestId) {
        return this.#requestWillBeSentMap.get(networkRequestId);
      }
      forgetRequestWillBeSent(networkRequestId) {
        this.#requestWillBeSentMap.delete(networkRequestId);
      }
      getRequestPaused(networkRequestId) {
        return this.#requestPausedMap.get(networkRequestId);
      }
      forgetRequestPaused(networkRequestId) {
        this.#requestPausedMap.delete(networkRequestId);
      }
      storeRequestPaused(networkRequestId, event) {
        this.#requestPausedMap.set(networkRequestId, event);
      }
      getRequest(networkRequestId) {
        return this.#httpRequestsMap.get(networkRequestId);
      }
      storeRequest(networkRequestId, request) {
        this.#httpRequestsMap.set(networkRequestId, request);
      }
      forgetRequest(networkRequestId) {
        this.#httpRequestsMap.delete(networkRequestId);
      }
      getQueuedEventGroup(networkRequestId) {
        return this.#queuedEventGroupMap.get(networkRequestId);
      }
      queueEventGroup(networkRequestId, event) {
        this.#queuedEventGroupMap.set(networkRequestId, event);
      }
      forgetQueuedEventGroup(networkRequestId) {
        this.#queuedEventGroupMap.delete(networkRequestId);
      }
      printState() {
        function replacer(_key, value) {
          if (value instanceof Map) {
            return {
              dataType: "Map",
              value: Array.from(value.entries())
              // or with spread: value: [...value]
            };
          } else if (value instanceof HTTPRequest_js_1.CdpHTTPRequest) {
            return {
              dataType: "CdpHTTPRequest",
              value: `${value.id}: ${value.url()}`
            };
          }
          {
            return value;
          }
        }
        console.log("httpRequestsMap", JSON.stringify(this.#httpRequestsMap, replacer, 2));
        console.log("requestWillBeSentMap", JSON.stringify(this.#requestWillBeSentMap, replacer, 2));
        console.log("requestWillBeSentMap", JSON.stringify(this.#responseReceivedExtraInfoMap, replacer, 2));
        console.log("requestWillBeSentMap", JSON.stringify(this.#requestPausedMap, replacer, 2));
      }
    };
    exports2.NetworkEventManager = NetworkEventManager;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/NetworkManager.js
var require_NetworkManager = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/NetworkManager.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NetworkManager = void 0;
    var CDPSession_js_1 = require_CDPSession();
    var EventEmitter_js_1 = require_EventEmitter();
    var NetworkManagerEvents_js_1 = require_NetworkManagerEvents();
    var util_js_1 = require_util();
    var assert_js_1 = require_assert();
    var disposable_js_1 = require_disposable();
    var ErrorLike_js_1 = require_ErrorLike();
    var Connection_js_1 = require_Connection();
    var HTTPRequest_js_1 = require_HTTPRequest2();
    var HTTPResponse_js_1 = require_HTTPResponse2();
    var NetworkEventManager_js_1 = require_NetworkEventManager();
    var NetworkManager = class extends EventEmitter_js_1.EventEmitter {
      #frameManager;
      #networkEventManager = new NetworkEventManager_js_1.NetworkEventManager();
      #extraHTTPHeaders;
      #credentials = null;
      #attemptedAuthentications = /* @__PURE__ */ new Set();
      #userRequestInterceptionEnabled = false;
      #protocolRequestInterceptionEnabled;
      #userCacheDisabled;
      #emulatedNetworkConditions;
      #userAgent;
      #userAgentMetadata;
      #platform;
      #handlers = [
        ["Fetch.requestPaused", this.#onRequestPaused],
        ["Fetch.authRequired", this.#onAuthRequired],
        ["Network.requestWillBeSent", this.#onRequestWillBeSent],
        ["Network.requestWillBeSentExtraInfo", this.#onRequestWillBeSentExtraInfo],
        ["Network.requestServedFromCache", this.#onRequestServedFromCache],
        ["Network.responseReceived", this.#onResponseReceived],
        ["Network.loadingFinished", this.#onLoadingFinished],
        ["Network.loadingFailed", this.#onLoadingFailed],
        ["Network.responseReceivedExtraInfo", this.#onResponseReceivedExtraInfo],
        [CDPSession_js_1.CDPSessionEvent.Disconnected, this.#removeClient]
      ];
      #clients = /* @__PURE__ */ new Map();
      #networkEnabled = true;
      constructor(frameManager, networkEnabled) {
        super();
        this.#frameManager = frameManager;
        this.#networkEnabled = networkEnabled ?? true;
      }
      #canIgnoreError(error) {
        return (0, ErrorLike_js_1.isErrorLike)(error) && ((0, Connection_js_1.isTargetClosedError)(error) || error.message.includes("Not supported") || error.message.includes("wasn't found"));
      }
      async addClient(client2) {
        if (!this.#networkEnabled || this.#clients.has(client2)) {
          return;
        }
        const subscriptions = new disposable_js_1.DisposableStack();
        this.#clients.set(client2, subscriptions);
        const clientEmitter = subscriptions.use(new EventEmitter_js_1.EventEmitter(client2));
        for (const [event, handler] of this.#handlers) {
          clientEmitter.on(event, (arg) => {
            return handler.bind(this)(client2, arg);
          });
        }
        try {
          await Promise.all([
            client2.send("Network.enable"),
            this.#applyExtraHTTPHeaders(client2),
            this.#applyNetworkConditions(client2),
            this.#applyProtocolCacheDisabled(client2),
            this.#applyProtocolRequestInterception(client2),
            this.#applyUserAgent(client2)
          ]);
        } catch (error) {
          if (this.#canIgnoreError(error)) {
            return;
          }
          throw error;
        }
      }
      async #removeClient(client2) {
        this.#clients.get(client2)?.dispose();
        this.#clients.delete(client2);
      }
      async authenticate(credentials) {
        this.#credentials = credentials;
        const enabled = this.#userRequestInterceptionEnabled || !!this.#credentials;
        if (enabled === this.#protocolRequestInterceptionEnabled) {
          return;
        }
        this.#protocolRequestInterceptionEnabled = enabled;
        await this.#applyToAllClients(this.#applyProtocolRequestInterception.bind(this));
      }
      async setExtraHTTPHeaders(headers) {
        const extraHTTPHeaders = {};
        for (const [key, value] of Object.entries(headers)) {
          (0, assert_js_1.assert)((0, util_js_1.isString)(value), `Expected value of header "${key}" to be String, but "${typeof value}" is found.`);
          extraHTTPHeaders[key.toLowerCase()] = value;
        }
        this.#extraHTTPHeaders = extraHTTPHeaders;
        await this.#applyToAllClients(this.#applyExtraHTTPHeaders.bind(this));
      }
      async #applyExtraHTTPHeaders(client2) {
        if (this.#extraHTTPHeaders === void 0) {
          return;
        }
        try {
          await client2.send("Network.setExtraHTTPHeaders", {
            headers: this.#extraHTTPHeaders
          });
        } catch (error) {
          if (this.#canIgnoreError(error)) {
            return;
          }
          throw error;
        }
      }
      extraHTTPHeaders() {
        return Object.assign({}, this.#extraHTTPHeaders);
      }
      inFlightRequestsCount() {
        return this.#networkEventManager.inFlightRequestsCount();
      }
      async setOfflineMode(value) {
        if (!this.#emulatedNetworkConditions) {
          this.#emulatedNetworkConditions = {
            offline: false,
            upload: -1,
            download: -1,
            latency: 0
          };
        }
        this.#emulatedNetworkConditions.offline = value;
        await this.#applyToAllClients(this.#applyNetworkConditions.bind(this));
      }
      async emulateNetworkConditions(networkConditions) {
        if (!this.#emulatedNetworkConditions) {
          this.#emulatedNetworkConditions = {
            offline: networkConditions?.offline ?? false,
            upload: -1,
            download: -1,
            latency: 0
          };
        }
        this.#emulatedNetworkConditions.upload = networkConditions ? networkConditions.upload : -1;
        this.#emulatedNetworkConditions.download = networkConditions ? networkConditions.download : -1;
        this.#emulatedNetworkConditions.latency = networkConditions ? networkConditions.latency : 0;
        this.#emulatedNetworkConditions.offline = networkConditions?.offline ?? false;
        await this.#applyToAllClients(this.#applyNetworkConditions.bind(this));
      }
      async #applyToAllClients(fn) {
        await Promise.all(Array.from(this.#clients.keys()).map((client2) => {
          return fn(client2);
        }));
      }
      async #applyNetworkConditions(client2) {
        if (this.#emulatedNetworkConditions === void 0) {
          return;
        }
        try {
          await client2.send("Network.emulateNetworkConditions", {
            offline: this.#emulatedNetworkConditions.offline,
            latency: this.#emulatedNetworkConditions.latency,
            uploadThroughput: this.#emulatedNetworkConditions.upload,
            downloadThroughput: this.#emulatedNetworkConditions.download
          });
        } catch (error) {
          if (this.#canIgnoreError(error)) {
            return;
          }
          throw error;
        }
      }
      async setUserAgent(userAgent, userAgentMetadata, platform) {
        this.#userAgent = userAgent;
        this.#userAgentMetadata = userAgentMetadata;
        this.#platform = platform;
        await this.#applyToAllClients(this.#applyUserAgent.bind(this));
      }
      async #applyUserAgent(client2) {
        if (this.#userAgent === void 0) {
          return;
        }
        try {
          await client2.send("Network.setUserAgentOverride", {
            userAgent: this.#userAgent,
            userAgentMetadata: this.#userAgentMetadata,
            platform: this.#platform
          });
        } catch (error) {
          if (this.#canIgnoreError(error)) {
            return;
          }
          throw error;
        }
      }
      async setCacheEnabled(enabled) {
        this.#userCacheDisabled = !enabled;
        await this.#applyToAllClients(this.#applyProtocolCacheDisabled.bind(this));
      }
      async setRequestInterception(value) {
        this.#userRequestInterceptionEnabled = value;
        const enabled = this.#userRequestInterceptionEnabled || !!this.#credentials;
        if (enabled === this.#protocolRequestInterceptionEnabled) {
          return;
        }
        this.#protocolRequestInterceptionEnabled = enabled;
        await this.#applyToAllClients(this.#applyProtocolRequestInterception.bind(this));
      }
      async #applyProtocolRequestInterception(client2) {
        if (this.#protocolRequestInterceptionEnabled === void 0) {
          return;
        }
        if (this.#userCacheDisabled === void 0) {
          this.#userCacheDisabled = false;
        }
        try {
          if (this.#protocolRequestInterceptionEnabled) {
            await Promise.all([
              this.#applyProtocolCacheDisabled(client2),
              client2.send("Fetch.enable", {
                handleAuthRequests: true,
                patterns: [{ urlPattern: "*" }]
              })
            ]);
          } else {
            await Promise.all([
              this.#applyProtocolCacheDisabled(client2),
              client2.send("Fetch.disable")
            ]);
          }
        } catch (error) {
          if (this.#canIgnoreError(error)) {
            return;
          }
          throw error;
        }
      }
      async #applyProtocolCacheDisabled(client2) {
        if (this.#userCacheDisabled === void 0) {
          return;
        }
        try {
          await client2.send("Network.setCacheDisabled", {
            cacheDisabled: this.#userCacheDisabled
          });
        } catch (error) {
          if (this.#canIgnoreError(error)) {
            return;
          }
          throw error;
        }
      }
      #onRequestWillBeSent(client2, event) {
        if (this.#userRequestInterceptionEnabled && !event.request.url.startsWith("data:")) {
          const { requestId: networkRequestId } = event;
          this.#networkEventManager.storeRequestWillBeSent(networkRequestId, event);
          const requestPausedEvent = this.#networkEventManager.getRequestPaused(networkRequestId);
          if (requestPausedEvent) {
            const { requestId: fetchRequestId } = requestPausedEvent;
            this.#patchRequestEventHeaders(event, requestPausedEvent);
            this.#onRequest(client2, event, fetchRequestId);
            this.#networkEventManager.forgetRequestPaused(networkRequestId);
          }
          return;
        }
        this.#onRequest(client2, event, void 0);
      }
      #onAuthRequired(client2, event) {
        let response = "Default";
        if (this.#attemptedAuthentications.has(event.requestId)) {
          response = "CancelAuth";
        } else if (this.#credentials) {
          response = "ProvideCredentials";
          this.#attemptedAuthentications.add(event.requestId);
        }
        const { username, password } = this.#credentials || {
          username: void 0,
          password: void 0
        };
        client2.send("Fetch.continueWithAuth", {
          requestId: event.requestId,
          authChallengeResponse: { response, username, password }
        }).catch(util_js_1.debugError);
      }
      /**
       * CDP may send a Fetch.requestPaused without or before a
       * Network.requestWillBeSent
       *
       * CDP may send multiple Fetch.requestPaused
       * for the same Network.requestWillBeSent.
       */
      #onRequestPaused(client2, event) {
        if (!this.#userRequestInterceptionEnabled && this.#protocolRequestInterceptionEnabled) {
          client2.send("Fetch.continueRequest", {
            requestId: event.requestId
          }).catch(util_js_1.debugError);
        }
        const { networkId: networkRequestId, requestId: fetchRequestId } = event;
        if (!networkRequestId) {
          this.#onRequestWithoutNetworkInstrumentation(client2, event);
          return;
        }
        const requestWillBeSentEvent = (() => {
          const requestWillBeSentEvent2 = this.#networkEventManager.getRequestWillBeSent(networkRequestId);
          if (requestWillBeSentEvent2 && (requestWillBeSentEvent2.request.url !== event.request.url || requestWillBeSentEvent2.request.method !== event.request.method)) {
            this.#networkEventManager.forgetRequestWillBeSent(networkRequestId);
            return;
          }
          return requestWillBeSentEvent2;
        })();
        if (requestWillBeSentEvent) {
          this.#patchRequestEventHeaders(requestWillBeSentEvent, event);
          this.#onRequest(client2, requestWillBeSentEvent, fetchRequestId);
        } else {
          this.#networkEventManager.storeRequestPaused(networkRequestId, event);
        }
      }
      #patchRequestEventHeaders(requestWillBeSentEvent, requestPausedEvent) {
        requestWillBeSentEvent.request.headers = {
          ...requestWillBeSentEvent.request.headers,
          // includes extra headers, like: Accept, Origin
          ...requestPausedEvent.request.headers
        };
      }
      #onRequestWithoutNetworkInstrumentation(client2, event) {
        const frame = event.frameId ? this.#frameManager.frame(event.frameId) : null;
        const request = new HTTPRequest_js_1.CdpHTTPRequest(client2, frame, event.requestId, this.#userRequestInterceptionEnabled, event, []);
        this.emit(NetworkManagerEvents_js_1.NetworkManagerEvent.Request, request);
        void request.finalizeInterceptions();
      }
      #onRequest(client2, event, fetchRequestId, fromMemoryCache = false) {
        let redirectChain = [];
        if (event.redirectResponse) {
          let redirectResponseExtraInfo = null;
          if (event.redirectHasExtraInfo) {
            redirectResponseExtraInfo = this.#networkEventManager.responseExtraInfo(event.requestId).shift();
            if (!redirectResponseExtraInfo) {
              this.#networkEventManager.queueRedirectInfo(event.requestId, {
                event,
                fetchRequestId
              });
              return;
            }
          }
          const request2 = this.#networkEventManager.getRequest(event.requestId);
          if (request2) {
            this.#handleRequestRedirect(client2, request2, event.redirectResponse, redirectResponseExtraInfo);
            redirectChain = request2._redirectChain;
            const extraInfo2 = this.#networkEventManager.requestExtraInfo(event.requestId).shift();
            if (extraInfo2) {
              request2.updateHeaders(extraInfo2.headers);
            }
          }
        }
        const frame = event.frameId ? this.#frameManager.frame(event.frameId) : null;
        const request = new HTTPRequest_js_1.CdpHTTPRequest(client2, frame, fetchRequestId, this.#userRequestInterceptionEnabled, event, redirectChain);
        const extraInfo = this.#networkEventManager.requestExtraInfo(event.requestId).shift();
        if (extraInfo) {
          request.updateHeaders(extraInfo.headers);
        }
        request._fromMemoryCache = fromMemoryCache;
        this.#networkEventManager.storeRequest(event.requestId, request);
        this.emit(NetworkManagerEvents_js_1.NetworkManagerEvent.Request, request);
        void request.finalizeInterceptions();
      }
      #onRequestWillBeSentExtraInfo(_client, event) {
        const request = this.#networkEventManager.getRequest(event.requestId);
        if (request) {
          request.updateHeaders(event.headers);
        } else {
          this.#networkEventManager.requestExtraInfo(event.requestId).push(event);
        }
      }
      #onRequestServedFromCache(client2, event) {
        const requestWillBeSentEvent = this.#networkEventManager.getRequestWillBeSent(event.requestId);
        let request = this.#networkEventManager.getRequest(event.requestId);
        if (request) {
          request._fromMemoryCache = true;
        }
        if (!request && requestWillBeSentEvent) {
          this.#onRequest(client2, requestWillBeSentEvent, void 0, true);
          request = this.#networkEventManager.getRequest(event.requestId);
        }
        if (!request) {
          (0, util_js_1.debugError)(new Error(`Request ${event.requestId} was served from cache but we could not find the corresponding request object`));
          return;
        }
        this.emit(NetworkManagerEvents_js_1.NetworkManagerEvent.RequestServedFromCache, request);
      }
      #handleRequestRedirect(_client, request, responsePayload, extraInfo) {
        const response = new HTTPResponse_js_1.CdpHTTPResponse(request, responsePayload, extraInfo);
        request._response = response;
        request._redirectChain.push(request);
        response._resolveBody(new Error("Response body is unavailable for redirect responses"));
        this.#forgetRequest(request, false);
        this.emit(NetworkManagerEvents_js_1.NetworkManagerEvent.Response, response);
        this.emit(NetworkManagerEvents_js_1.NetworkManagerEvent.RequestFinished, request);
      }
      #emitResponseEvent(_client, responseReceived, extraInfo) {
        const request = this.#networkEventManager.getRequest(responseReceived.requestId);
        if (!request) {
          return;
        }
        const extraInfos = this.#networkEventManager.responseExtraInfo(responseReceived.requestId);
        if (extraInfos.length) {
          (0, util_js_1.debugError)(new Error("Unexpected extraInfo events for request " + responseReceived.requestId));
        }
        if (responseReceived.response.fromDiskCache) {
          extraInfo = null;
        }
        const response = new HTTPResponse_js_1.CdpHTTPResponse(request, responseReceived.response, extraInfo);
        request._response = response;
        this.emit(NetworkManagerEvents_js_1.NetworkManagerEvent.Response, response);
      }
      #onResponseReceived(client2, event) {
        const request = this.#networkEventManager.getRequest(event.requestId);
        let extraInfo = null;
        if (request && !request._fromMemoryCache && event.hasExtraInfo) {
          extraInfo = this.#networkEventManager.responseExtraInfo(event.requestId).shift();
          if (!extraInfo) {
            this.#networkEventManager.queueEventGroup(event.requestId, {
              responseReceivedEvent: event
            });
            return;
          }
        }
        this.#emitResponseEvent(client2, event, extraInfo);
      }
      #onResponseReceivedExtraInfo(client2, event) {
        const redirectInfo = this.#networkEventManager.takeQueuedRedirectInfo(event.requestId);
        if (redirectInfo) {
          this.#networkEventManager.responseExtraInfo(event.requestId).push(event);
          this.#onRequest(client2, redirectInfo.event, redirectInfo.fetchRequestId);
          return;
        }
        const queuedEvents = this.#networkEventManager.getQueuedEventGroup(event.requestId);
        if (queuedEvents) {
          this.#networkEventManager.forgetQueuedEventGroup(event.requestId);
          this.#emitResponseEvent(client2, queuedEvents.responseReceivedEvent, event);
          if (queuedEvents.loadingFinishedEvent) {
            this.#emitLoadingFinished(client2, queuedEvents.loadingFinishedEvent);
          }
          if (queuedEvents.loadingFailedEvent) {
            this.#emitLoadingFailed(client2, queuedEvents.loadingFailedEvent);
          }
          return;
        }
        this.#networkEventManager.responseExtraInfo(event.requestId).push(event);
      }
      #forgetRequest(request, events) {
        const requestId = request.id;
        const interceptionId = request._interceptionId;
        this.#networkEventManager.forgetRequest(requestId);
        if (interceptionId !== void 0) {
          this.#attemptedAuthentications.delete(interceptionId);
        }
        if (events) {
          this.#networkEventManager.forget(requestId);
        }
      }
      #onLoadingFinished(client2, event) {
        const queuedEvents = this.#networkEventManager.getQueuedEventGroup(event.requestId);
        if (queuedEvents) {
          queuedEvents.loadingFinishedEvent = event;
        } else {
          this.#emitLoadingFinished(client2, event);
        }
      }
      #emitLoadingFinished(client2, event) {
        const request = this.#networkEventManager.getRequest(event.requestId);
        if (!request) {
          return;
        }
        this.#adoptCdpSessionIfNeeded(client2, request);
        if (request.response()) {
          request.response()?._resolveBody();
        }
        this.#forgetRequest(request, true);
        this.emit(NetworkManagerEvents_js_1.NetworkManagerEvent.RequestFinished, request);
      }
      #onLoadingFailed(client2, event) {
        const queuedEvents = this.#networkEventManager.getQueuedEventGroup(event.requestId);
        if (queuedEvents) {
          queuedEvents.loadingFailedEvent = event;
        } else {
          this.#emitLoadingFailed(client2, event);
        }
      }
      #emitLoadingFailed(client2, event) {
        const request = this.#networkEventManager.getRequest(event.requestId);
        if (!request) {
          return;
        }
        this.#adoptCdpSessionIfNeeded(client2, request);
        request._failureText = event.errorText;
        const response = request.response();
        if (response) {
          response._resolveBody();
        }
        this.#forgetRequest(request, true);
        this.emit(NetworkManagerEvents_js_1.NetworkManagerEvent.RequestFailed, request);
      }
      #adoptCdpSessionIfNeeded(client2, request) {
        if (client2 !== request.client) {
          request.client = client2;
        }
      }
    };
    exports2.NetworkManager = NetworkManager;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/FrameManager.js
var require_FrameManager = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/FrameManager.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.FrameManager = void 0;
    var CDPSession_js_1 = require_CDPSession();
    var Frame_js_1 = require_Frame();
    var EventEmitter_js_1 = require_EventEmitter();
    var util_js_1 = require_util();
    var assert_js_1 = require_assert();
    var Deferred_js_1 = require_Deferred();
    var disposable_js_1 = require_disposable();
    var ErrorLike_js_1 = require_ErrorLike();
    var CdpPreloadScript_js_1 = require_CdpPreloadScript();
    var Connection_js_1 = require_Connection();
    var DeviceRequestPrompt_js_1 = require_DeviceRequestPrompt2();
    var ExecutionContext_js_1 = require_ExecutionContext();
    var Frame_js_2 = require_Frame2();
    var FrameManagerEvents_js_1 = require_FrameManagerEvents();
    var FrameTree_js_1 = require_FrameTree();
    var IsolatedWorlds_js_1 = require_IsolatedWorlds();
    var NetworkManager_js_1 = require_NetworkManager();
    var TIME_FOR_WAITING_FOR_SWAP = 100;
    var FrameManager = class extends EventEmitter_js_1.EventEmitter {
      #page;
      #networkManager;
      #timeoutSettings;
      #isolatedWorlds = /* @__PURE__ */ new Set();
      #client;
      #scriptsToEvaluateOnNewDocument = /* @__PURE__ */ new Map();
      #bindings = /* @__PURE__ */ new Set();
      _frameTree = new FrameTree_js_1.FrameTree();
      /**
       * Set of frame IDs stored to indicate if a frame has received a
       * frameNavigated event so that frame tree responses could be ignored as the
       * frameNavigated event usually contains the latest information.
       */
      #frameNavigatedReceived = /* @__PURE__ */ new Set();
      #deviceRequestPromptManagerMap = /* @__PURE__ */ new WeakMap();
      #frameTreeHandled;
      get timeoutSettings() {
        return this.#timeoutSettings;
      }
      get networkManager() {
        return this.#networkManager;
      }
      get client() {
        return this.#client;
      }
      constructor(client2, page2, timeoutSettings) {
        super();
        this.#client = client2;
        this.#page = page2;
        this.#networkManager = new NetworkManager_js_1.NetworkManager(this, page2.browser().isNetworkEnabled());
        this.#timeoutSettings = timeoutSettings;
        this.setupEventListeners(this.#client);
        client2.once(CDPSession_js_1.CDPSessionEvent.Disconnected, () => {
          this.#onClientDisconnect().catch(util_js_1.debugError);
        });
      }
      /**
       * Called when the frame's client is disconnected. We don't know if the
       * disconnect means that the frame is removed or if it will be replaced by a
       * new frame. Therefore, we wait for a swap event.
       */
      async #onClientDisconnect() {
        const mainFrame = this._frameTree.getMainFrame();
        if (!mainFrame) {
          return;
        }
        if (!this.#page.browser().connected) {
          this.#removeFramesRecursively(mainFrame);
          return;
        }
        for (const child of mainFrame.childFrames()) {
          this.#removeFramesRecursively(child);
        }
        const swapped = Deferred_js_1.Deferred.create({
          timeout: TIME_FOR_WAITING_FOR_SWAP,
          message: "Frame was not swapped"
        });
        mainFrame.once(Frame_js_1.FrameEvent.FrameSwappedByActivation, () => {
          swapped.resolve();
        });
        try {
          await swapped.valueOrThrow();
        } catch {
          this.#removeFramesRecursively(mainFrame);
        }
      }
      /**
       * When the main frame is replaced by another main frame,
       * we maintain the main frame object identity while updating
       * its frame tree and ID.
       */
      async swapFrameTree(client2) {
        this.#client = client2;
        const frame = this._frameTree.getMainFrame();
        if (frame) {
          this.#frameNavigatedReceived.add(this.#client.target()._targetId);
          this._frameTree.removeFrame(frame);
          frame.updateId(this.#client.target()._targetId);
          this._frameTree.addFrame(frame);
          frame.updateClient(client2);
        }
        this.setupEventListeners(client2);
        client2.once(CDPSession_js_1.CDPSessionEvent.Disconnected, () => {
          this.#onClientDisconnect().catch(util_js_1.debugError);
        });
        await this.initialize(client2, frame);
        await this.#networkManager.addClient(client2);
        if (frame) {
          frame.emit(Frame_js_1.FrameEvent.FrameSwappedByActivation, void 0);
        }
      }
      async registerSpeculativeSession(client2) {
        await this.#networkManager.addClient(client2);
      }
      setupEventListeners(session) {
        session.on("Page.frameAttached", async (event) => {
          await this.#frameTreeHandled?.valueOrThrow();
          this.#onFrameAttached(session, event.frameId, event.parentFrameId);
        });
        session.on("Page.frameNavigated", async (event) => {
          this.#frameNavigatedReceived.add(event.frame.id);
          await this.#frameTreeHandled?.valueOrThrow();
          void this.#onFrameNavigated(event.frame, event.type);
        });
        session.on("Page.navigatedWithinDocument", async (event) => {
          await this.#frameTreeHandled?.valueOrThrow();
          this.#onFrameNavigatedWithinDocument(event.frameId, event.url);
        });
        session.on("Page.frameDetached", async (event) => {
          await this.#frameTreeHandled?.valueOrThrow();
          this.#onFrameDetached(event.frameId, event.reason);
        });
        session.on("Page.frameStartedLoading", async (event) => {
          await this.#frameTreeHandled?.valueOrThrow();
          this.#onFrameStartedLoading(event.frameId);
        });
        session.on("Page.frameStoppedLoading", async (event) => {
          await this.#frameTreeHandled?.valueOrThrow();
          this.#onFrameStoppedLoading(event.frameId);
        });
        session.on("Runtime.executionContextCreated", async (event) => {
          await this.#frameTreeHandled?.valueOrThrow();
          this.#onExecutionContextCreated(event.context, session);
        });
        session.on("Page.lifecycleEvent", async (event) => {
          await this.#frameTreeHandled?.valueOrThrow();
          this.#onLifecycleEvent(event);
        });
      }
      async initialize(client2, frame) {
        try {
          this.#frameTreeHandled?.resolve();
          this.#frameTreeHandled = Deferred_js_1.Deferred.create();
          await Promise.all([
            this.#networkManager.addClient(client2),
            client2.send("Page.enable"),
            client2.send("Page.getFrameTree").then(({ frameTree }) => {
              this.#handleFrameTree(client2, frameTree);
              this.#frameTreeHandled?.resolve();
            }),
            client2.send("Page.setLifecycleEventsEnabled", { enabled: true }),
            client2.send("Runtime.enable").then(() => {
              return this.#createIsolatedWorld(client2, util_js_1.UTILITY_WORLD_NAME);
            }),
            ...(frame ? Array.from(this.#scriptsToEvaluateOnNewDocument.values()) : []).map((script) => {
              return frame?.addPreloadScript(script);
            }),
            ...(frame ? Array.from(this.#bindings.values()) : []).map((binding) => {
              return frame?.addExposedFunctionBinding(binding);
            })
          ]);
        } catch (error) {
          this.#frameTreeHandled?.resolve();
          if ((0, ErrorLike_js_1.isErrorLike)(error) && (0, Connection_js_1.isTargetClosedError)(error)) {
            return;
          }
          throw error;
        }
      }
      page() {
        return this.#page;
      }
      mainFrame() {
        const mainFrame = this._frameTree.getMainFrame();
        (0, assert_js_1.assert)(mainFrame, "Requesting main frame too early!");
        return mainFrame;
      }
      frames() {
        return Array.from(this._frameTree.frames());
      }
      frame(frameId) {
        return this._frameTree.getById(frameId) || null;
      }
      async addExposedFunctionBinding(binding) {
        this.#bindings.add(binding);
        await Promise.all(this.frames().map(async (frame) => {
          return await frame.addExposedFunctionBinding(binding);
        }));
      }
      async removeExposedFunctionBinding(binding) {
        this.#bindings.delete(binding);
        await Promise.all(this.frames().map(async (frame) => {
          return await frame.removeExposedFunctionBinding(binding);
        }));
      }
      async evaluateOnNewDocument(source) {
        const { identifier } = await this.mainFrame()._client().send("Page.addScriptToEvaluateOnNewDocument", {
          source
        });
        const preloadScript = new CdpPreloadScript_js_1.CdpPreloadScript(this.mainFrame(), identifier, source);
        this.#scriptsToEvaluateOnNewDocument.set(identifier, preloadScript);
        await Promise.all(this.frames().map(async (frame) => {
          return await frame.addPreloadScript(preloadScript);
        }));
        return { identifier };
      }
      async removeScriptToEvaluateOnNewDocument(identifier) {
        const preloadScript = this.#scriptsToEvaluateOnNewDocument.get(identifier);
        if (!preloadScript) {
          throw new Error(`Script to evaluate on new document with id ${identifier} not found`);
        }
        this.#scriptsToEvaluateOnNewDocument.delete(identifier);
        await Promise.all(this.frames().map((frame) => {
          const identifier2 = preloadScript.getIdForFrame(frame);
          if (!identifier2) {
            return;
          }
          return frame._client().send("Page.removeScriptToEvaluateOnNewDocument", {
            identifier: identifier2
          }).catch(util_js_1.debugError);
        }));
      }
      onAttachedToTarget(target) {
        if (target._getTargetInfo().type !== "iframe") {
          return;
        }
        const frame = this.frame(target._getTargetInfo().targetId);
        if (frame) {
          frame.updateClient(target._session());
        }
        this.setupEventListeners(target._session());
        void this.initialize(target._session(), frame).catch(util_js_1.debugError);
      }
      _deviceRequestPromptManager(client2) {
        let manager = this.#deviceRequestPromptManagerMap.get(client2);
        if (manager === void 0) {
          manager = new DeviceRequestPrompt_js_1.CdpDeviceRequestPromptManager(client2, this.#timeoutSettings);
          this.#deviceRequestPromptManagerMap.set(client2, manager);
        }
        return manager;
      }
      #onLifecycleEvent(event) {
        const frame = this.frame(event.frameId);
        if (!frame) {
          return;
        }
        frame._onLifecycleEvent(event.loaderId, event.name);
        this.emit(FrameManagerEvents_js_1.FrameManagerEvent.LifecycleEvent, frame);
        frame.emit(Frame_js_1.FrameEvent.LifecycleEvent, void 0);
      }
      #onFrameStartedLoading(frameId) {
        const frame = this.frame(frameId);
        if (!frame) {
          return;
        }
        frame._onLoadingStarted();
      }
      #onFrameStoppedLoading(frameId) {
        const frame = this.frame(frameId);
        if (!frame) {
          return;
        }
        frame._onLoadingStopped();
        this.emit(FrameManagerEvents_js_1.FrameManagerEvent.LifecycleEvent, frame);
        frame.emit(Frame_js_1.FrameEvent.LifecycleEvent, void 0);
      }
      #handleFrameTree(session, frameTree) {
        if (frameTree.frame.parentId) {
          this.#onFrameAttached(session, frameTree.frame.id, frameTree.frame.parentId);
        }
        if (!this.#frameNavigatedReceived.has(frameTree.frame.id)) {
          void this.#onFrameNavigated(frameTree.frame, "Navigation");
        } else {
          this.#frameNavigatedReceived.delete(frameTree.frame.id);
        }
        if (!frameTree.childFrames) {
          return;
        }
        for (const child of frameTree.childFrames) {
          this.#handleFrameTree(session, child);
        }
      }
      #onFrameAttached(session, frameId, parentFrameId) {
        let frame = this.frame(frameId);
        if (frame) {
          const parentFrame = this.frame(parentFrameId);
          if (session && parentFrame && frame.client !== parentFrame?.client) {
            frame.updateClient(session);
          }
          return;
        }
        frame = new Frame_js_2.CdpFrame(this, frameId, parentFrameId, session);
        this._frameTree.addFrame(frame);
        this.emit(FrameManagerEvents_js_1.FrameManagerEvent.FrameAttached, frame);
      }
      async #onFrameNavigated(framePayload, navigationType) {
        const frameId = framePayload.id;
        const isMainFrame = !framePayload.parentId;
        let frame = this._frameTree.getById(frameId);
        if (frame) {
          for (const child of frame.childFrames()) {
            this.#removeFramesRecursively(child);
          }
        }
        if (isMainFrame) {
          if (frame) {
            this._frameTree.removeFrame(frame);
            frame._id = frameId;
          } else {
            frame = new Frame_js_2.CdpFrame(this, frameId, void 0, this.#client);
          }
          this._frameTree.addFrame(frame);
        }
        frame = await this._frameTree.waitForFrame(frameId);
        frame._navigated(framePayload);
        this.emit(FrameManagerEvents_js_1.FrameManagerEvent.FrameNavigated, frame);
        frame.emit(Frame_js_1.FrameEvent.FrameNavigated, navigationType);
      }
      async #createIsolatedWorld(session, name) {
        const key = `${session.id()}:${name}`;
        if (this.#isolatedWorlds.has(key)) {
          return;
        }
        await session.send("Page.addScriptToEvaluateOnNewDocument", {
          source: `//# sourceURL=${util_js_1.PuppeteerURL.INTERNAL_URL}`,
          worldName: name
        });
        await Promise.all(this.frames().filter((frame) => {
          return frame.client === session;
        }).map((frame) => {
          return session.send("Page.createIsolatedWorld", {
            frameId: frame._id,
            worldName: name,
            grantUniveralAccess: true
          }).catch(util_js_1.debugError);
        }));
        this.#isolatedWorlds.add(key);
      }
      #onFrameNavigatedWithinDocument(frameId, url) {
        const frame = this.frame(frameId);
        if (!frame) {
          return;
        }
        frame._navigatedWithinDocument(url);
        this.emit(FrameManagerEvents_js_1.FrameManagerEvent.FrameNavigatedWithinDocument, frame);
        frame.emit(Frame_js_1.FrameEvent.FrameNavigatedWithinDocument, void 0);
        this.emit(FrameManagerEvents_js_1.FrameManagerEvent.FrameNavigated, frame);
        frame.emit(Frame_js_1.FrameEvent.FrameNavigated, "Navigation");
      }
      #onFrameDetached(frameId, reason) {
        const frame = this.frame(frameId);
        if (!frame) {
          return;
        }
        switch (reason) {
          case "remove":
            this.#removeFramesRecursively(frame);
            break;
          case "swap":
            this.emit(FrameManagerEvents_js_1.FrameManagerEvent.FrameSwapped, frame);
            frame.emit(Frame_js_1.FrameEvent.FrameSwapped, void 0);
            break;
        }
      }
      #onExecutionContextCreated(contextPayload, session) {
        const auxData = contextPayload.auxData;
        const frameId = auxData && auxData.frameId;
        const frame = typeof frameId === "string" ? this.frame(frameId) : void 0;
        let world;
        if (frame) {
          if (frame.client !== session) {
            return;
          }
          if (contextPayload.auxData && contextPayload.auxData["isDefault"]) {
            world = frame.worlds[IsolatedWorlds_js_1.MAIN_WORLD];
          } else if (contextPayload.name === util_js_1.UTILITY_WORLD_NAME) {
            world = frame.worlds[IsolatedWorlds_js_1.PUPPETEER_WORLD];
          }
        }
        if (!world) {
          return;
        }
        const context = new ExecutionContext_js_1.ExecutionContext(frame?.client || this.#client, contextPayload, world);
        world.setContext(context);
      }
      #removeFramesRecursively(frame) {
        for (const child of frame.childFrames()) {
          this.#removeFramesRecursively(child);
        }
        frame[disposable_js_1.disposeSymbol]();
        this._frameTree.removeFrame(frame);
        this.emit(FrameManagerEvents_js_1.FrameManagerEvent.FrameDetached, frame);
        frame.emit(Frame_js_1.FrameEvent.FrameDetached, frame);
      }
    };
    exports2.FrameManager = FrameManager;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/USKeyboardLayout.js
var require_USKeyboardLayout = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/USKeyboardLayout.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2._keyDefinitions = void 0;
    exports2._keyDefinitions = {
      "0": { keyCode: 48, key: "0", code: "Digit0" },
      "1": { keyCode: 49, key: "1", code: "Digit1" },
      "2": { keyCode: 50, key: "2", code: "Digit2" },
      "3": { keyCode: 51, key: "3", code: "Digit3" },
      "4": { keyCode: 52, key: "4", code: "Digit4" },
      "5": { keyCode: 53, key: "5", code: "Digit5" },
      "6": { keyCode: 54, key: "6", code: "Digit6" },
      "7": { keyCode: 55, key: "7", code: "Digit7" },
      "8": { keyCode: 56, key: "8", code: "Digit8" },
      "9": { keyCode: 57, key: "9", code: "Digit9" },
      Power: { key: "Power", code: "Power" },
      Eject: { key: "Eject", code: "Eject" },
      Abort: { keyCode: 3, code: "Abort", key: "Cancel" },
      Help: { keyCode: 6, code: "Help", key: "Help" },
      Backspace: { keyCode: 8, code: "Backspace", key: "Backspace" },
      Tab: { keyCode: 9, code: "Tab", key: "Tab" },
      Numpad5: {
        keyCode: 12,
        shiftKeyCode: 101,
        key: "Clear",
        code: "Numpad5",
        shiftKey: "5",
        location: 3
      },
      NumpadEnter: {
        keyCode: 13,
        code: "NumpadEnter",
        key: "Enter",
        text: "\r",
        location: 3
      },
      Enter: { keyCode: 13, code: "Enter", key: "Enter", text: "\r" },
      "\r": { keyCode: 13, code: "Enter", key: "Enter", text: "\r" },
      "\n": { keyCode: 13, code: "Enter", key: "Enter", text: "\r" },
      ShiftLeft: { keyCode: 16, code: "ShiftLeft", key: "Shift", location: 1 },
      ShiftRight: { keyCode: 16, code: "ShiftRight", key: "Shift", location: 2 },
      ControlLeft: {
        keyCode: 17,
        code: "ControlLeft",
        key: "Control",
        location: 1
      },
      ControlRight: {
        keyCode: 17,
        code: "ControlRight",
        key: "Control",
        location: 2
      },
      AltLeft: { keyCode: 18, code: "AltLeft", key: "Alt", location: 1 },
      AltRight: { keyCode: 18, code: "AltRight", key: "Alt", location: 2 },
      Pause: { keyCode: 19, code: "Pause", key: "Pause" },
      CapsLock: { keyCode: 20, code: "CapsLock", key: "CapsLock" },
      Escape: { keyCode: 27, code: "Escape", key: "Escape" },
      Convert: { keyCode: 28, code: "Convert", key: "Convert" },
      NonConvert: { keyCode: 29, code: "NonConvert", key: "NonConvert" },
      Space: { keyCode: 32, code: "Space", key: " " },
      Numpad9: {
        keyCode: 33,
        shiftKeyCode: 105,
        key: "PageUp",
        code: "Numpad9",
        shiftKey: "9",
        location: 3
      },
      PageUp: { keyCode: 33, code: "PageUp", key: "PageUp" },
      Numpad3: {
        keyCode: 34,
        shiftKeyCode: 99,
        key: "PageDown",
        code: "Numpad3",
        shiftKey: "3",
        location: 3
      },
      PageDown: { keyCode: 34, code: "PageDown", key: "PageDown" },
      End: { keyCode: 35, code: "End", key: "End" },
      Numpad1: {
        keyCode: 35,
        shiftKeyCode: 97,
        key: "End",
        code: "Numpad1",
        shiftKey: "1",
        location: 3
      },
      Home: { keyCode: 36, code: "Home", key: "Home" },
      Numpad7: {
        keyCode: 36,
        shiftKeyCode: 103,
        key: "Home",
        code: "Numpad7",
        shiftKey: "7",
        location: 3
      },
      ArrowLeft: { keyCode: 37, code: "ArrowLeft", key: "ArrowLeft" },
      Numpad4: {
        keyCode: 37,
        shiftKeyCode: 100,
        key: "ArrowLeft",
        code: "Numpad4",
        shiftKey: "4",
        location: 3
      },
      Numpad8: {
        keyCode: 38,
        shiftKeyCode: 104,
        key: "ArrowUp",
        code: "Numpad8",
        shiftKey: "8",
        location: 3
      },
      ArrowUp: { keyCode: 38, code: "ArrowUp", key: "ArrowUp" },
      ArrowRight: { keyCode: 39, code: "ArrowRight", key: "ArrowRight" },
      Numpad6: {
        keyCode: 39,
        shiftKeyCode: 102,
        key: "ArrowRight",
        code: "Numpad6",
        shiftKey: "6",
        location: 3
      },
      Numpad2: {
        keyCode: 40,
        shiftKeyCode: 98,
        key: "ArrowDown",
        code: "Numpad2",
        shiftKey: "2",
        location: 3
      },
      ArrowDown: { keyCode: 40, code: "ArrowDown", key: "ArrowDown" },
      Select: { keyCode: 41, code: "Select", key: "Select" },
      Open: { keyCode: 43, code: "Open", key: "Execute" },
      PrintScreen: { keyCode: 44, code: "PrintScreen", key: "PrintScreen" },
      Insert: { keyCode: 45, code: "Insert", key: "Insert" },
      Numpad0: {
        keyCode: 45,
        shiftKeyCode: 96,
        key: "Insert",
        code: "Numpad0",
        shiftKey: "0",
        location: 3
      },
      Delete: { keyCode: 46, code: "Delete", key: "Delete" },
      NumpadDecimal: {
        keyCode: 46,
        shiftKeyCode: 110,
        code: "NumpadDecimal",
        key: "\0",
        shiftKey: ".",
        location: 3
      },
      Digit0: { keyCode: 48, code: "Digit0", shiftKey: ")", key: "0" },
      Digit1: { keyCode: 49, code: "Digit1", shiftKey: "!", key: "1" },
      Digit2: { keyCode: 50, code: "Digit2", shiftKey: "@", key: "2" },
      Digit3: { keyCode: 51, code: "Digit3", shiftKey: "#", key: "3" },
      Digit4: { keyCode: 52, code: "Digit4", shiftKey: "$", key: "4" },
      Digit5: { keyCode: 53, code: "Digit5", shiftKey: "%", key: "5" },
      Digit6: { keyCode: 54, code: "Digit6", shiftKey: "^", key: "6" },
      Digit7: { keyCode: 55, code: "Digit7", shiftKey: "&", key: "7" },
      Digit8: { keyCode: 56, code: "Digit8", shiftKey: "*", key: "8" },
      Digit9: { keyCode: 57, code: "Digit9", shiftKey: "(", key: "9" },
      KeyA: { keyCode: 65, code: "KeyA", shiftKey: "A", key: "a" },
      KeyB: { keyCode: 66, code: "KeyB", shiftKey: "B", key: "b" },
      KeyC: { keyCode: 67, code: "KeyC", shiftKey: "C", key: "c" },
      KeyD: { keyCode: 68, code: "KeyD", shiftKey: "D", key: "d" },
      KeyE: { keyCode: 69, code: "KeyE", shiftKey: "E", key: "e" },
      KeyF: { keyCode: 70, code: "KeyF", shiftKey: "F", key: "f" },
      KeyG: { keyCode: 71, code: "KeyG", shiftKey: "G", key: "g" },
      KeyH: { keyCode: 72, code: "KeyH", shiftKey: "H", key: "h" },
      KeyI: { keyCode: 73, code: "KeyI", shiftKey: "I", key: "i" },
      KeyJ: { keyCode: 74, code: "KeyJ", shiftKey: "J", key: "j" },
      KeyK: { keyCode: 75, code: "KeyK", shiftKey: "K", key: "k" },
      KeyL: { keyCode: 76, code: "KeyL", shiftKey: "L", key: "l" },
      KeyM: { keyCode: 77, code: "KeyM", shiftKey: "M", key: "m" },
      KeyN: { keyCode: 78, code: "KeyN", shiftKey: "N", key: "n" },
      KeyO: { keyCode: 79, code: "KeyO", shiftKey: "O", key: "o" },
      KeyP: { keyCode: 80, code: "KeyP", shiftKey: "P", key: "p" },
      KeyQ: { keyCode: 81, code: "KeyQ", shiftKey: "Q", key: "q" },
      KeyR: { keyCode: 82, code: "KeyR", shiftKey: "R", key: "r" },
      KeyS: { keyCode: 83, code: "KeyS", shiftKey: "S", key: "s" },
      KeyT: { keyCode: 84, code: "KeyT", shiftKey: "T", key: "t" },
      KeyU: { keyCode: 85, code: "KeyU", shiftKey: "U", key: "u" },
      KeyV: { keyCode: 86, code: "KeyV", shiftKey: "V", key: "v" },
      KeyW: { keyCode: 87, code: "KeyW", shiftKey: "W", key: "w" },
      KeyX: { keyCode: 88, code: "KeyX", shiftKey: "X", key: "x" },
      KeyY: { keyCode: 89, code: "KeyY", shiftKey: "Y", key: "y" },
      KeyZ: { keyCode: 90, code: "KeyZ", shiftKey: "Z", key: "z" },
      MetaLeft: { keyCode: 91, code: "MetaLeft", key: "Meta", location: 1 },
      MetaRight: { keyCode: 92, code: "MetaRight", key: "Meta", location: 2 },
      ContextMenu: { keyCode: 93, code: "ContextMenu", key: "ContextMenu" },
      NumpadMultiply: {
        keyCode: 106,
        code: "NumpadMultiply",
        key: "*",
        location: 3
      },
      NumpadAdd: { keyCode: 107, code: "NumpadAdd", key: "+", location: 3 },
      NumpadSubtract: {
        keyCode: 109,
        code: "NumpadSubtract",
        key: "-",
        location: 3
      },
      NumpadDivide: { keyCode: 111, code: "NumpadDivide", key: "/", location: 3 },
      F1: { keyCode: 112, code: "F1", key: "F1" },
      F2: { keyCode: 113, code: "F2", key: "F2" },
      F3: { keyCode: 114, code: "F3", key: "F3" },
      F4: { keyCode: 115, code: "F4", key: "F4" },
      F5: { keyCode: 116, code: "F5", key: "F5" },
      F6: { keyCode: 117, code: "F6", key: "F6" },
      F7: { keyCode: 118, code: "F7", key: "F7" },
      F8: { keyCode: 119, code: "F8", key: "F8" },
      F9: { keyCode: 120, code: "F9", key: "F9" },
      F10: { keyCode: 121, code: "F10", key: "F10" },
      F11: { keyCode: 122, code: "F11", key: "F11" },
      F12: { keyCode: 123, code: "F12", key: "F12" },
      F13: { keyCode: 124, code: "F13", key: "F13" },
      F14: { keyCode: 125, code: "F14", key: "F14" },
      F15: { keyCode: 126, code: "F15", key: "F15" },
      F16: { keyCode: 127, code: "F16", key: "F16" },
      F17: { keyCode: 128, code: "F17", key: "F17" },
      F18: { keyCode: 129, code: "F18", key: "F18" },
      F19: { keyCode: 130, code: "F19", key: "F19" },
      F20: { keyCode: 131, code: "F20", key: "F20" },
      F21: { keyCode: 132, code: "F21", key: "F21" },
      F22: { keyCode: 133, code: "F22", key: "F22" },
      F23: { keyCode: 134, code: "F23", key: "F23" },
      F24: { keyCode: 135, code: "F24", key: "F24" },
      NumLock: { keyCode: 144, code: "NumLock", key: "NumLock" },
      ScrollLock: { keyCode: 145, code: "ScrollLock", key: "ScrollLock" },
      AudioVolumeMute: {
        keyCode: 173,
        code: "AudioVolumeMute",
        key: "AudioVolumeMute"
      },
      AudioVolumeDown: {
        keyCode: 174,
        code: "AudioVolumeDown",
        key: "AudioVolumeDown"
      },
      AudioVolumeUp: { keyCode: 175, code: "AudioVolumeUp", key: "AudioVolumeUp" },
      MediaTrackNext: {
        keyCode: 176,
        code: "MediaTrackNext",
        key: "MediaTrackNext"
      },
      MediaTrackPrevious: {
        keyCode: 177,
        code: "MediaTrackPrevious",
        key: "MediaTrackPrevious"
      },
      MediaStop: { keyCode: 178, code: "MediaStop", key: "MediaStop" },
      MediaPlayPause: {
        keyCode: 179,
        code: "MediaPlayPause",
        key: "MediaPlayPause"
      },
      Semicolon: { keyCode: 186, code: "Semicolon", shiftKey: ":", key: ";" },
      Equal: { keyCode: 187, code: "Equal", shiftKey: "+", key: "=" },
      NumpadEqual: { keyCode: 187, code: "NumpadEqual", key: "=", location: 3 },
      Comma: { keyCode: 188, code: "Comma", shiftKey: "<", key: "," },
      Minus: { keyCode: 189, code: "Minus", shiftKey: "_", key: "-" },
      Period: { keyCode: 190, code: "Period", shiftKey: ">", key: "." },
      Slash: { keyCode: 191, code: "Slash", shiftKey: "?", key: "/" },
      Backquote: { keyCode: 192, code: "Backquote", shiftKey: "~", key: "`" },
      BracketLeft: { keyCode: 219, code: "BracketLeft", shiftKey: "{", key: "[" },
      Backslash: { keyCode: 220, code: "Backslash", shiftKey: "|", key: "\\" },
      BracketRight: { keyCode: 221, code: "BracketRight", shiftKey: "}", key: "]" },
      Quote: { keyCode: 222, code: "Quote", shiftKey: '"', key: "'" },
      AltGraph: { keyCode: 225, code: "AltGraph", key: "AltGraph" },
      Props: { keyCode: 247, code: "Props", key: "CrSel" },
      Cancel: { keyCode: 3, key: "Cancel", code: "Abort" },
      Clear: { keyCode: 12, key: "Clear", code: "Numpad5", location: 3 },
      Shift: { keyCode: 16, key: "Shift", code: "ShiftLeft", location: 1 },
      Control: { keyCode: 17, key: "Control", code: "ControlLeft", location: 1 },
      Alt: { keyCode: 18, key: "Alt", code: "AltLeft", location: 1 },
      Accept: { keyCode: 30, key: "Accept" },
      ModeChange: { keyCode: 31, key: "ModeChange" },
      " ": { keyCode: 32, key: " ", code: "Space" },
      Print: { keyCode: 42, key: "Print" },
      Execute: { keyCode: 43, key: "Execute", code: "Open" },
      "\0": { keyCode: 46, key: "\0", code: "NumpadDecimal", location: 3 },
      a: { keyCode: 65, key: "a", code: "KeyA" },
      b: { keyCode: 66, key: "b", code: "KeyB" },
      c: { keyCode: 67, key: "c", code: "KeyC" },
      d: { keyCode: 68, key: "d", code: "KeyD" },
      e: { keyCode: 69, key: "e", code: "KeyE" },
      f: { keyCode: 70, key: "f", code: "KeyF" },
      g: { keyCode: 71, key: "g", code: "KeyG" },
      h: { keyCode: 72, key: "h", code: "KeyH" },
      i: { keyCode: 73, key: "i", code: "KeyI" },
      j: { keyCode: 74, key: "j", code: "KeyJ" },
      k: { keyCode: 75, key: "k", code: "KeyK" },
      l: { keyCode: 76, key: "l", code: "KeyL" },
      m: { keyCode: 77, key: "m", code: "KeyM" },
      n: { keyCode: 78, key: "n", code: "KeyN" },
      o: { keyCode: 79, key: "o", code: "KeyO" },
      p: { keyCode: 80, key: "p", code: "KeyP" },
      q: { keyCode: 81, key: "q", code: "KeyQ" },
      r: { keyCode: 82, key: "r", code: "KeyR" },
      s: { keyCode: 83, key: "s", code: "KeyS" },
      t: { keyCode: 84, key: "t", code: "KeyT" },
      u: { keyCode: 85, key: "u", code: "KeyU" },
      v: { keyCode: 86, key: "v", code: "KeyV" },
      w: { keyCode: 87, key: "w", code: "KeyW" },
      x: { keyCode: 88, key: "x", code: "KeyX" },
      y: { keyCode: 89, key: "y", code: "KeyY" },
      z: { keyCode: 90, key: "z", code: "KeyZ" },
      Meta: { keyCode: 91, key: "Meta", code: "MetaLeft", location: 1 },
      "*": { keyCode: 106, key: "*", code: "NumpadMultiply", location: 3 },
      "+": { keyCode: 107, key: "+", code: "NumpadAdd", location: 3 },
      "-": { keyCode: 109, key: "-", code: "NumpadSubtract", location: 3 },
      "/": { keyCode: 111, key: "/", code: "NumpadDivide", location: 3 },
      ";": { keyCode: 186, key: ";", code: "Semicolon" },
      "=": { keyCode: 187, key: "=", code: "Equal" },
      ",": { keyCode: 188, key: ",", code: "Comma" },
      ".": { keyCode: 190, key: ".", code: "Period" },
      "`": { keyCode: 192, key: "`", code: "Backquote" },
      "[": { keyCode: 219, key: "[", code: "BracketLeft" },
      "\\": { keyCode: 220, key: "\\", code: "Backslash" },
      "]": { keyCode: 221, key: "]", code: "BracketRight" },
      "'": { keyCode: 222, key: "'", code: "Quote" },
      Attn: { keyCode: 246, key: "Attn" },
      CrSel: { keyCode: 247, key: "CrSel", code: "Props" },
      ExSel: { keyCode: 248, key: "ExSel" },
      EraseEof: { keyCode: 249, key: "EraseEof" },
      Play: { keyCode: 250, key: "Play" },
      ZoomOut: { keyCode: 251, key: "ZoomOut" },
      ")": { keyCode: 48, key: ")", code: "Digit0" },
      "!": { keyCode: 49, key: "!", code: "Digit1" },
      "@": { keyCode: 50, key: "@", code: "Digit2" },
      "#": { keyCode: 51, key: "#", code: "Digit3" },
      $: { keyCode: 52, key: "$", code: "Digit4" },
      "%": { keyCode: 53, key: "%", code: "Digit5" },
      "^": { keyCode: 54, key: "^", code: "Digit6" },
      "&": { keyCode: 55, key: "&", code: "Digit7" },
      "(": { keyCode: 57, key: "(", code: "Digit9" },
      A: { keyCode: 65, key: "A", code: "KeyA" },
      B: { keyCode: 66, key: "B", code: "KeyB" },
      C: { keyCode: 67, key: "C", code: "KeyC" },
      D: { keyCode: 68, key: "D", code: "KeyD" },
      E: { keyCode: 69, key: "E", code: "KeyE" },
      F: { keyCode: 70, key: "F", code: "KeyF" },
      G: { keyCode: 71, key: "G", code: "KeyG" },
      H: { keyCode: 72, key: "H", code: "KeyH" },
      I: { keyCode: 73, key: "I", code: "KeyI" },
      J: { keyCode: 74, key: "J", code: "KeyJ" },
      K: { keyCode: 75, key: "K", code: "KeyK" },
      L: { keyCode: 76, key: "L", code: "KeyL" },
      M: { keyCode: 77, key: "M", code: "KeyM" },
      N: { keyCode: 78, key: "N", code: "KeyN" },
      O: { keyCode: 79, key: "O", code: "KeyO" },
      P: { keyCode: 80, key: "P", code: "KeyP" },
      Q: { keyCode: 81, key: "Q", code: "KeyQ" },
      R: { keyCode: 82, key: "R", code: "KeyR" },
      S: { keyCode: 83, key: "S", code: "KeyS" },
      T: { keyCode: 84, key: "T", code: "KeyT" },
      U: { keyCode: 85, key: "U", code: "KeyU" },
      V: { keyCode: 86, key: "V", code: "KeyV" },
      W: { keyCode: 87, key: "W", code: "KeyW" },
      X: { keyCode: 88, key: "X", code: "KeyX" },
      Y: { keyCode: 89, key: "Y", code: "KeyY" },
      Z: { keyCode: 90, key: "Z", code: "KeyZ" },
      ":": { keyCode: 186, key: ":", code: "Semicolon" },
      "<": { keyCode: 188, key: "<", code: "Comma" },
      _: { keyCode: 189, key: "_", code: "Minus" },
      ">": { keyCode: 190, key: ">", code: "Period" },
      "?": { keyCode: 191, key: "?", code: "Slash" },
      "~": { keyCode: 192, key: "~", code: "Backquote" },
      "{": { keyCode: 219, key: "{", code: "BracketLeft" },
      "|": { keyCode: 220, key: "|", code: "Backslash" },
      "}": { keyCode: 221, key: "}", code: "BracketRight" },
      '"': { keyCode: 222, key: '"', code: "Quote" },
      SoftLeft: { key: "SoftLeft", code: "SoftLeft", location: 4 },
      SoftRight: { key: "SoftRight", code: "SoftRight", location: 4 },
      Camera: { keyCode: 44, key: "Camera", code: "Camera", location: 4 },
      Call: { key: "Call", code: "Call", location: 4 },
      EndCall: { keyCode: 95, key: "EndCall", code: "EndCall", location: 4 },
      VolumeDown: {
        keyCode: 182,
        key: "VolumeDown",
        code: "VolumeDown",
        location: 4
      },
      VolumeUp: { keyCode: 183, key: "VolumeUp", code: "VolumeUp", location: 4 }
    };
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Input.js
var require_Input2 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Input.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CdpTouchscreen = exports2.CdpTouchHandle = exports2.CdpMouse = exports2.CdpKeyboard = void 0;
    var Input_js_1 = require_Input();
    var Errors_js_1 = require_Errors();
    var USKeyboardLayout_js_1 = require_USKeyboardLayout();
    var assert_js_1 = require_assert();
    var CdpKeyboard = class extends Input_js_1.Keyboard {
      #client;
      #pressedKeys = /* @__PURE__ */ new Set();
      _modifiers = 0;
      constructor(client2) {
        super();
        this.#client = client2;
      }
      updateClient(client2) {
        this.#client = client2;
      }
      async down(key, options = {
        text: void 0,
        commands: []
      }) {
        const description = this.#keyDescriptionForString(key);
        const autoRepeat = this.#pressedKeys.has(description.code);
        this.#pressedKeys.add(description.code);
        this._modifiers |= this.#modifierBit(description.key);
        const text = options.text === void 0 ? description.text : options.text;
        await this.#client.send("Input.dispatchKeyEvent", {
          type: text ? "keyDown" : "rawKeyDown",
          modifiers: this._modifiers,
          windowsVirtualKeyCode: description.keyCode,
          code: description.code,
          key: description.key,
          text,
          unmodifiedText: text,
          autoRepeat,
          location: description.location,
          isKeypad: description.location === 3,
          commands: options.commands
        });
      }
      #modifierBit(key) {
        if (key === "Alt") {
          return 1;
        }
        if (key === "Control") {
          return 2;
        }
        if (key === "Meta") {
          return 4;
        }
        if (key === "Shift") {
          return 8;
        }
        return 0;
      }
      #keyDescriptionForString(keyString) {
        const shift = this._modifiers & 8;
        const description = {
          key: "",
          keyCode: 0,
          code: "",
          text: "",
          location: 0
        };
        const definition = USKeyboardLayout_js_1._keyDefinitions[keyString];
        (0, assert_js_1.assert)(definition, `Unknown key: "${keyString}"`);
        if (definition.key) {
          description.key = definition.key;
        }
        if (shift && definition.shiftKey) {
          description.key = definition.shiftKey;
        }
        if (definition.keyCode) {
          description.keyCode = definition.keyCode;
        }
        if (shift && definition.shiftKeyCode) {
          description.keyCode = definition.shiftKeyCode;
        }
        if (definition.code) {
          description.code = definition.code;
        }
        if (definition.location) {
          description.location = definition.location;
        }
        if (description.key.length === 1) {
          description.text = description.key;
        }
        if (definition.text) {
          description.text = definition.text;
        }
        if (shift && definition.shiftText) {
          description.text = definition.shiftText;
        }
        if (this._modifiers & ~8) {
          description.text = "";
        }
        return description;
      }
      async up(key) {
        const description = this.#keyDescriptionForString(key);
        this._modifiers &= ~this.#modifierBit(description.key);
        this.#pressedKeys.delete(description.code);
        await this.#client.send("Input.dispatchKeyEvent", {
          type: "keyUp",
          modifiers: this._modifiers,
          key: description.key,
          windowsVirtualKeyCode: description.keyCode,
          code: description.code,
          location: description.location
        });
      }
      async sendCharacter(char) {
        await this.#client.send("Input.insertText", { text: char });
      }
      charIsKey(char) {
        return !!USKeyboardLayout_js_1._keyDefinitions[char];
      }
      async type(text, options = {}) {
        const delay = options.delay || void 0;
        for (const char of text) {
          if (this.charIsKey(char)) {
            await this.press(char, { delay });
          } else {
            if (delay) {
              await new Promise((f) => {
                return setTimeout(f, delay);
              });
            }
            await this.sendCharacter(char);
          }
        }
      }
      async press(key, options = {}) {
        const { delay = null } = options;
        await this.down(key, options);
        if (delay) {
          await new Promise((f) => {
            return setTimeout(f, options.delay);
          });
        }
        await this.up(key);
      }
    };
    exports2.CdpKeyboard = CdpKeyboard;
    var getFlag = (button) => {
      switch (button) {
        case Input_js_1.MouseButton.Left:
          return 1;
        case Input_js_1.MouseButton.Right:
          return 2;
        case Input_js_1.MouseButton.Middle:
          return 4;
        case Input_js_1.MouseButton.Back:
          return 8;
        case Input_js_1.MouseButton.Forward:
          return 16;
      }
    };
    var getButtonFromPressedButtons = (buttons) => {
      if (buttons & 1) {
        return Input_js_1.MouseButton.Left;
      } else if (buttons & 2) {
        return Input_js_1.MouseButton.Right;
      } else if (buttons & 4) {
        return Input_js_1.MouseButton.Middle;
      } else if (buttons & 8) {
        return Input_js_1.MouseButton.Back;
      } else if (buttons & 16) {
        return Input_js_1.MouseButton.Forward;
      }
      return "none";
    };
    var CdpMouse = class extends Input_js_1.Mouse {
      #client;
      #keyboard;
      constructor(client2, keyboard) {
        super();
        this.#client = client2;
        this.#keyboard = keyboard;
      }
      updateClient(client2) {
        this.#client = client2;
      }
      #_state = {
        position: { x: 0, y: 0 },
        buttons: 0
      };
      get #state() {
        return Object.assign({ ...this.#_state }, ...this.#transactions);
      }
      // Transactions can run in parallel, so we store each of thme in this array.
      #transactions = [];
      #createTransaction() {
        const transaction = {};
        this.#transactions.push(transaction);
        const popTransaction = () => {
          this.#transactions.splice(this.#transactions.indexOf(transaction), 1);
        };
        return {
          update: (updates) => {
            Object.assign(transaction, updates);
          },
          commit: () => {
            this.#_state = { ...this.#_state, ...transaction };
            popTransaction();
          },
          rollback: popTransaction
        };
      }
      /**
       * This is a shortcut for a typical update, commit/rollback lifecycle based on
       * the error of the action.
       */
      async #withTransaction(action) {
        const { update, commit, rollback } = this.#createTransaction();
        try {
          await action(update);
          commit();
        } catch (error) {
          rollback();
          throw error;
        }
      }
      async reset() {
        const actions = [];
        for (const [flag, button] of [
          [1, Input_js_1.MouseButton.Left],
          [4, Input_js_1.MouseButton.Middle],
          [2, Input_js_1.MouseButton.Right],
          [16, Input_js_1.MouseButton.Forward],
          [8, Input_js_1.MouseButton.Back]
        ]) {
          if (this.#state.buttons & flag) {
            actions.push(this.up({ button }));
          }
        }
        if (this.#state.position.x !== 0 || this.#state.position.y !== 0) {
          actions.push(this.move(0, 0));
        }
        await Promise.all(actions);
      }
      async move(x, y, options = {}) {
        const { steps = 1 } = options;
        const from = this.#state.position;
        const to = { x, y };
        for (let i = 1; i <= steps; i++) {
          await this.#withTransaction((updateState) => {
            updateState({
              position: {
                x: from.x + (to.x - from.x) * (i / steps),
                y: from.y + (to.y - from.y) * (i / steps)
              }
            });
            const { buttons, position } = this.#state;
            return this.#client.send("Input.dispatchMouseEvent", {
              type: "mouseMoved",
              modifiers: this.#keyboard._modifiers,
              buttons,
              button: getButtonFromPressedButtons(buttons),
              ...position
            });
          });
        }
      }
      async down(options = {}) {
        const { button = Input_js_1.MouseButton.Left, clickCount = 1 } = options;
        const flag = getFlag(button);
        if (!flag) {
          throw new Error(`Unsupported mouse button: ${button}`);
        }
        if (this.#state.buttons & flag) {
          throw new Error(`'${button}' is already pressed.`);
        }
        await this.#withTransaction((updateState) => {
          updateState({
            buttons: this.#state.buttons | flag
          });
          const { buttons, position } = this.#state;
          return this.#client.send("Input.dispatchMouseEvent", {
            type: "mousePressed",
            modifiers: this.#keyboard._modifiers,
            clickCount,
            buttons,
            button,
            ...position
          });
        });
      }
      async up(options = {}) {
        const { button = Input_js_1.MouseButton.Left, clickCount = 1 } = options;
        const flag = getFlag(button);
        if (!flag) {
          throw new Error(`Unsupported mouse button: ${button}`);
        }
        if (!(this.#state.buttons & flag)) {
          throw new Error(`'${button}' is not pressed.`);
        }
        await this.#withTransaction((updateState) => {
          updateState({
            buttons: this.#state.buttons & ~flag
          });
          const { buttons, position } = this.#state;
          return this.#client.send("Input.dispatchMouseEvent", {
            type: "mouseReleased",
            modifiers: this.#keyboard._modifiers,
            clickCount,
            buttons,
            button,
            ...position
          });
        });
      }
      async click(x, y, options = {}) {
        const { delay, count = 1, clickCount = count } = options;
        if (count < 1) {
          throw new Error("Click must occur a positive number of times.");
        }
        const actions = [this.move(x, y)];
        if (clickCount === count) {
          for (let i = 1; i < count; ++i) {
            actions.push(this.down({ ...options, clickCount: i }), this.up({ ...options, clickCount: i }));
          }
        }
        actions.push(this.down({ ...options, clickCount }));
        if (typeof delay === "number") {
          await Promise.all(actions);
          actions.length = 0;
          await new Promise((resolve5) => {
            setTimeout(resolve5, delay);
          });
        }
        actions.push(this.up({ ...options, clickCount }));
        await Promise.all(actions);
      }
      async wheel(options = {}) {
        const { deltaX = 0, deltaY = 0 } = options;
        const { position, buttons } = this.#state;
        await this.#client.send("Input.dispatchMouseEvent", {
          type: "mouseWheel",
          pointerType: "mouse",
          modifiers: this.#keyboard._modifiers,
          deltaY,
          deltaX,
          buttons,
          ...position
        });
      }
      async drag(start, target) {
        const promise = new Promise((resolve5) => {
          this.#client.once("Input.dragIntercepted", (event) => {
            return resolve5(event.data);
          });
        });
        await this.move(start.x, start.y);
        await this.down();
        await this.move(target.x, target.y);
        return await promise;
      }
      async dragEnter(target, data) {
        await this.#client.send("Input.dispatchDragEvent", {
          type: "dragEnter",
          x: target.x,
          y: target.y,
          modifiers: this.#keyboard._modifiers,
          data
        });
      }
      async dragOver(target, data) {
        await this.#client.send("Input.dispatchDragEvent", {
          type: "dragOver",
          x: target.x,
          y: target.y,
          modifiers: this.#keyboard._modifiers,
          data
        });
      }
      async drop(target, data) {
        await this.#client.send("Input.dispatchDragEvent", {
          type: "drop",
          x: target.x,
          y: target.y,
          modifiers: this.#keyboard._modifiers,
          data
        });
      }
      async dragAndDrop(start, target, options = {}) {
        const { delay = null } = options;
        const data = await this.drag(start, target);
        await this.dragEnter(target, data);
        await this.dragOver(target, data);
        if (delay) {
          await new Promise((resolve5) => {
            return setTimeout(resolve5, delay);
          });
        }
        await this.drop(target, data);
        await this.up();
      }
    };
    exports2.CdpMouse = CdpMouse;
    var CdpTouchHandle = class {
      #started = false;
      #touchScreen;
      #touchPoint;
      #client;
      #keyboard;
      constructor(client2, touchScreen, keyboard, touchPoint) {
        this.#client = client2;
        this.#touchScreen = touchScreen;
        this.#keyboard = keyboard;
        this.#touchPoint = touchPoint;
      }
      updateClient(client2) {
        this.#client = client2;
      }
      async start() {
        if (this.#started) {
          throw new Errors_js_1.TouchError("Touch has already started");
        }
        await this.#client.send("Input.dispatchTouchEvent", {
          type: "touchStart",
          touchPoints: [this.#touchPoint],
          modifiers: this.#keyboard._modifiers
        });
        this.#started = true;
      }
      move(x, y) {
        this.#touchPoint.x = Math.round(x);
        this.#touchPoint.y = Math.round(y);
        return this.#client.send("Input.dispatchTouchEvent", {
          type: "touchMove",
          touchPoints: [this.#touchPoint],
          modifiers: this.#keyboard._modifiers
        });
      }
      async end() {
        await this.#client.send("Input.dispatchTouchEvent", {
          type: "touchEnd",
          touchPoints: [this.#touchPoint],
          modifiers: this.#keyboard._modifiers
        });
        this.#touchScreen.removeHandle(this);
      }
    };
    exports2.CdpTouchHandle = CdpTouchHandle;
    var CdpTouchscreen = class extends Input_js_1.Touchscreen {
      #client;
      #keyboard;
      constructor(client2, keyboard) {
        super();
        this.#client = client2;
        this.#keyboard = keyboard;
      }
      updateClient(client2) {
        this.#client = client2;
        this.touches.forEach((t) => {
          t.updateClient(client2);
        });
      }
      async touchStart(x, y) {
        const id = this.idGenerator();
        const touchPoint = {
          x: Math.round(x),
          y: Math.round(y),
          radiusX: 0.5,
          radiusY: 0.5,
          force: 0.5,
          id
        };
        const touch = new CdpTouchHandle(this.#client, this, this.#keyboard, touchPoint);
        await touch.start();
        this.touches.push(touch);
        return touch;
      }
    };
    exports2.CdpTouchscreen = CdpTouchscreen;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Tracing.js
var require_Tracing = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Tracing.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Tracing = void 0;
    var util_js_1 = require_util();
    var assert_js_1 = require_assert();
    var Deferred_js_1 = require_Deferred();
    var ErrorLike_js_1 = require_ErrorLike();
    var Tracing = class {
      #client;
      #recording = false;
      #path;
      /**
       * @internal
       */
      constructor(client2) {
        this.#client = client2;
      }
      /**
       * @internal
       */
      updateClient(client2) {
        this.#client = client2;
      }
      /**
       * Starts a trace for the current page.
       * @remarks
       * Only one trace can be active at a time per browser.
       *
       * @param options - Optional `TracingOptions`.
       */
      async start(options = {}) {
        (0, assert_js_1.assert)(!this.#recording, "Cannot start recording trace while already recording trace.");
        const defaultCategories = [
          "-*",
          "devtools.timeline",
          "v8.execute",
          "disabled-by-default-devtools.timeline",
          "disabled-by-default-devtools.timeline.frame",
          "toplevel",
          "blink.console",
          "blink.user_timing",
          "latencyInfo",
          "disabled-by-default-devtools.timeline.stack",
          "disabled-by-default-v8.cpu_profiler"
        ];
        const { path: path2, screenshots = false, categories = defaultCategories } = options;
        if (screenshots) {
          categories.push("disabled-by-default-devtools.screenshot");
        }
        const excludedCategories = categories.filter((cat) => {
          return cat.startsWith("-");
        }).map((cat) => {
          return cat.slice(1);
        });
        const includedCategories = categories.filter((cat) => {
          return !cat.startsWith("-");
        });
        this.#path = path2;
        this.#recording = true;
        await this.#client.send("Tracing.start", {
          transferMode: "ReturnAsStream",
          traceConfig: {
            excludedCategories,
            includedCategories
          }
        });
      }
      /**
       * Stops a trace started with the `start` method.
       * @returns Promise which resolves to buffer with trace data.
       */
      async stop() {
        const contentDeferred = Deferred_js_1.Deferred.create();
        this.#client.once("Tracing.tracingComplete", async (event) => {
          try {
            (0, assert_js_1.assert)(event.stream, 'Missing "stream"');
            const readable = await (0, util_js_1.getReadableFromProtocolStream)(this.#client, event.stream);
            const typedArray = await (0, util_js_1.getReadableAsTypedArray)(readable, this.#path);
            contentDeferred.resolve(typedArray ?? void 0);
          } catch (error) {
            if ((0, ErrorLike_js_1.isErrorLike)(error)) {
              contentDeferred.reject(error);
            } else {
              contentDeferred.reject(new Error(`Unknown error: ${error}`));
            }
          }
        });
        await this.#client.send("Tracing.end");
        this.#recording = false;
        return await contentDeferred.valueOrThrow();
      }
    };
    exports2.Tracing = Tracing;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/WebWorker.js
var require_WebWorker2 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/WebWorker.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CdpWebWorker = void 0;
    var CDPSession_js_1 = require_CDPSession();
    var Target_js_1 = require_Target();
    var WebWorker_js_1 = require_WebWorker();
    var TimeoutSettings_js_1 = require_TimeoutSettings();
    var util_js_1 = require_util();
    var ExecutionContext_js_1 = require_ExecutionContext();
    var IsolatedWorld_js_1 = require_IsolatedWorld();
    var CdpWebWorker = class extends WebWorker_js_1.WebWorker {
      #world;
      #client;
      #id;
      #targetType;
      constructor(client2, url, targetId, targetType, consoleAPICalled, exceptionThrown, networkManager) {
        super(url);
        this.#id = targetId;
        this.#client = client2;
        this.#targetType = targetType;
        this.#world = new IsolatedWorld_js_1.IsolatedWorld(this, new TimeoutSettings_js_1.TimeoutSettings());
        this.#client.once("Runtime.executionContextCreated", async (event) => {
          this.#world.setContext(new ExecutionContext_js_1.ExecutionContext(client2, event.context, this.#world));
        });
        this.#world.emitter.on("consoleapicalled", async (event) => {
          try {
            return consoleAPICalled(this.#world, event);
          } catch (err) {
            (0, util_js_1.debugError)(err);
          }
        });
        this.#client.on("Runtime.exceptionThrown", exceptionThrown);
        this.#client.once(CDPSession_js_1.CDPSessionEvent.Disconnected, () => {
          this.#world.dispose();
        });
        networkManager?.addClient(this.#client).catch(util_js_1.debugError);
        this.#client.send("Runtime.enable").catch(util_js_1.debugError);
      }
      mainRealm() {
        return this.#world;
      }
      get client() {
        return this.#client;
      }
      async close() {
        switch (this.#targetType) {
          case Target_js_1.TargetType.SERVICE_WORKER: {
            await this.client.connection()?.send("Target.closeTarget", {
              targetId: this.#id
            });
            await this.client.connection()?.send("Target.detachFromTarget", {
              sessionId: this.client.id()
            });
            break;
          }
          case Target_js_1.TargetType.SHARED_WORKER: {
            await this.client.connection()?.send("Target.closeTarget", {
              targetId: this.#id
            });
            break;
          }
          default:
            await this.evaluate(() => {
              self.close();
            });
        }
      }
    };
    exports2.CdpWebWorker = CdpWebWorker;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Page.js
var require_Page2 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Page.js"(exports2) {
    "use strict";
    init_prefix();
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CdpPage = void 0;
    exports2.convertSameSiteFromPuppeteerToCdp = convertSameSiteFromPuppeteerToCdp;
    exports2.convertCookiesPartitionKeyFromPuppeteerToCdp = convertCookiesPartitionKeyFromPuppeteerToCdp;
    var rxjs_js_1 = require_rxjs();
    var CDPSession_js_1 = require_CDPSession();
    var Page_js_1 = require_Page();
    var ConsoleMessage_js_1 = require_ConsoleMessage();
    var Errors_js_1 = require_Errors();
    var EventEmitter_js_1 = require_EventEmitter();
    var FileChooser_js_1 = require_FileChooser();
    var NetworkManagerEvents_js_1 = require_NetworkManagerEvents();
    var util_js_1 = require_util();
    var environment_js_1 = require_environment();
    var assert_js_1 = require_assert();
    var Deferred_js_1 = require_Deferred();
    var disposable_js_1 = require_disposable();
    var ErrorLike_js_1 = require_ErrorLike();
    var Binding_js_1 = require_Binding();
    var BluetoothEmulation_js_1 = require_BluetoothEmulation();
    var CdpSession_js_1 = require_CdpSession();
    var Connection_js_1 = require_Connection();
    var Coverage_js_1 = require_Coverage();
    var Dialog_js_1 = require_Dialog2();
    var EmulationManager_js_1 = require_EmulationManager();
    var FrameManager_js_1 = require_FrameManager();
    var FrameManagerEvents_js_1 = require_FrameManagerEvents();
    var Input_js_1 = require_Input2();
    var IsolatedWorlds_js_1 = require_IsolatedWorlds();
    var JSHandle_js_1 = require_JSHandle2();
    var Tracing_js_1 = require_Tracing();
    var utils_js_1 = require_utils();
    var WebWorker_js_1 = require_WebWorker2();
    function convertConsoleMessageLevel(method) {
      switch (method) {
        case "warning":
          return "warn";
        default:
          return method;
      }
    }
    function convertSameSiteFromPuppeteerToCdp(sameSite) {
      switch (sameSite) {
        case "Strict":
        case "Lax":
        case "None":
          return sameSite;
        default:
          return void 0;
      }
    }
    var CdpPage = class _CdpPage extends Page_js_1.Page {
      static async _create(client2, target, defaultViewport) {
        const page2 = new _CdpPage(client2, target);
        await page2.#initialize();
        if (defaultViewport) {
          try {
            await page2.setViewport(defaultViewport);
          } catch (err) {
            if ((0, ErrorLike_js_1.isErrorLike)(err) && (0, Connection_js_1.isTargetClosedError)(err)) {
              (0, util_js_1.debugError)(err);
            } else {
              throw err;
            }
          }
        }
        return page2;
      }
      #closed = false;
      #targetManager;
      #cdpBluetoothEmulation;
      #primaryTargetClient;
      #primaryTarget;
      #tabTargetClient;
      #tabTarget;
      #keyboard;
      #mouse;
      #touchscreen;
      #frameManager;
      #emulationManager;
      #tracing;
      #bindings = /* @__PURE__ */ new Map();
      #exposedFunctions = /* @__PURE__ */ new Map();
      #coverage;
      #viewport;
      #workers = /* @__PURE__ */ new Map();
      #fileChooserDeferreds = /* @__PURE__ */ new Set();
      #sessionCloseDeferred = Deferred_js_1.Deferred.create();
      #serviceWorkerBypassed = false;
      #userDragInterceptionEnabled = false;
      constructor(client2, target) {
        super();
        this.#primaryTargetClient = client2;
        this.#tabTargetClient = client2.parentSession();
        (0, assert_js_1.assert)(this.#tabTargetClient, "Tab target session is not defined.");
        this.#tabTarget = this.#tabTargetClient.target();
        (0, assert_js_1.assert)(this.#tabTarget, "Tab target is not defined.");
        this._tabId = this.#tabTarget._getTargetInfo().targetId;
        this.#primaryTarget = target;
        this.#targetManager = target._targetManager();
        this.#keyboard = new Input_js_1.CdpKeyboard(client2);
        this.#mouse = new Input_js_1.CdpMouse(client2, this.#keyboard);
        this.#touchscreen = new Input_js_1.CdpTouchscreen(client2, this.#keyboard);
        this.#frameManager = new FrameManager_js_1.FrameManager(client2, this, this._timeoutSettings);
        this.#emulationManager = new EmulationManager_js_1.EmulationManager(client2);
        this.#tracing = new Tracing_js_1.Tracing(client2);
        this.#coverage = new Coverage_js_1.Coverage(client2);
        this.#viewport = null;
        this.#cdpBluetoothEmulation = new BluetoothEmulation_js_1.CdpBluetoothEmulation(this.#primaryTargetClient.connection());
        const frameManagerEmitter = new EventEmitter_js_1.EventEmitter(this.#frameManager);
        frameManagerEmitter.on(FrameManagerEvents_js_1.FrameManagerEvent.FrameAttached, (frame) => {
          this.emit("frameattached", frame);
        });
        frameManagerEmitter.on(FrameManagerEvents_js_1.FrameManagerEvent.FrameDetached, (frame) => {
          this.emit("framedetached", frame);
        });
        frameManagerEmitter.on(FrameManagerEvents_js_1.FrameManagerEvent.FrameNavigated, (frame) => {
          this.emit("framenavigated", frame);
        });
        frameManagerEmitter.on(FrameManagerEvents_js_1.FrameManagerEvent.ConsoleApiCalled, ([world, event]) => {
          this.#onConsoleAPI(world, event);
        });
        frameManagerEmitter.on(FrameManagerEvents_js_1.FrameManagerEvent.BindingCalled, ([world, event]) => {
          void this.#onBindingCalled(world, event);
        });
        const networkManagerEmitter = new EventEmitter_js_1.EventEmitter(this.#frameManager.networkManager);
        networkManagerEmitter.on(NetworkManagerEvents_js_1.NetworkManagerEvent.Request, (request) => {
          this.emit("request", request);
        });
        networkManagerEmitter.on(NetworkManagerEvents_js_1.NetworkManagerEvent.RequestServedFromCache, (request) => {
          this.emit("requestservedfromcache", request);
        });
        networkManagerEmitter.on(NetworkManagerEvents_js_1.NetworkManagerEvent.Response, (response) => {
          this.emit("response", response);
        });
        networkManagerEmitter.on(NetworkManagerEvents_js_1.NetworkManagerEvent.RequestFailed, (request) => {
          this.emit("requestfailed", request);
        });
        networkManagerEmitter.on(NetworkManagerEvents_js_1.NetworkManagerEvent.RequestFinished, (request) => {
          this.emit("requestfinished", request);
        });
        this.#tabTargetClient.on(CDPSession_js_1.CDPSessionEvent.Swapped, this.#onActivation.bind(this));
        this.#tabTargetClient.on(CDPSession_js_1.CDPSessionEvent.Ready, this.#onSecondaryTarget.bind(this));
        this.#targetManager.on("targetGone", this.#onDetachedFromTarget);
        this.#tabTarget._isClosedDeferred.valueOrThrow().then(() => {
          this.#targetManager.off("targetGone", this.#onDetachedFromTarget);
          this.emit("close", void 0);
          this.#closed = true;
        }).catch(util_js_1.debugError);
        this.#setupPrimaryTargetListeners();
        this.#attachExistingTargets();
      }
      #attachExistingTargets() {
        const queue = [];
        for (const childTarget of this.#targetManager.getChildTargets(this.#primaryTarget)) {
          queue.push(childTarget);
        }
        let idx = 0;
        while (idx < queue.length) {
          const next = queue[idx];
          idx++;
          const session = next._session();
          if (session) {
            this.#onAttachedToTarget(session);
          }
          for (const childTarget of this.#targetManager.getChildTargets(next)) {
            queue.push(childTarget);
          }
        }
      }
      async #onActivation(newSession) {
        (0, assert_js_1.assert)(newSession instanceof CdpSession_js_1.CdpCDPSession, "CDPSession is not instance of CdpCDPSession");
        this.#primaryTargetClient = newSession;
        this.#primaryTarget = newSession.target();
        (0, assert_js_1.assert)(this.#primaryTarget, "Missing target on swap");
        this.#keyboard.updateClient(newSession);
        this.#mouse.updateClient(newSession);
        this.#touchscreen.updateClient(newSession);
        this.#emulationManager.updateClient(newSession);
        this.#tracing.updateClient(newSession);
        this.#coverage.updateClient(newSession);
        await this.#frameManager.swapFrameTree(newSession);
        this.#setupPrimaryTargetListeners();
      }
      async #onSecondaryTarget(session) {
        (0, assert_js_1.assert)(session instanceof CdpSession_js_1.CdpCDPSession);
        if (session.target()._subtype() !== "prerender") {
          return;
        }
        this.#frameManager.registerSpeculativeSession(session).catch(util_js_1.debugError);
        this.#emulationManager.registerSpeculativeSession(session).catch(util_js_1.debugError);
      }
      /**
       * Sets up listeners for the primary target. The primary target can change
       * during a navigation to a prerended page.
       */
      #setupPrimaryTargetListeners() {
        const clientEmitter = new EventEmitter_js_1.EventEmitter(this.#primaryTargetClient);
        clientEmitter.on(CDPSession_js_1.CDPSessionEvent.Ready, this.#onAttachedToTarget);
        clientEmitter.on(CDPSession_js_1.CDPSessionEvent.Disconnected, () => {
          this.#sessionCloseDeferred.reject(new Errors_js_1.TargetCloseError("Target closed"));
        });
        clientEmitter.on("Page.domContentEventFired", () => {
          this.emit("domcontentloaded", void 0);
        });
        clientEmitter.on("Page.loadEventFired", () => {
          this.emit("load", void 0);
        });
        clientEmitter.on("Page.javascriptDialogOpening", this.#onDialog.bind(this));
        clientEmitter.on("Runtime.exceptionThrown", this.#handleException.bind(this));
        clientEmitter.on("Inspector.targetCrashed", this.#onTargetCrashed.bind(this));
        clientEmitter.on("Performance.metrics", this.#emitMetrics.bind(this));
        clientEmitter.on("Log.entryAdded", this.#onLogEntryAdded.bind(this));
        clientEmitter.on("Page.fileChooserOpened", this.#onFileChooser.bind(this));
      }
      #onDetachedFromTarget = (target) => {
        const sessionId = target._session()?.id();
        const worker = this.#workers.get(sessionId);
        if (!worker) {
          return;
        }
        this.#workers.delete(sessionId);
        this.emit("workerdestroyed", worker);
      };
      #onAttachedToTarget = (session) => {
        (0, assert_js_1.assert)(session instanceof CdpSession_js_1.CdpCDPSession);
        this.#frameManager.onAttachedToTarget(session.target());
        if (session.target()._getTargetInfo().type === "worker") {
          const worker = new WebWorker_js_1.CdpWebWorker(session, session.target().url(), session.target()._targetId, session.target().type(), this.#onConsoleAPI.bind(this), this.#handleException.bind(this), this.#frameManager.networkManager);
          this.#workers.set(session.id(), worker);
          this.emit("workercreated", worker);
        }
        session.on(CDPSession_js_1.CDPSessionEvent.Ready, this.#onAttachedToTarget);
      };
      async #initialize() {
        try {
          await Promise.all([
            this.#frameManager.initialize(this.#primaryTargetClient),
            this.#primaryTargetClient.send("Performance.enable"),
            this.#primaryTargetClient.send("Log.enable")
          ]);
        } catch (err) {
          if ((0, ErrorLike_js_1.isErrorLike)(err) && (0, Connection_js_1.isTargetClosedError)(err)) {
            (0, util_js_1.debugError)(err);
          } else {
            throw err;
          }
        }
      }
      async resize(params) {
        const windowId = await this.windowId();
        await this.#primaryTargetClient.send("Browser.setContentsSize", {
          windowId: Number(windowId),
          width: params.contentWidth,
          height: params.contentHeight
        });
      }
      async windowId() {
        const { windowId } = await this.#primaryTargetClient.send("Browser.getWindowForTarget");
        return windowId.toString();
      }
      async #onFileChooser(event) {
        const env_1 = { stack: [], error: void 0, hasError: false };
        try {
          if (!this.#fileChooserDeferreds.size) {
            return;
          }
          const frame = this.#frameManager.frame(event.frameId);
          (0, assert_js_1.assert)(frame, "This should never happen.");
          const handle = __addDisposableResource2(env_1, await frame.worlds[IsolatedWorlds_js_1.MAIN_WORLD].adoptBackendNode(event.backendNodeId), false);
          const fileChooser = new FileChooser_js_1.FileChooser(handle.move(), event.mode !== "selectSingle");
          for (const promise of this.#fileChooserDeferreds) {
            promise.resolve(fileChooser);
          }
          this.#fileChooserDeferreds.clear();
        } catch (e_1) {
          env_1.error = e_1;
          env_1.hasError = true;
        } finally {
          __disposeResources2(env_1);
        }
      }
      _client() {
        return this.#primaryTargetClient;
      }
      isServiceWorkerBypassed() {
        return this.#serviceWorkerBypassed;
      }
      isDragInterceptionEnabled() {
        return this.#userDragInterceptionEnabled;
      }
      isJavaScriptEnabled() {
        return this.#emulationManager.javascriptEnabled;
      }
      async openDevTools() {
        const pageTargetId = this.target()._targetId;
        const browser = this.browser();
        const devtoolsPage = await browser._createDevToolsPage(pageTargetId);
        return devtoolsPage;
      }
      async hasDevTools() {
        const browser = this.browser();
        const targetId = await browser._hasDevToolsTarget(this.target()._targetId);
        return Boolean(targetId);
      }
      async waitForFileChooser(options = {}) {
        const needsEnable = this.#fileChooserDeferreds.size === 0;
        const { timeout = this._timeoutSettings.timeout() } = options;
        const deferred = Deferred_js_1.Deferred.create({
          message: `Waiting for \`FileChooser\` failed: ${timeout}ms exceeded`,
          timeout
        });
        if (options.signal) {
          options.signal.addEventListener("abort", () => {
            deferred.reject(options.signal?.reason);
          }, { once: true });
        }
        this.#fileChooserDeferreds.add(deferred);
        let enablePromise;
        if (needsEnable) {
          enablePromise = this.#primaryTargetClient.send("Page.setInterceptFileChooserDialog", {
            enabled: true
          });
        }
        try {
          const [result] = await Promise.all([
            deferred.valueOrThrow(),
            enablePromise
          ]);
          return result;
        } catch (error) {
          this.#fileChooserDeferreds.delete(deferred);
          throw error;
        }
      }
      async setGeolocation(options) {
        return await this.#emulationManager.setGeolocation(options);
      }
      target() {
        return this.#primaryTarget;
      }
      browser() {
        return this.#primaryTarget.browser();
      }
      browserContext() {
        return this.#primaryTarget.browserContext();
      }
      #onTargetCrashed() {
        this.emit("error", new Error("Page crashed!"));
      }
      #onLogEntryAdded(event) {
        const { level, text, args: args2, source, url, lineNumber, stackTrace } = event.entry;
        if (args2) {
          args2.map((arg) => {
            void (0, JSHandle_js_1.releaseObject)(this.#primaryTargetClient, arg);
          });
        }
        if (source !== "worker") {
          this.emit("console", new ConsoleMessage_js_1.ConsoleMessage(convertConsoleMessageLevel(level), text, [], [{ url, lineNumber }], void 0, stackTrace, this.#primaryTarget._targetId));
        }
      }
      mainFrame() {
        return this.#frameManager.mainFrame();
      }
      get keyboard() {
        return this.#keyboard;
      }
      get touchscreen() {
        return this.#touchscreen;
      }
      get coverage() {
        return this.#coverage;
      }
      get tracing() {
        return this.#tracing;
      }
      frames() {
        return this.#frameManager.frames();
      }
      workers() {
        return Array.from(this.#workers.values());
      }
      async setRequestInterception(value) {
        return await this.#frameManager.networkManager.setRequestInterception(value);
      }
      async setBypassServiceWorker(bypass) {
        this.#serviceWorkerBypassed = bypass;
        return await this.#primaryTargetClient.send("Network.setBypassServiceWorker", { bypass });
      }
      async setDragInterception(enabled) {
        this.#userDragInterceptionEnabled = enabled;
        return await this.#primaryTargetClient.send("Input.setInterceptDrags", {
          enabled
        });
      }
      async setOfflineMode(enabled) {
        return await this.#frameManager.networkManager.setOfflineMode(enabled);
      }
      async emulateNetworkConditions(networkConditions) {
        return await this.#frameManager.networkManager.emulateNetworkConditions(networkConditions);
      }
      async emulateFocusedPage(enabled) {
        return await this.#emulationManager.emulateFocus(enabled);
      }
      setDefaultNavigationTimeout(timeout) {
        this._timeoutSettings.setDefaultNavigationTimeout(timeout);
      }
      setDefaultTimeout(timeout) {
        this._timeoutSettings.setDefaultTimeout(timeout);
      }
      getDefaultTimeout() {
        return this._timeoutSettings.timeout();
      }
      getDefaultNavigationTimeout() {
        return this._timeoutSettings.navigationTimeout();
      }
      async queryObjects(prototypeHandle) {
        (0, assert_js_1.assert)(!prototypeHandle.disposed, "Prototype JSHandle is disposed!");
        (0, assert_js_1.assert)(prototypeHandle.id, "Prototype JSHandle must not be referencing primitive value");
        const response = await this.mainFrame().client.send("Runtime.queryObjects", {
          prototypeObjectId: prototypeHandle.id
        });
        return this.mainFrame().mainRealm().createCdpHandle(response.objects);
      }
      async cookies(...urls) {
        const originalCookies = (await this.#primaryTargetClient.send("Network.getCookies", {
          urls: urls.length ? urls : [this.url()]
        })).cookies;
        const unsupportedCookieAttributes = ["sourcePort"];
        const filterUnsupportedAttributes = (cookie) => {
          for (const attr of unsupportedCookieAttributes) {
            delete cookie[attr];
          }
          return cookie;
        };
        return originalCookies.map(filterUnsupportedAttributes).map((cookie) => {
          return {
            ...cookie,
            // TODO: a breaking change is needed in Puppeteer types to support other
            // partition keys.
            partitionKey: cookie.partitionKey ? cookie.partitionKey.topLevelSite : void 0,
            // TODO: remove sameParty as it is removed from Chrome.
            sameParty: false
          };
        });
      }
      async deleteCookie(...cookies) {
        const pageURL = this.url();
        for (const cookie of cookies) {
          const item = {
            ...cookie,
            partitionKey: convertCookiesPartitionKeyFromPuppeteerToCdp(cookie.partitionKey)
          };
          if (!cookie.url && pageURL.startsWith("http")) {
            item.url = pageURL;
          }
          await this.#primaryTargetClient.send("Network.deleteCookies", item);
          if (pageURL.startsWith("http") && !item.partitionKey) {
            const url = new URL(pageURL);
            await this.#primaryTargetClient.send("Network.deleteCookies", {
              ...item,
              partitionKey: {
                topLevelSite: url.origin.replace(`:${url.port}`, ""),
                hasCrossSiteAncestor: false
              }
            });
          }
        }
      }
      async setCookie(...cookies) {
        const pageURL = this.url();
        const startsWithHTTP = pageURL.startsWith("http");
        const items = cookies.map((cookie) => {
          const item = Object.assign({}, cookie);
          if (!item.url && startsWithHTTP) {
            item.url = pageURL;
          }
          (0, assert_js_1.assert)(item.url !== "about:blank", `Blank page can not have cookie "${item.name}"`);
          (0, assert_js_1.assert)(!String.prototype.startsWith.call(item.url || "", "data:"), `Data URL page can not have cookie "${item.name}"`);
          return item;
        });
        await this.deleteCookie(...items);
        if (items.length) {
          await this.#primaryTargetClient.send("Network.setCookies", {
            cookies: items.map((cookieParam) => {
              return {
                ...cookieParam,
                partitionKey: convertCookiesPartitionKeyFromPuppeteerToCdp(cookieParam.partitionKey),
                sameSite: convertSameSiteFromPuppeteerToCdp(cookieParam.sameSite)
              };
            })
          });
        }
      }
      async exposeFunction(name, pptrFunction) {
        if (this.#bindings.has(name)) {
          throw new Error(`Failed to add page binding with name ${name}: window['${name}'] already exists!`);
        }
        const source = (0, utils_js_1.pageBindingInitString)("exposedFun", name);
        let binding;
        switch (typeof pptrFunction) {
          case "function":
            binding = new Binding_js_1.Binding(name, pptrFunction, source);
            break;
          default:
            binding = new Binding_js_1.Binding(name, pptrFunction.default, source);
            break;
        }
        this.#bindings.set(name, binding);
        const [{ identifier }] = await Promise.all([
          this.#frameManager.evaluateOnNewDocument(source),
          this.#frameManager.addExposedFunctionBinding(binding)
        ]);
        this.#exposedFunctions.set(name, identifier);
      }
      async removeExposedFunction(name) {
        const exposedFunctionId = this.#exposedFunctions.get(name);
        if (!exposedFunctionId) {
          throw new Error(`Function with name "${name}" does not exist`);
        }
        const binding = this.#bindings.get(name);
        this.#exposedFunctions.delete(name);
        this.#bindings.delete(name);
        await Promise.all([
          this.#frameManager.removeScriptToEvaluateOnNewDocument(exposedFunctionId),
          this.#frameManager.removeExposedFunctionBinding(binding)
        ]);
      }
      async authenticate(credentials) {
        return await this.#frameManager.networkManager.authenticate(credentials);
      }
      async setExtraHTTPHeaders(headers) {
        return await this.#frameManager.networkManager.setExtraHTTPHeaders(headers);
      }
      async setUserAgent(userAgentOrOptions, userAgentMetadata) {
        if (typeof userAgentOrOptions === "string") {
          return await this.#frameManager.networkManager.setUserAgent(userAgentOrOptions, userAgentMetadata);
        } else {
          const userAgent = userAgentOrOptions.userAgent ?? await this.browser().userAgent();
          return await this.#frameManager.networkManager.setUserAgent(userAgent, userAgentOrOptions.userAgentMetadata, userAgentOrOptions.platform);
        }
      }
      async metrics() {
        const response = await this.#primaryTargetClient.send("Performance.getMetrics");
        return this.#buildMetricsObject(response.metrics);
      }
      async captureHeapSnapshot(options) {
        const { createWriteStream } = environment_js_1.environment.value.fs;
        const stream = createWriteStream(options.path);
        const streamPromise = new Promise((resolve5, reject) => {
          stream.on("error", reject);
          stream.on("finish", resolve5);
        });
        const client2 = this.#primaryTargetClient;
        await client2.send("HeapProfiler.enable");
        await client2.send("HeapProfiler.collectGarbage");
        const handler = (event) => {
          stream.write(event.chunk);
        };
        client2.on("HeapProfiler.addHeapSnapshotChunk", handler);
        try {
          await client2.send("HeapProfiler.takeHeapSnapshot", {
            reportProgress: false
          });
        } finally {
          client2.off("HeapProfiler.addHeapSnapshotChunk", handler);
          await client2.send("HeapProfiler.disable");
        }
        stream.end();
        await streamPromise;
      }
      #emitMetrics(event) {
        this.emit("metrics", {
          title: event.title,
          metrics: this.#buildMetricsObject(event.metrics)
        });
      }
      #buildMetricsObject(metrics) {
        const result = {};
        for (const metric of metrics || []) {
          if (supportedMetrics.has(metric.name)) {
            result[metric.name] = metric.value;
          }
        }
        return result;
      }
      #handleException(exception) {
        this.emit("pageerror", (0, utils_js_1.createClientError)(exception.exceptionDetails));
      }
      #onConsoleAPI(world, event) {
        const values = event.args.map((arg) => {
          return world.createCdpHandle(arg);
        });
        if (!this.listenerCount(
          "console"
          /* PageEvent.Console */
        )) {
          values.forEach((arg) => {
            return arg.dispose();
          });
          return;
        }
        const textTokens = [];
        for (const arg of values) {
          textTokens.push((0, utils_js_1.valueFromJSHandle)(arg));
        }
        const stackTraceLocations = [];
        if (event.stackTrace) {
          for (const callFrame of event.stackTrace.callFrames) {
            stackTraceLocations.push({
              url: callFrame.url,
              lineNumber: callFrame.lineNumber,
              columnNumber: callFrame.columnNumber
            });
          }
        }
        let targetId;
        if (world.environment.client instanceof CdpSession_js_1.CdpCDPSession) {
          targetId = world.environment.client.target()._targetId;
        }
        const message = new ConsoleMessage_js_1.ConsoleMessage(convertConsoleMessageLevel(event.type), textTokens.join(" "), values, stackTraceLocations, void 0, event.stackTrace, targetId);
        this.emit("console", message);
      }
      async #onBindingCalled(world, event) {
        let payload;
        try {
          payload = JSON.parse(event.payload);
        } catch {
          return;
        }
        const { type, name, seq, args: args2, isTrivial } = payload;
        if (type !== "exposedFun") {
          return;
        }
        const context = world.context;
        if (!context) {
          return;
        }
        const binding = this.#bindings.get(name);
        await binding?.run(context, seq, args2, isTrivial);
      }
      #onDialog(event) {
        const type = (0, util_js_1.validateDialogType)(event.type);
        const dialog = new Dialog_js_1.CdpDialog(this.#primaryTargetClient, type, event.message, event.defaultPrompt);
        this.emit("dialog", dialog);
      }
      async reload(options) {
        const [result] = await Promise.all([
          this.waitForNavigation({
            ...options,
            ignoreSameDocumentNavigation: true
          }),
          this.#primaryTargetClient.send("Page.reload", {
            ignoreCache: options?.ignoreCache ?? false
          })
        ]);
        return result;
      }
      async createCDPSession() {
        return await this.target().createCDPSession();
      }
      async goBack(options = {}) {
        return await this.#go(-1, options);
      }
      async goForward(options = {}) {
        return await this.#go(1, options);
      }
      async #go(delta, options) {
        const history = await this.#primaryTargetClient.send("Page.getNavigationHistory");
        const entry = history.entries[history.currentIndex + delta];
        if (!entry) {
          throw new Error("History entry to navigate to not found.");
        }
        const result = await Promise.all([
          this.waitForNavigation(options),
          this.#primaryTargetClient.send("Page.navigateToHistoryEntry", {
            entryId: entry.id
          })
        ]);
        return result[0];
      }
      async bringToFront() {
        await this.#primaryTargetClient.send("Page.bringToFront");
      }
      async setJavaScriptEnabled(enabled) {
        return await this.#emulationManager.setJavaScriptEnabled(enabled);
      }
      async setBypassCSP(enabled) {
        await this.#primaryTargetClient.send("Page.setBypassCSP", { enabled });
      }
      async emulateMediaType(type) {
        return await this.#emulationManager.emulateMediaType(type);
      }
      async emulateCPUThrottling(factor) {
        return await this.#emulationManager.emulateCPUThrottling(factor);
      }
      async emulateMediaFeatures(features) {
        return await this.#emulationManager.emulateMediaFeatures(features);
      }
      async emulateTimezone(timezoneId) {
        return await this.#emulationManager.emulateTimezone(timezoneId);
      }
      async emulateIdleState(overrides) {
        return await this.#emulationManager.emulateIdleState(overrides);
      }
      async emulateVisionDeficiency(type) {
        return await this.#emulationManager.emulateVisionDeficiency(type);
      }
      async setViewport(viewport) {
        const needsReload = await this.#emulationManager.emulateViewport(viewport);
        this.#viewport = viewport;
        if (needsReload) {
          await this.reload();
        }
      }
      viewport() {
        return this.#viewport;
      }
      async evaluateOnNewDocument(pageFunction, ...args2) {
        const source = (0, util_js_1.evaluationString)(pageFunction, ...args2);
        return await this.#frameManager.evaluateOnNewDocument(source);
      }
      async removeScriptToEvaluateOnNewDocument(identifier) {
        return await this.#frameManager.removeScriptToEvaluateOnNewDocument(identifier);
      }
      async setCacheEnabled(enabled = true) {
        await this.#frameManager.networkManager.setCacheEnabled(enabled);
      }
      async _screenshot(options) {
        const env_2 = { stack: [], error: void 0, hasError: false };
        try {
          const { fromSurface, omitBackground, optimizeForSpeed, quality, clip: userClip, type, captureBeyondViewport } = options;
          const stack = __addDisposableResource2(env_2, new disposable_js_1.AsyncDisposableStack(), true);
          if (omitBackground && (type === "png" || type === "webp")) {
            await this.#emulationManager.setTransparentBackgroundColor();
            stack.defer(async () => {
              await this.#emulationManager.resetDefaultBackgroundColor().catch(util_js_1.debugError);
            });
          }
          let clip = userClip;
          if (clip && !captureBeyondViewport) {
            const viewport = await this.mainFrame().isolatedRealm().evaluate(() => {
              const { height, pageLeft: x, pageTop: y, width } = window.visualViewport;
              return { x, y, height, width };
            });
            clip = getIntersectionRect(clip, viewport);
          }
          const { data } = await this.#primaryTargetClient.send("Page.captureScreenshot", {
            format: type,
            optimizeForSpeed,
            fromSurface,
            ...quality !== void 0 ? { quality: Math.round(quality) } : {},
            ...clip ? { clip: { ...clip, scale: clip.scale ?? 1 } } : {},
            captureBeyondViewport
          });
          return data;
        } catch (e_2) {
          env_2.error = e_2;
          env_2.hasError = true;
        } finally {
          const result_1 = __disposeResources2(env_2);
          if (result_1)
            await result_1;
        }
      }
      async createPDFStream(options = {}) {
        const { timeout: ms = this._timeoutSettings.timeout() } = options;
        const { landscape, displayHeaderFooter, headerTemplate, footerTemplate, printBackground, scale, width: paperWidth, height: paperHeight, margin, pageRanges, preferCSSPageSize, omitBackground, tagged: generateTaggedPDF, outline: generateDocumentOutline, waitForFonts } = (0, util_js_1.parsePDFOptions)(options);
        if (omitBackground) {
          await this.#emulationManager.setTransparentBackgroundColor();
        }
        if (waitForFonts) {
          await (0, rxjs_js_1.firstValueFrom)((0, rxjs_js_1.from)(this.mainFrame().isolatedRealm().evaluate(() => {
            return document.fonts.ready;
          })).pipe((0, rxjs_js_1.raceWith)((0, util_js_1.timeout)(ms))));
        }
        const printCommandPromise = this.#primaryTargetClient.send("Page.printToPDF", {
          transferMode: "ReturnAsStream",
          landscape,
          displayHeaderFooter,
          headerTemplate,
          footerTemplate,
          printBackground,
          scale,
          paperWidth,
          paperHeight,
          marginTop: margin.top,
          marginBottom: margin.bottom,
          marginLeft: margin.left,
          marginRight: margin.right,
          pageRanges,
          preferCSSPageSize,
          generateTaggedPDF,
          generateDocumentOutline
        });
        const result = await (0, rxjs_js_1.firstValueFrom)((0, rxjs_js_1.from)(printCommandPromise).pipe((0, rxjs_js_1.raceWith)((0, util_js_1.timeout)(ms))));
        if (omitBackground) {
          await this.#emulationManager.resetDefaultBackgroundColor();
        }
        (0, assert_js_1.assert)(result.stream, "`stream` is missing from `Page.printToPDF");
        return await (0, util_js_1.getReadableFromProtocolStream)(this.#primaryTargetClient, result.stream);
      }
      async pdf(options = {}) {
        const { path: path2 = void 0 } = options;
        const readable = await this.createPDFStream(options);
        const typedArray = await (0, util_js_1.getReadableAsTypedArray)(readable, path2);
        (0, assert_js_1.assert)(typedArray, "Could not create typed array");
        return typedArray;
      }
      async close(options = { runBeforeUnload: void 0 }) {
        const env_3 = { stack: [], error: void 0, hasError: false };
        try {
          const _guard = __addDisposableResource2(env_3, await this.browserContext().waitForScreenshotOperations(), false);
          const connection = this.#primaryTargetClient.connection();
          (0, assert_js_1.assert)(connection, "Connection closed. Most likely the page has been closed.");
          const runBeforeUnload = !!options.runBeforeUnload;
          if (runBeforeUnload) {
            await this.#primaryTargetClient.send("Page.close");
          } else {
            await connection.send("Target.closeTarget", {
              targetId: this.#primaryTarget._targetId
            });
            await this.#tabTarget._isClosedDeferred.valueOrThrow();
          }
        } catch (e_3) {
          env_3.error = e_3;
          env_3.hasError = true;
        } finally {
          __disposeResources2(env_3);
        }
      }
      isClosed() {
        return this.#closed;
      }
      get mouse() {
        return this.#mouse;
      }
      /**
       * This method is typically coupled with an action that triggers a device
       * request from an api such as WebBluetooth.
       *
       * :::caution
       *
       * This must be called before the device request is made. It will not return a
       * currently active device prompt.
       *
       * :::
       *
       * @example
       *
       * ```ts
       * const [devicePrompt] = Promise.all([
       *   page.waitForDevicePrompt(),
       *   page.click('#connect-bluetooth'),
       * ]);
       * await devicePrompt.select(
       *   await devicePrompt.waitForDevice(({name}) => name.includes('My Device')),
       * );
       * ```
       */
      async waitForDevicePrompt(options = {}) {
        return await this.mainFrame().waitForDevicePrompt(options);
      }
      get bluetooth() {
        return this.#cdpBluetoothEmulation;
      }
    };
    exports2.CdpPage = CdpPage;
    var supportedMetrics = /* @__PURE__ */ new Set([
      "Timestamp",
      "Documents",
      "Frames",
      "JSEventListeners",
      "Nodes",
      "LayoutCount",
      "RecalcStyleCount",
      "LayoutDuration",
      "RecalcStyleDuration",
      "ScriptDuration",
      "TaskDuration",
      "JSHeapUsedSize",
      "JSHeapTotalSize"
    ]);
    function getIntersectionRect(clip, viewport) {
      const x = Math.max(clip.x, viewport.x);
      const y = Math.max(clip.y, viewport.y);
      return {
        x,
        y,
        width: Math.max(Math.min(clip.x + clip.width, viewport.x + viewport.width) - x, 0),
        height: Math.max(Math.min(clip.y + clip.height, viewport.y + viewport.height) - y, 0)
      };
    }
    function convertCookiesPartitionKeyFromPuppeteerToCdp(partitionKey) {
      if (partitionKey === void 0) {
        return void 0;
      }
      if (typeof partitionKey === "string") {
        return {
          topLevelSite: partitionKey,
          hasCrossSiteAncestor: false
        };
      }
      return {
        topLevelSite: partitionKey.sourceOrigin,
        hasCrossSiteAncestor: partitionKey.hasCrossSiteAncestor ?? false
      };
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/BrowserContext.js
var require_BrowserContext2 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/BrowserContext.js"(exports2) {
    "use strict";
    init_prefix();
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CdpBrowserContext = void 0;
    var Browser_js_1 = require_Browser();
    var BrowserContext_js_1 = require_BrowserContext();
    var assert_js_1 = require_assert();
    var Page_js_1 = require_Page2();
    var CdpBrowserContext = class extends BrowserContext_js_1.BrowserContext {
      #connection;
      #browser;
      #id;
      constructor(connection, browser, contextId) {
        super();
        this.#connection = connection;
        this.#browser = browser;
        this.#id = contextId;
      }
      get id() {
        return this.#id;
      }
      targets() {
        return this.#browser.targets().filter((target) => {
          return target.browserContext() === this;
        });
      }
      async pages(includeAll = false) {
        const pages = await Promise.all(this.targets().filter((target) => {
          return target.type() === "page" || (target.type() === "other" || includeAll) && this.#browser._getIsPageTargetCallback()?.(target);
        }).map((target) => {
          return target.page();
        }));
        return pages.filter((page2) => {
          return !!page2;
        });
      }
      async overridePermissions(origin, permissions) {
        const protocolPermissions = permissions.map((permission) => {
          const protocolPermission = Browser_js_1.WEB_PERMISSION_TO_PROTOCOL_PERMISSION.get(permission);
          if (!protocolPermission) {
            throw new Error("Unknown permission: " + permission);
          }
          return protocolPermission;
        });
        await this.#connection.send("Browser.grantPermissions", {
          origin,
          browserContextId: this.#id || void 0,
          permissions: protocolPermissions
        });
      }
      async setPermission(origin, ...permissions) {
        await Promise.all(permissions.map(async (permission) => {
          const protocolPermission = {
            name: permission.permission.name,
            userVisibleOnly: permission.permission.userVisibleOnly,
            sysex: permission.permission.sysex,
            allowWithoutSanitization: permission.permission.allowWithoutSanitization,
            panTiltZoom: permission.permission.panTiltZoom
          };
          await this.#connection.send("Browser.setPermission", {
            origin: origin === "*" ? void 0 : origin,
            browserContextId: this.#id || void 0,
            permission: protocolPermission,
            setting: permission.state
          });
        }));
      }
      async clearPermissionOverrides() {
        await this.#connection.send("Browser.resetPermissions", {
          browserContextId: this.#id || void 0
        });
      }
      async newPage(options) {
        const env_1 = { stack: [], error: void 0, hasError: false };
        try {
          const _guard = __addDisposableResource2(env_1, await this.waitForScreenshotOperations(), false);
          return await this.#browser._createPageInContext(this.#id, options);
        } catch (e_1) {
          env_1.error = e_1;
          env_1.hasError = true;
        } finally {
          __disposeResources2(env_1);
        }
      }
      browser() {
        return this.#browser;
      }
      async close() {
        (0, assert_js_1.assert)(this.#id, "Default BrowserContext cannot be closed!");
        await this.#browser._disposeContext(this.#id);
      }
      async cookies() {
        const { cookies } = await this.#connection.send("Storage.getCookies", {
          browserContextId: this.#id
        });
        return cookies.map((cookie) => {
          return {
            ...cookie,
            partitionKey: cookie.partitionKey ? {
              sourceOrigin: cookie.partitionKey.topLevelSite,
              hasCrossSiteAncestor: cookie.partitionKey.hasCrossSiteAncestor
            } : void 0,
            // TODO: remove sameParty as it is removed from Chrome.
            sameParty: false
          };
        });
      }
      async setCookie(...cookies) {
        return await this.#connection.send("Storage.setCookies", {
          browserContextId: this.#id,
          cookies: cookies.map((cookie) => {
            return {
              ...cookie,
              partitionKey: (0, Page_js_1.convertCookiesPartitionKeyFromPuppeteerToCdp)(cookie.partitionKey),
              sameSite: (0, Page_js_1.convertSameSiteFromPuppeteerToCdp)(cookie.sameSite)
            };
          })
        });
      }
      async setDownloadBehavior(downloadBehavior) {
        await this.#connection.send("Browser.setDownloadBehavior", {
          behavior: downloadBehavior.policy,
          downloadPath: downloadBehavior.downloadPath,
          browserContextId: this.#id
        });
      }
    };
    exports2.CdpBrowserContext = CdpBrowserContext;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Target.js
var require_Target2 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Target.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OtherTarget = exports2.WorkerTarget = exports2.DevToolsTarget = exports2.PageTarget = exports2.CdpTarget = exports2.InitializationStatus = void 0;
    var Target_js_1 = require_Target();
    var util_js_1 = require_util();
    var Deferred_js_1 = require_Deferred();
    var Page_js_1 = require_Page2();
    var WebWorker_js_1 = require_WebWorker2();
    var InitializationStatus;
    (function(InitializationStatus2) {
      InitializationStatus2["SUCCESS"] = "success";
      InitializationStatus2["ABORTED"] = "aborted";
    })(InitializationStatus || (exports2.InitializationStatus = InitializationStatus = {}));
    var CdpTarget = class extends Target_js_1.Target {
      #browserContext;
      #session;
      #targetInfo;
      #targetManager;
      #sessionFactory;
      #childTargets = /* @__PURE__ */ new Set();
      _initializedDeferred = Deferred_js_1.Deferred.create();
      _isClosedDeferred = Deferred_js_1.Deferred.create();
      _targetId;
      /**
       * To initialize the target for use, call initialize.
       *
       * @internal
       */
      constructor(targetInfo, session, browserContext, targetManager, sessionFactory) {
        super();
        this.#session = session;
        this.#targetManager = targetManager;
        this.#targetInfo = targetInfo;
        this.#browserContext = browserContext;
        this._targetId = targetInfo.targetId;
        this.#sessionFactory = sessionFactory;
        if (this.#session) {
          this.#session.setTarget(this);
        }
      }
      async asPage() {
        const session = this._session();
        if (!session) {
          return await this.createCDPSession().then((client2) => {
            return Page_js_1.CdpPage._create(client2, this, null);
          });
        }
        return await Page_js_1.CdpPage._create(session, this, null);
      }
      _subtype() {
        return this.#targetInfo.subtype;
      }
      _session() {
        return this.#session;
      }
      _addChildTarget(target) {
        this.#childTargets.add(target);
      }
      _removeChildTarget(target) {
        this.#childTargets.delete(target);
      }
      _childTargets() {
        return this.#childTargets;
      }
      _sessionFactory() {
        if (!this.#sessionFactory) {
          throw new Error("sessionFactory is not initialized");
        }
        return this.#sessionFactory;
      }
      createCDPSession() {
        if (!this.#sessionFactory) {
          throw new Error("sessionFactory is not initialized");
        }
        return this.#sessionFactory(false).then((session) => {
          session.setTarget(this);
          return session;
        });
      }
      url() {
        return this.#targetInfo.url;
      }
      type() {
        const type = this.#targetInfo.type;
        switch (type) {
          case "page":
            return Target_js_1.TargetType.PAGE;
          case "background_page":
            return Target_js_1.TargetType.BACKGROUND_PAGE;
          case "service_worker":
            return Target_js_1.TargetType.SERVICE_WORKER;
          case "shared_worker":
            return Target_js_1.TargetType.SHARED_WORKER;
          case "browser":
            return Target_js_1.TargetType.BROWSER;
          case "webview":
            return Target_js_1.TargetType.WEBVIEW;
          case "tab":
            return Target_js_1.TargetType.TAB;
          default:
            return Target_js_1.TargetType.OTHER;
        }
      }
      _targetManager() {
        if (!this.#targetManager) {
          throw new Error("targetManager is not initialized");
        }
        return this.#targetManager;
      }
      _getTargetInfo() {
        return this.#targetInfo;
      }
      browser() {
        if (!this.#browserContext) {
          throw new Error("browserContext is not initialized");
        }
        return this.#browserContext.browser();
      }
      browserContext() {
        if (!this.#browserContext) {
          throw new Error("browserContext is not initialized");
        }
        return this.#browserContext;
      }
      opener() {
        const { openerId } = this.#targetInfo;
        if (!openerId) {
          return;
        }
        return this.browser().targets().find((target) => {
          return target._targetId === openerId;
        });
      }
      _targetInfoChanged(targetInfo) {
        this.#targetInfo = targetInfo;
        this._checkIfInitialized();
      }
      _initialize() {
        this._initializedDeferred.resolve(InitializationStatus.SUCCESS);
      }
      _isTargetExposed() {
        return this.type() !== Target_js_1.TargetType.TAB && !this._subtype();
      }
      _checkIfInitialized() {
        if (!this._initializedDeferred.resolved()) {
          this._initializedDeferred.resolve(InitializationStatus.SUCCESS);
        }
      }
    };
    exports2.CdpTarget = CdpTarget;
    var PageTarget = class _PageTarget extends CdpTarget {
      #defaultViewport;
      pagePromise;
      constructor(targetInfo, session, browserContext, targetManager, sessionFactory, defaultViewport) {
        super(targetInfo, session, browserContext, targetManager, sessionFactory);
        this.#defaultViewport = defaultViewport ?? void 0;
      }
      _initialize() {
        this._initializedDeferred.valueOrThrow().then(async (result) => {
          if (result === InitializationStatus.ABORTED) {
            return;
          }
          const opener = this.opener();
          if (!(opener instanceof _PageTarget)) {
            return;
          }
          if (!opener || !opener.pagePromise || this.type() !== "page") {
            return true;
          }
          const openerPage = await opener.pagePromise;
          if (!openerPage.listenerCount(
            "popup"
            /* PageEvent.Popup */
          )) {
            return true;
          }
          const popupPage = await this.page();
          openerPage.emit("popup", popupPage);
          return true;
        }).catch(util_js_1.debugError);
        this._checkIfInitialized();
      }
      async page() {
        if (!this.pagePromise) {
          const session = this._session();
          this.pagePromise = (session ? Promise.resolve(session) : this._sessionFactory()(
            /* isAutoAttachEmulated=*/
            false
          )).then((client2) => {
            return Page_js_1.CdpPage._create(client2, this, this.#defaultViewport ?? null);
          });
        }
        return await this.pagePromise ?? null;
      }
      _checkIfInitialized() {
        if (this._initializedDeferred.resolved()) {
          return;
        }
        if (this._getTargetInfo().url !== "") {
          this._initializedDeferred.resolve(InitializationStatus.SUCCESS);
        }
      }
    };
    exports2.PageTarget = PageTarget;
    var DevToolsTarget = class extends PageTarget {
    };
    exports2.DevToolsTarget = DevToolsTarget;
    var WorkerTarget = class extends CdpTarget {
      #workerPromise;
      async worker() {
        if (!this.#workerPromise) {
          const session = this._session();
          this.#workerPromise = (session ? Promise.resolve(session) : this._sessionFactory()(
            /* isAutoAttachEmulated=*/
            false
          )).then((client2) => {
            return new WebWorker_js_1.CdpWebWorker(
              client2,
              this._getTargetInfo().url,
              this._targetId,
              this.type(),
              () => {
              },
              () => {
              },
              void 0
              /* networkManager */
            );
          });
        }
        return await this.#workerPromise;
      }
    };
    exports2.WorkerTarget = WorkerTarget;
    var OtherTarget = class extends CdpTarget {
    };
    exports2.OtherTarget = OtherTarget;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/TargetManager.js
var require_TargetManager = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/TargetManager.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.TargetManager = void 0;
    var CDPSession_js_1 = require_CDPSession();
    var EventEmitter_js_1 = require_EventEmitter();
    var util_js_1 = require_util();
    var assert_js_1 = require_assert();
    var Deferred_js_1 = require_Deferred();
    var CdpSession_js_1 = require_CdpSession();
    var Target_js_1 = require_Target2();
    function isPageTargetBecomingPrimary(target, newTargetInfo) {
      return Boolean(target._subtype()) && !newTargetInfo.subtype;
    }
    var TargetManager = class extends EventEmitter_js_1.EventEmitter {
      #connection;
      /**
       * Keeps track of the following events: 'Target.targetCreated',
       * 'Target.targetDestroyed', 'Target.targetInfoChanged'.
       *
       * A target becomes discovered when 'Target.targetCreated' is received.
       * A target is removed from this map once 'Target.targetDestroyed' is
       * received.
       *
       * `targetFilterCallback` has no effect on this map.
       */
      #discoveredTargetsByTargetId = /* @__PURE__ */ new Map();
      /**
       * A target is added to this map once TargetManager has created
       * a Target and attached at least once to it.
       */
      #attachedTargetsByTargetId = /* @__PURE__ */ new Map();
      /**
       * Tracks which sessions attach to which target.
       */
      #attachedTargetsBySessionId = /* @__PURE__ */ new Map();
      /**
       * If a target was filtered out by `targetFilterCallback`, we still receive
       * events about it from CDP, but we don't forward them to the rest of Puppeteer.
       */
      #ignoredTargets = /* @__PURE__ */ new Set();
      #targetFilterCallback;
      #targetFactory;
      #attachedToTargetListenersBySession = /* @__PURE__ */ new WeakMap();
      #detachedFromTargetListenersBySession = /* @__PURE__ */ new WeakMap();
      #initializeDeferred = Deferred_js_1.Deferred.create();
      #waitForInitiallyDiscoveredTargets = true;
      #discoveryFilter = [{}];
      // IDs of tab targets detected while running the initial Target.setAutoAttach
      // request. These are the targets whose initialization we want to await for
      // before resolving puppeteer.connect() or launch() to avoid flakiness.
      // Whenever a sub-target whose parent is a tab target is attached, we remove
      // the tab target from this list. Once the list is empty, we resolve the
      // initializeDeferred.
      #targetsIdsForInit = /* @__PURE__ */ new Set();
      // This is false until the connection-level Target.setAutoAttach request is
      // done. It indicates whethere we are running the initial auto-attach step or
      // if we are handling targets after that.
      #initialAttachDone = false;
      constructor(connection, targetFactory, targetFilterCallback, waitForInitiallyDiscoveredTargets = true) {
        super();
        this.#connection = connection;
        this.#targetFilterCallback = targetFilterCallback;
        this.#targetFactory = targetFactory;
        this.#waitForInitiallyDiscoveredTargets = waitForInitiallyDiscoveredTargets;
        this.#connection.on("Target.targetCreated", this.#onTargetCreated);
        this.#connection.on("Target.targetDestroyed", this.#onTargetDestroyed);
        this.#connection.on("Target.targetInfoChanged", this.#onTargetInfoChanged);
        this.#connection.on(CDPSession_js_1.CDPSessionEvent.SessionDetached, this.#onSessionDetached);
        this.#setupAttachmentListeners(this.#connection);
      }
      async initialize() {
        await this.#connection.send("Target.setDiscoverTargets", {
          discover: true,
          filter: this.#discoveryFilter
        });
        await this.#connection.send("Target.setAutoAttach", {
          waitForDebuggerOnStart: true,
          flatten: true,
          autoAttach: true,
          filter: [
            {
              type: "page",
              exclude: true
            },
            ...this.#discoveryFilter
          ]
        });
        this.#initialAttachDone = true;
        this.#finishInitializationIfReady();
        await this.#initializeDeferred.valueOrThrow();
      }
      getChildTargets(target) {
        return target._childTargets();
      }
      dispose() {
        this.#connection.off("Target.targetCreated", this.#onTargetCreated);
        this.#connection.off("Target.targetDestroyed", this.#onTargetDestroyed);
        this.#connection.off("Target.targetInfoChanged", this.#onTargetInfoChanged);
        this.#connection.off(CDPSession_js_1.CDPSessionEvent.SessionDetached, this.#onSessionDetached);
        this.#removeAttachmentListeners(this.#connection);
      }
      getAvailableTargets() {
        return this.#attachedTargetsByTargetId;
      }
      #setupAttachmentListeners(session) {
        const listener = (event) => {
          void this.#onAttachedToTarget(session, event);
        };
        (0, assert_js_1.assert)(!this.#attachedToTargetListenersBySession.has(session));
        this.#attachedToTargetListenersBySession.set(session, listener);
        session.on("Target.attachedToTarget", listener);
        const detachedListener = (event) => {
          return this.#onDetachedFromTarget(session, event);
        };
        (0, assert_js_1.assert)(!this.#detachedFromTargetListenersBySession.has(session));
        this.#detachedFromTargetListenersBySession.set(session, detachedListener);
        session.on("Target.detachedFromTarget", detachedListener);
      }
      #removeAttachmentListeners(session) {
        const listener = this.#attachedToTargetListenersBySession.get(session);
        if (listener) {
          session.off("Target.attachedToTarget", listener);
          this.#attachedToTargetListenersBySession.delete(session);
        }
        const detachedListener = this.#detachedFromTargetListenersBySession.get(session);
        if (detachedListener) {
          session.off("Target.detachedFromTarget", detachedListener);
          this.#detachedFromTargetListenersBySession.delete(session);
        }
      }
      #silentDetach = async (session, parentSession) => {
        await session.send("Runtime.runIfWaitingForDebugger").catch(util_js_1.debugError);
        await parentSession.send("Target.detachFromTarget", {
          sessionId: session.id()
        }).catch(util_js_1.debugError);
      };
      #getParentTarget = (parentSession) => {
        return parentSession instanceof CdpSession_js_1.CdpCDPSession ? parentSession.target() : null;
      };
      #onSessionDetached = (session) => {
        this.#removeAttachmentListeners(session);
      };
      #onTargetCreated = async (event) => {
        this.#discoveredTargetsByTargetId.set(event.targetInfo.targetId, event.targetInfo);
        this.emit("targetDiscovered", event.targetInfo);
        if (event.targetInfo.type === "browser" && event.targetInfo.attached) {
          if (this.#attachedTargetsByTargetId.has(event.targetInfo.targetId)) {
            return;
          }
          const target = this.#targetFactory(event.targetInfo, void 0);
          target._initialize();
          this.#attachedTargetsByTargetId.set(event.targetInfo.targetId, target);
        }
      };
      #onTargetDestroyed = (event) => {
        const targetInfo = this.#discoveredTargetsByTargetId.get(event.targetId);
        this.#discoveredTargetsByTargetId.delete(event.targetId);
        this.#finishInitializationIfReady(event.targetId);
        if (targetInfo?.type === "service_worker") {
          const target = this.#attachedTargetsByTargetId.get(event.targetId);
          if (target) {
            this.emit("targetGone", target);
            this.#attachedTargetsByTargetId.delete(event.targetId);
          }
        }
      };
      #onTargetInfoChanged = (event) => {
        this.#discoveredTargetsByTargetId.set(event.targetInfo.targetId, event.targetInfo);
        if (this.#ignoredTargets.has(event.targetInfo.targetId) || !event.targetInfo.attached) {
          return;
        }
        const target = this.#attachedTargetsByTargetId.get(event.targetInfo.targetId);
        if (!target) {
          return;
        }
        const previousURL = target.url();
        const wasInitialized = target._initializedDeferred.value() === Target_js_1.InitializationStatus.SUCCESS;
        if (isPageTargetBecomingPrimary(target, event.targetInfo)) {
          const session = target._session();
          (0, assert_js_1.assert)(session, "Target that is being activated is missing a CDPSession.");
          session.parentSession()?.emit(CDPSession_js_1.CDPSessionEvent.Swapped, session);
        }
        target._targetInfoChanged(event.targetInfo);
        if (wasInitialized && previousURL !== target.url()) {
          this.emit("targetChanged", {
            target,
            wasInitialized,
            previousURL
          });
        }
      };
      #onAttachedToTarget = async (parentSession, event) => {
        const targetInfo = event.targetInfo;
        const session = this.#connection._session(event.sessionId);
        if (!session) {
          throw new Error(`Session ${event.sessionId} was not created.`);
        }
        if (!this.#connection.isAutoAttached(targetInfo.targetId)) {
          return;
        }
        if (targetInfo.type === "service_worker") {
          await this.#silentDetach(session, parentSession);
          if (this.#attachedTargetsByTargetId.has(targetInfo.targetId)) {
            return;
          }
          const target2 = this.#targetFactory(targetInfo);
          target2._initialize();
          this.#attachedTargetsByTargetId.set(targetInfo.targetId, target2);
          this.emit("targetAvailable", target2);
          return;
        }
        let target = this.#attachedTargetsByTargetId.get(targetInfo.targetId);
        const isExistingTarget = target !== void 0;
        if (!target) {
          target = this.#targetFactory(targetInfo, session, parentSession instanceof CdpSession_js_1.CdpCDPSession ? parentSession : void 0);
        }
        const parentTarget = this.#getParentTarget(parentSession);
        if (this.#targetFilterCallback && !this.#targetFilterCallback(target)) {
          this.#ignoredTargets.add(targetInfo.targetId);
          if (parentTarget?.type() === "tab") {
            this.#finishInitializationIfReady(parentTarget._targetId);
          }
          await this.#silentDetach(session, parentSession);
          return;
        }
        if (this.#waitForInitiallyDiscoveredTargets && event.targetInfo.type === "tab" && !this.#initialAttachDone) {
          this.#targetsIdsForInit.add(event.targetInfo.targetId);
        }
        this.#setupAttachmentListeners(session);
        if (isExistingTarget) {
          session.setTarget(target);
          this.#attachedTargetsBySessionId.set(session.id(), target);
        } else {
          target._initialize();
          this.#attachedTargetsByTargetId.set(targetInfo.targetId, target);
          this.#attachedTargetsBySessionId.set(session.id(), target);
        }
        parentTarget?._addChildTarget(target);
        parentSession.emit(CDPSession_js_1.CDPSessionEvent.Ready, session);
        if (!isExistingTarget) {
          this.emit("targetAvailable", target);
        }
        if (parentTarget?.type() === "tab") {
          this.#finishInitializationIfReady(parentTarget._targetId);
        }
        await Promise.all([
          session.send("Target.setAutoAttach", {
            waitForDebuggerOnStart: true,
            flatten: true,
            autoAttach: true,
            filter: this.#discoveryFilter
          }),
          session.send("Runtime.runIfWaitingForDebugger")
        ]).catch(util_js_1.debugError);
      };
      #finishInitializationIfReady(targetId) {
        if (targetId !== void 0) {
          this.#targetsIdsForInit.delete(targetId);
        }
        if (!this.#initialAttachDone) {
          return;
        }
        if (this.#targetsIdsForInit.size === 0) {
          this.#initializeDeferred.resolve();
        }
      }
      #onDetachedFromTarget = (parentSession, event) => {
        const target = this.#attachedTargetsBySessionId.get(event.sessionId);
        this.#attachedTargetsBySessionId.delete(event.sessionId);
        if (!target) {
          return;
        }
        if (parentSession instanceof CdpSession_js_1.CdpCDPSession) {
          parentSession.target()._removeChildTarget(target);
        }
        this.#attachedTargetsByTargetId.delete(target._targetId);
        this.emit("targetGone", target);
      };
    };
    exports2.TargetManager = TargetManager;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Browser.js
var require_Browser2 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Browser.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CdpBrowser = void 0;
    var Browser_js_1 = require_Browser();
    var CDPSession_js_1 = require_CDPSession();
    var BrowserContext_js_1 = require_BrowserContext2();
    var Target_js_1 = require_Target2();
    var TargetManager_js_1 = require_TargetManager();
    function isDevToolsPageTarget(url) {
      return url.startsWith("devtools://devtools/bundled/devtools_app.html");
    }
    var CdpBrowser = class _CdpBrowser extends Browser_js_1.Browser {
      protocol = "cdp";
      static async _create(connection, contextIds, acceptInsecureCerts, defaultViewport, downloadBehavior, process2, closeCallback, targetFilterCallback, isPageTargetCallback, waitForInitiallyDiscoveredTargets = true, networkEnabled = true, handleDevToolsAsPage = false) {
        const browser = new _CdpBrowser(connection, contextIds, defaultViewport, process2, closeCallback, targetFilterCallback, isPageTargetCallback, waitForInitiallyDiscoveredTargets, networkEnabled, handleDevToolsAsPage);
        if (acceptInsecureCerts) {
          await connection.send("Security.setIgnoreCertificateErrors", {
            ignore: true
          });
        }
        await browser._attach(downloadBehavior);
        return browser;
      }
      #defaultViewport;
      #process;
      #connection;
      #closeCallback;
      #targetFilterCallback;
      #isPageTargetCallback;
      #defaultContext;
      #contexts = /* @__PURE__ */ new Map();
      #networkEnabled = true;
      #targetManager;
      #handleDevToolsAsPage = false;
      constructor(connection, contextIds, defaultViewport, process2, closeCallback, targetFilterCallback, isPageTargetCallback, waitForInitiallyDiscoveredTargets = true, networkEnabled = true, handleDevToolsAsPage = false) {
        super();
        this.#networkEnabled = networkEnabled;
        this.#defaultViewport = defaultViewport;
        this.#process = process2;
        this.#connection = connection;
        this.#closeCallback = closeCallback || (() => {
        });
        this.#targetFilterCallback = targetFilterCallback || (() => {
          return true;
        });
        this.#handleDevToolsAsPage = handleDevToolsAsPage;
        this.#setIsPageTargetCallback(isPageTargetCallback);
        this.#targetManager = new TargetManager_js_1.TargetManager(connection, this.#createTarget, this.#targetFilterCallback, waitForInitiallyDiscoveredTargets);
        this.#defaultContext = new BrowserContext_js_1.CdpBrowserContext(this.#connection, this);
        for (const contextId of contextIds) {
          this.#contexts.set(contextId, new BrowserContext_js_1.CdpBrowserContext(this.#connection, this, contextId));
        }
      }
      #emitDisconnected = () => {
        this.emit("disconnected", void 0);
      };
      async _attach(downloadBehavior) {
        this.#connection.on(CDPSession_js_1.CDPSessionEvent.Disconnected, this.#emitDisconnected);
        if (downloadBehavior) {
          await this.#defaultContext.setDownloadBehavior(downloadBehavior);
        }
        this.#targetManager.on("targetAvailable", this.#onAttachedToTarget);
        this.#targetManager.on("targetGone", this.#onDetachedFromTarget);
        this.#targetManager.on("targetChanged", this.#onTargetChanged);
        this.#targetManager.on("targetDiscovered", this.#onTargetDiscovered);
        await this.#targetManager.initialize();
      }
      _detach() {
        this.#connection.off(CDPSession_js_1.CDPSessionEvent.Disconnected, this.#emitDisconnected);
        this.#targetManager.off("targetAvailable", this.#onAttachedToTarget);
        this.#targetManager.off("targetGone", this.#onDetachedFromTarget);
        this.#targetManager.off("targetChanged", this.#onTargetChanged);
        this.#targetManager.off("targetDiscovered", this.#onTargetDiscovered);
      }
      process() {
        return this.#process ?? null;
      }
      _targetManager() {
        return this.#targetManager;
      }
      #setIsPageTargetCallback(isPageTargetCallback) {
        this.#isPageTargetCallback = isPageTargetCallback || ((target) => {
          return target.type() === "page" || target.type() === "background_page" || target.type() === "webview" || this.#handleDevToolsAsPage && target.type() === "other" && isDevToolsPageTarget(target.url());
        });
      }
      _getIsPageTargetCallback() {
        return this.#isPageTargetCallback;
      }
      async createBrowserContext(options = {}) {
        const { proxyServer, proxyBypassList, downloadBehavior } = options;
        const { browserContextId } = await this.#connection.send("Target.createBrowserContext", {
          proxyServer,
          proxyBypassList: proxyBypassList && proxyBypassList.join(",")
        });
        const context = new BrowserContext_js_1.CdpBrowserContext(this.#connection, this, browserContextId);
        if (downloadBehavior) {
          await context.setDownloadBehavior(downloadBehavior);
        }
        this.#contexts.set(browserContextId, context);
        return context;
      }
      browserContexts() {
        return [this.#defaultContext, ...Array.from(this.#contexts.values())];
      }
      defaultBrowserContext() {
        return this.#defaultContext;
      }
      async _disposeContext(contextId) {
        if (!contextId) {
          return;
        }
        await this.#connection.send("Target.disposeBrowserContext", {
          browserContextId: contextId
        });
        this.#contexts.delete(contextId);
      }
      #createTarget = (targetInfo, session) => {
        const { browserContextId } = targetInfo;
        const context = browserContextId && this.#contexts.has(browserContextId) ? this.#contexts.get(browserContextId) : this.#defaultContext;
        if (!context) {
          throw new Error("Missing browser context");
        }
        const createSession = (isAutoAttachEmulated) => {
          return this.#connection._createSession(targetInfo, isAutoAttachEmulated);
        };
        const otherTarget = new Target_js_1.OtherTarget(targetInfo, session, context, this.#targetManager, createSession);
        if (targetInfo.url && isDevToolsPageTarget(targetInfo.url)) {
          return new Target_js_1.DevToolsTarget(targetInfo, session, context, this.#targetManager, createSession, this.#defaultViewport ?? null);
        }
        if (this.#isPageTargetCallback(otherTarget)) {
          return new Target_js_1.PageTarget(targetInfo, session, context, this.#targetManager, createSession, this.#defaultViewport ?? null);
        }
        if (targetInfo.type === "service_worker" || targetInfo.type === "shared_worker") {
          return new Target_js_1.WorkerTarget(targetInfo, session, context, this.#targetManager, createSession);
        }
        return otherTarget;
      };
      #onAttachedToTarget = async (target) => {
        if (target._isTargetExposed() && await target._initializedDeferred.valueOrThrow() === Target_js_1.InitializationStatus.SUCCESS) {
          this.emit("targetcreated", target);
          target.browserContext().emit("targetcreated", target);
        }
      };
      #onDetachedFromTarget = async (target) => {
        target._initializedDeferred.resolve(Target_js_1.InitializationStatus.ABORTED);
        target._isClosedDeferred.resolve();
        if (target._isTargetExposed() && await target._initializedDeferred.valueOrThrow() === Target_js_1.InitializationStatus.SUCCESS) {
          this.emit("targetdestroyed", target);
          target.browserContext().emit("targetdestroyed", target);
        }
      };
      #onTargetChanged = ({ target }) => {
        this.emit("targetchanged", target);
        target.browserContext().emit("targetchanged", target);
      };
      #onTargetDiscovered = (targetInfo) => {
        this.emit("targetdiscovered", targetInfo);
      };
      wsEndpoint() {
        return this.#connection.url();
      }
      async newPage(options) {
        return await this.#defaultContext.newPage(options);
      }
      async _createPageInContext(contextId, options) {
        const hasTargets = this.targets().filter((t) => {
          return t.browserContext().id === contextId;
        }).length > 0;
        const windowBounds = options?.type === "window" ? options.windowBounds : void 0;
        const { targetId } = await this.#connection.send("Target.createTarget", {
          url: "about:blank",
          browserContextId: contextId || void 0,
          left: windowBounds?.left,
          top: windowBounds?.top,
          width: windowBounds?.width,
          height: windowBounds?.height,
          windowState: windowBounds?.windowState,
          // Works around crbug.com/454825274.
          newWindow: hasTargets && options?.type === "window" ? true : void 0,
          background: options?.background
        });
        const target = await this.waitForTarget((t) => {
          return t._targetId === targetId;
        });
        if (!target) {
          throw new Error(`Missing target for page (id = ${targetId})`);
        }
        const initialized = await target._initializedDeferred.valueOrThrow() === Target_js_1.InitializationStatus.SUCCESS;
        if (!initialized) {
          throw new Error(`Failed to create target for page (id = ${targetId})`);
        }
        const page2 = await target.page();
        if (!page2) {
          throw new Error(`Failed to create a page for context (id = ${contextId})`);
        }
        return page2;
      }
      async _createDevToolsPage(pageTargetId) {
        const openDevToolsResponse = await this.#connection.send("Target.openDevTools", {
          targetId: pageTargetId
        });
        const target = await this.waitForTarget((t) => {
          return t._targetId === openDevToolsResponse.targetId;
        });
        if (!target) {
          throw new Error(`Missing target for DevTools page (id = ${pageTargetId})`);
        }
        const initialized = await target._initializedDeferred.valueOrThrow() === Target_js_1.InitializationStatus.SUCCESS;
        if (!initialized) {
          throw new Error(`Failed to create target for DevTools page (id = ${pageTargetId})`);
        }
        const page2 = await target.page();
        if (!page2) {
          throw new Error(`Failed to create a DevTools Page for target (id = ${pageTargetId})`);
        }
        return page2;
      }
      async _hasDevToolsTarget(pageTargetId) {
        const response = await this.#connection.send("Target.getDevToolsTarget", {
          targetId: pageTargetId
        });
        return response.targetId;
      }
      async installExtension(path2) {
        const { id } = await this.#connection.send("Extensions.loadUnpacked", { path: path2 });
        return id;
      }
      uninstallExtension(id) {
        return this.#connection.send("Extensions.uninstall", { id });
      }
      async screens() {
        const { screenInfos } = await this.#connection.send("Emulation.getScreenInfos");
        return screenInfos;
      }
      async addScreen(params) {
        const { screenInfo } = await this.#connection.send("Emulation.addScreen", params);
        return screenInfo;
      }
      async removeScreen(screenId) {
        return await this.#connection.send("Emulation.removeScreen", { screenId });
      }
      async getWindowBounds(windowId) {
        const { bounds } = await this.#connection.send("Browser.getWindowBounds", {
          windowId: Number(windowId)
        });
        return bounds;
      }
      async setWindowBounds(windowId, windowBounds) {
        await this.#connection.send("Browser.setWindowBounds", {
          windowId: Number(windowId),
          bounds: windowBounds
        });
      }
      targets() {
        return Array.from(this.#targetManager.getAvailableTargets().values()).filter((target) => {
          return target._isTargetExposed() && target._initializedDeferred.value() === Target_js_1.InitializationStatus.SUCCESS;
        });
      }
      target() {
        const browserTarget = this.targets().find((target) => {
          return target.type() === "browser";
        });
        if (!browserTarget) {
          throw new Error("Browser target is not found");
        }
        return browserTarget;
      }
      async version() {
        const version = await this.#getVersion();
        return version.product;
      }
      async userAgent() {
        const version = await this.#getVersion();
        return version.userAgent;
      }
      async close() {
        await this.#closeCallback.call(null);
        await this.disconnect();
      }
      disconnect() {
        this.#targetManager.dispose();
        this.#connection.dispose();
        this._detach();
        return Promise.resolve();
      }
      get connected() {
        return !this.#connection._closed;
      }
      #getVersion() {
        return this.#connection.send("Browser.getVersion");
      }
      get debugInfo() {
        return {
          pendingProtocolErrors: this.#connection.getPendingProtocolErrors()
        };
      }
      isNetworkEnabled() {
        return this.#networkEnabled;
      }
    };
    exports2.CdpBrowser = CdpBrowser;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/BrowserConnector.js
var require_BrowserConnector = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/BrowserConnector.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2._connectToCdpBrowser = _connectToCdpBrowser;
    var util_js_1 = require_util();
    var incremental_id_generator_js_1 = require_incremental_id_generator();
    var Browser_js_1 = require_Browser2();
    var Connection_js_1 = require_Connection();
    async function _connectToCdpBrowser(connectionTransport, url, options) {
      const { acceptInsecureCerts = false, networkEnabled = true, defaultViewport = util_js_1.DEFAULT_VIEWPORT, downloadBehavior, targetFilter, _isPageTarget: isPageTarget, slowMo = 0, protocolTimeout, handleDevToolsAsPage, idGenerator = (0, incremental_id_generator_js_1.createIncrementalIdGenerator)() } = options;
      const connection = new Connection_js_1.Connection(
        url,
        connectionTransport,
        slowMo,
        protocolTimeout,
        /* rawErrors */
        false,
        idGenerator
      );
      const { browserContextIds } = await connection.send("Target.getBrowserContexts");
      const browser = await Browser_js_1.CdpBrowser._create(connection, browserContextIds, acceptInsecureCerts, defaultViewport, downloadBehavior, void 0, () => {
        return connection.send("Browser.close").catch(util_js_1.debugError);
      }, targetFilter, isPageTarget, void 0, networkEnabled, handleDevToolsAsPage);
      return browser;
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ExtensionTransport.js
var require_ExtensionTransport = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ExtensionTransport.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ExtensionTransport = void 0;
    var tabTargetInfo = {
      targetId: "tabTargetId",
      type: "tab",
      title: "tab",
      url: "about:blank",
      attached: false,
      canAccessOpener: false
    };
    var pageTargetInfo = {
      targetId: "pageTargetId",
      type: "page",
      title: "page",
      url: "about:blank",
      attached: false,
      canAccessOpener: false
    };
    var ExtensionTransport = class _ExtensionTransport {
      static async connectTab(tabId) {
        await chrome.debugger.attach({ tabId }, "1.3");
        return new _ExtensionTransport(tabId);
      }
      onmessage;
      onclose;
      #tabId;
      /**
       * @internal
       */
      constructor(tabId) {
        this.#tabId = tabId;
        chrome.debugger.onEvent.addListener(this.#debuggerEventHandler);
      }
      #debuggerEventHandler = (source, method, params) => {
        if (source.tabId !== this.#tabId) {
          return;
        }
        this.#dispatchResponse({
          // @ts-expect-error sessionId is not in stable yet.
          sessionId: source.sessionId ?? "pageTargetSessionId",
          method,
          params
        });
      };
      #dispatchResponse(message) {
        setTimeout(() => {
          this.onmessage?.(JSON.stringify(message));
        }, 0);
      }
      send(message) {
        const parsed = JSON.parse(message);
        switch (parsed.method) {
          case "Browser.getVersion": {
            this.#dispatchResponse({
              id: parsed.id,
              sessionId: parsed.sessionId,
              method: parsed.method,
              result: {
                protocolVersion: "1.3",
                product: "chrome",
                revision: "unknown",
                userAgent: "chrome",
                jsVersion: "unknown"
              }
            });
            return;
          }
          case "Target.getBrowserContexts": {
            this.#dispatchResponse({
              id: parsed.id,
              sessionId: parsed.sessionId,
              method: parsed.method,
              result: {
                browserContextIds: []
              }
            });
            return;
          }
          case "Target.setDiscoverTargets": {
            this.#dispatchResponse({
              method: "Target.targetCreated",
              params: {
                targetInfo: tabTargetInfo
              }
            });
            this.#dispatchResponse({
              method: "Target.targetCreated",
              params: {
                targetInfo: pageTargetInfo
              }
            });
            this.#dispatchResponse({
              id: parsed.id,
              sessionId: parsed.sessionId,
              method: parsed.method,
              result: {}
            });
            return;
          }
          case "Target.setAutoAttach": {
            if (parsed.sessionId === "tabTargetSessionId") {
              this.#dispatchResponse({
                method: "Target.attachedToTarget",
                sessionId: "tabTargetSessionId",
                params: {
                  targetInfo: pageTargetInfo,
                  sessionId: "pageTargetSessionId"
                }
              });
              this.#dispatchResponse({
                id: parsed.id,
                sessionId: parsed.sessionId,
                method: parsed.method,
                result: {}
              });
              return;
            } else if (!parsed.sessionId) {
              this.#dispatchResponse({
                method: "Target.attachedToTarget",
                params: {
                  targetInfo: tabTargetInfo,
                  sessionId: "tabTargetSessionId"
                }
              });
              this.#dispatchResponse({
                id: parsed.id,
                sessionId: parsed.sessionId,
                method: parsed.method,
                result: {}
              });
              return;
            }
          }
        }
        if (parsed.sessionId === "pageTargetSessionId") {
          delete parsed.sessionId;
        }
        chrome.debugger.sendCommand({ tabId: this.#tabId, sessionId: parsed.sessionId }, parsed.method, parsed.params).then((response) => {
          this.#dispatchResponse({
            id: parsed.id,
            sessionId: parsed.sessionId ?? "pageTargetSessionId",
            method: parsed.method,
            result: response
          });
        }).catch((err) => {
          this.#dispatchResponse({
            id: parsed.id,
            sessionId: parsed.sessionId ?? "pageTargetSessionId",
            method: parsed.method,
            error: {
              code: err?.code,
              data: err?.data,
              message: err?.message ?? "CDP error had no message"
            }
          });
        });
      }
      close() {
        chrome.debugger.onEvent.removeListener(this.#debuggerEventHandler);
        void chrome.debugger.detach({ tabId: this.#tabId });
      }
    };
    exports2.ExtensionTransport = ExtensionTransport;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/PredefinedNetworkConditions.js
var require_PredefinedNetworkConditions = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/PredefinedNetworkConditions.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PredefinedNetworkConditions = void 0;
    exports2.PredefinedNetworkConditions = Object.freeze({
      // Generally aligned with DevTools
      // https://source.chromium.org/chromium/chromium/src/+/main:third_party/devtools-frontend/src/front_end/core/sdk/NetworkManager.ts;l=398;drc=225e1240f522ca684473f541ae6dae6cd766dd33.
      "Slow 3G": {
        // ~500Kbps down
        download: 500 * 1e3 / 8 * 0.8,
        // ~500Kbps up
        upload: 500 * 1e3 / 8 * 0.8,
        // 400ms RTT
        latency: 400 * 5
      },
      "Fast 3G": {
        // ~1.6 Mbps down
        download: 1.6 * 1e3 * 1e3 / 8 * 0.9,
        // ~0.75 Mbps up
        upload: 750 * 1e3 / 8 * 0.9,
        // 150ms RTT
        latency: 150 * 3.75
      },
      // alias to Fast 3G to align with Lighthouse (crbug.com/342406608)
      // and DevTools (crbug.com/342406608),
      "Slow 4G": {
        // ~1.6 Mbps down
        download: 1.6 * 1e3 * 1e3 / 8 * 0.9,
        // ~0.75 Mbps up
        upload: 750 * 1e3 / 8 * 0.9,
        // 150ms RTT
        latency: 150 * 3.75
      },
      "Fast 4G": {
        // 9 Mbps down
        download: 9 * 1e3 * 1e3 / 8 * 0.9,
        // 1.5 Mbps up
        upload: 1.5 * 1e3 * 1e3 / 8 * 0.9,
        // 60ms RTT
        latency: 60 * 2.75
      }
    });
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/TargetManageEvents.js
var require_TargetManageEvents = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/TargetManageEvents.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/cdp.js
var require_cdp = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/cdp.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    __exportStar2(require_Accessibility(), exports2);
    __exportStar2(require_Binding(), exports2);
    __exportStar2(require_BluetoothEmulation(), exports2);
    __exportStar2(require_Browser2(), exports2);
    __exportStar2(require_BrowserContext2(), exports2);
    __exportStar2(require_BrowserConnector(), exports2);
    __exportStar2(require_CdpSession(), exports2);
    __exportStar2(require_Connection(), exports2);
    __exportStar2(require_Coverage(), exports2);
    __exportStar2(require_CdpPreloadScript(), exports2);
    __exportStar2(require_DeviceRequestPrompt2(), exports2);
    __exportStar2(require_Dialog2(), exports2);
    __exportStar2(require_ElementHandle2(), exports2);
    __exportStar2(require_EmulationManager(), exports2);
    __exportStar2(require_ExecutionContext(), exports2);
    __exportStar2(require_ExtensionTransport(), exports2);
    __exportStar2(require_Frame2(), exports2);
    __exportStar2(require_FrameManager(), exports2);
    __exportStar2(require_FrameManagerEvents(), exports2);
    __exportStar2(require_FrameTree(), exports2);
    __exportStar2(require_HTTPRequest2(), exports2);
    __exportStar2(require_HTTPResponse2(), exports2);
    __exportStar2(require_Input2(), exports2);
    __exportStar2(require_IsolatedWorld(), exports2);
    __exportStar2(require_IsolatedWorlds(), exports2);
    __exportStar2(require_JSHandle2(), exports2);
    __exportStar2(require_LifecycleWatcher(), exports2);
    __exportStar2(require_NetworkEventManager(), exports2);
    __exportStar2(require_NetworkManager(), exports2);
    __exportStar2(require_Page2(), exports2);
    __exportStar2(require_PredefinedNetworkConditions(), exports2);
    __exportStar2(require_Target2(), exports2);
    __exportStar2(require_TargetManager(), exports2);
    __exportStar2(require_TargetManageEvents(), exports2);
    __exportStar2(require_Tracing(), exports2);
    __exportStar2(require_utils(), exports2);
    __exportStar2(require_WebWorker2(), exports2);
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/BrowserWebSocketTransport.js
var require_BrowserWebSocketTransport = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/BrowserWebSocketTransport.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BrowserWebSocketTransport = void 0;
    var BrowserWebSocketTransport = class _BrowserWebSocketTransport {
      static create(url) {
        return new Promise((resolve5, reject) => {
          const ws = new WebSocket(url);
          ws.addEventListener("open", () => {
            return resolve5(new _BrowserWebSocketTransport(ws));
          });
          ws.addEventListener("error", reject);
        });
      }
      #ws;
      onmessage;
      onclose;
      constructor(ws) {
        this.#ws = ws;
        this.#ws.addEventListener("message", (event) => {
          if (this.onmessage) {
            this.onmessage.call(null, event.data);
          }
        });
        this.#ws.addEventListener("close", () => {
          if (this.onclose) {
            this.onclose.call(null);
          }
        });
        this.#ws.addEventListener("error", () => {
        });
      }
      send(message) {
        this.#ws.send(message);
      }
      close() {
        this.#ws.close();
      }
    };
    exports2.BrowserWebSocketTransport = BrowserWebSocketTransport;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/Device.js
var require_Device = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/Device.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.KnownDevices = void 0;
    var knownDevices = [
      {
        name: "Blackberry PlayBook",
        userAgent: "Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+",
        viewport: {
          width: 600,
          height: 1024,
          deviceScaleFactor: 1,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Blackberry PlayBook landscape",
        userAgent: "Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+",
        viewport: {
          width: 1024,
          height: 600,
          deviceScaleFactor: 1,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "BlackBerry Z30",
        userAgent: "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+",
        viewport: {
          width: 360,
          height: 640,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "BlackBerry Z30 landscape",
        userAgent: "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+",
        viewport: {
          width: 640,
          height: 360,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Galaxy Note 3",
        userAgent: "Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
        viewport: {
          width: 360,
          height: 640,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Galaxy Note 3 landscape",
        userAgent: "Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
        viewport: {
          width: 640,
          height: 360,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Galaxy Note II",
        userAgent: "Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
        viewport: {
          width: 360,
          height: 640,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Galaxy Note II landscape",
        userAgent: "Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
        viewport: {
          width: 640,
          height: 360,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Galaxy S III",
        userAgent: "Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
        viewport: {
          width: 360,
          height: 640,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Galaxy S III landscape",
        userAgent: "Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
        viewport: {
          width: 640,
          height: 360,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Galaxy S5",
        userAgent: "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 360,
          height: 640,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Galaxy S5 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 640,
          height: 360,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Galaxy S8",
        userAgent: "Mozilla/5.0 (Linux; Android 7.0; SM-G950U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",
        viewport: {
          width: 360,
          height: 740,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Galaxy S8 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 7.0; SM-G950U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",
        viewport: {
          width: 740,
          height: 360,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Galaxy S9+",
        userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; SM-G965U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",
        viewport: {
          width: 320,
          height: 658,
          deviceScaleFactor: 4.5,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Galaxy S9+ landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; SM-G965U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",
        viewport: {
          width: 658,
          height: 320,
          deviceScaleFactor: 4.5,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Galaxy Tab S4",
        userAgent: "Mozilla/5.0 (Linux; Android 8.1.0; SM-T837A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Safari/537.36",
        viewport: {
          width: 712,
          height: 1138,
          deviceScaleFactor: 2.25,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Galaxy Tab S4 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 8.1.0; SM-T837A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Safari/537.36",
        viewport: {
          width: 1138,
          height: 712,
          deviceScaleFactor: 2.25,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPad",
        userAgent: "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",
        viewport: {
          width: 768,
          height: 1024,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPad landscape",
        userAgent: "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",
        viewport: {
          width: 1024,
          height: 768,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPad (gen 6)",
        userAgent: "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 768,
          height: 1024,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPad (gen 6) landscape",
        userAgent: "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 1024,
          height: 768,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPad (gen 7)",
        userAgent: "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 810,
          height: 1080,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPad (gen 7) landscape",
        userAgent: "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 1080,
          height: 810,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPad Mini",
        userAgent: "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",
        viewport: {
          width: 768,
          height: 1024,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPad Mini landscape",
        userAgent: "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",
        viewport: {
          width: 1024,
          height: 768,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPad Pro",
        userAgent: "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",
        viewport: {
          width: 1024,
          height: 1366,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPad Pro landscape",
        userAgent: "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",
        viewport: {
          width: 1366,
          height: 1024,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPad Pro 11",
        userAgent: "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 834,
          height: 1194,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPad Pro 11 landscape",
        userAgent: "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 1194,
          height: 834,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 4",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53",
        viewport: {
          width: 320,
          height: 480,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 4 landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53",
        viewport: {
          width: 480,
          height: 320,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 5",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1",
        viewport: {
          width: 320,
          height: 568,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 5 landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1",
        viewport: {
          width: 568,
          height: 320,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 6",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 375,
          height: 667,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 6 landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 667,
          height: 375,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 6 Plus",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 414,
          height: 736,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 6 Plus landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 736,
          height: 414,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 7",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 375,
          height: 667,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 7 landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 667,
          height: 375,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 7 Plus",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 414,
          height: 736,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 7 Plus landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 736,
          height: 414,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 8",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 375,
          height: 667,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 8 landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 667,
          height: 375,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 8 Plus",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 414,
          height: 736,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 8 Plus landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 736,
          height: 414,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone SE",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1",
        viewport: {
          width: 320,
          height: 568,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone SE landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1",
        viewport: {
          width: 568,
          height: 320,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone X",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 375,
          height: 812,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone X landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 812,
          height: 375,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone XR",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 414,
          height: 896,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone XR landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 896,
          height: 414,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 11",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 414,
          height: 828,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 11 landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 828,
          height: 414,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 11 Pro",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 375,
          height: 812,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 11 Pro landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 812,
          height: 375,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 11 Pro Max",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 414,
          height: 896,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 11 Pro Max landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 896,
          height: 414,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 12",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 390,
          height: 844,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 12 landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 844,
          height: 390,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 12 Pro",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 390,
          height: 844,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 12 Pro landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 844,
          height: 390,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 12 Pro Max",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 428,
          height: 926,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 12 Pro Max landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 926,
          height: 428,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 12 Mini",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 375,
          height: 812,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 12 Mini landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 812,
          height: 375,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 13",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 390,
          height: 844,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 13 landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 844,
          height: 390,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 13 Pro",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 390,
          height: 844,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 13 Pro landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 844,
          height: 390,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 13 Pro Max",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 428,
          height: 926,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 13 Pro Max landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 926,
          height: 428,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 13 Mini",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 375,
          height: 812,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 13 Mini landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 812,
          height: 375,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 14",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 390,
          height: 663,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 14 landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 750,
          height: 340,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 14 Plus",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 428,
          height: 745,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 14 Plus landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 832,
          height: 378,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 14 Pro",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 393,
          height: 659,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 14 Pro landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 734,
          height: 343,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 14 Pro Max",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 430,
          height: 739,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 14 Pro Max landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 814,
          height: 380,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 15",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 393,
          height: 659,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 15 landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 734,
          height: 343,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 15 Plus",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 430,
          height: 739,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 15 Plus landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 814,
          height: 380,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 15 Pro",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 393,
          height: 659,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 15 Pro landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 734,
          height: 343,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 15 Pro Max",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 430,
          height: 739,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 15 Pro Max landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 814,
          height: 380,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "JioPhone 2",
        userAgent: "Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5",
        viewport: {
          width: 240,
          height: 320,
          deviceScaleFactor: 1,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "JioPhone 2 landscape",
        userAgent: "Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5",
        viewport: {
          width: 320,
          height: 240,
          deviceScaleFactor: 1,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Kindle Fire HDX",
        userAgent: "Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true",
        viewport: {
          width: 800,
          height: 1280,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Kindle Fire HDX landscape",
        userAgent: "Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true",
        viewport: {
          width: 1280,
          height: 800,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "LG Optimus L70",
        userAgent: "Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 384,
          height: 640,
          deviceScaleFactor: 1.25,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "LG Optimus L70 landscape",
        userAgent: "Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 640,
          height: 384,
          deviceScaleFactor: 1.25,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Microsoft Lumia 550",
        userAgent: "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263",
        viewport: {
          width: 640,
          height: 360,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Microsoft Lumia 950",
        userAgent: "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263",
        viewport: {
          width: 360,
          height: 640,
          deviceScaleFactor: 4,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Microsoft Lumia 950 landscape",
        userAgent: "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263",
        viewport: {
          width: 640,
          height: 360,
          deviceScaleFactor: 4,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Nexus 10",
        userAgent: "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36",
        viewport: {
          width: 800,
          height: 1280,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Nexus 10 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36",
        viewport: {
          width: 1280,
          height: 800,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Nexus 4",
        userAgent: "Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 384,
          height: 640,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Nexus 4 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 640,
          height: 384,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Nexus 5",
        userAgent: "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 360,
          height: 640,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Nexus 5 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 640,
          height: 360,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Nexus 5X",
        userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 412,
          height: 732,
          deviceScaleFactor: 2.625,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Nexus 5X landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 732,
          height: 412,
          deviceScaleFactor: 2.625,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Nexus 6",
        userAgent: "Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 412,
          height: 732,
          deviceScaleFactor: 3.5,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Nexus 6 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 732,
          height: 412,
          deviceScaleFactor: 3.5,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Nexus 6P",
        userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 412,
          height: 732,
          deviceScaleFactor: 3.5,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Nexus 6P landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 732,
          height: 412,
          deviceScaleFactor: 3.5,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Nexus 7",
        userAgent: "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36",
        viewport: {
          width: 600,
          height: 960,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Nexus 7 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36",
        viewport: {
          width: 960,
          height: 600,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Nokia Lumia 520",
        userAgent: "Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)",
        viewport: {
          width: 320,
          height: 533,
          deviceScaleFactor: 1.5,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Nokia Lumia 520 landscape",
        userAgent: "Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)",
        viewport: {
          width: 533,
          height: 320,
          deviceScaleFactor: 1.5,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Nokia N9",
        userAgent: "Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13",
        viewport: {
          width: 480,
          height: 854,
          deviceScaleFactor: 1,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Nokia N9 landscape",
        userAgent: "Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13",
        viewport: {
          width: 854,
          height: 480,
          deviceScaleFactor: 1,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Pixel 2",
        userAgent: "Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 411,
          height: 731,
          deviceScaleFactor: 2.625,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Pixel 2 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 731,
          height: 411,
          deviceScaleFactor: 2.625,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Pixel 2 XL",
        userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 411,
          height: 823,
          deviceScaleFactor: 3.5,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Pixel 2 XL landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 823,
          height: 411,
          deviceScaleFactor: 3.5,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Pixel 3",
        userAgent: "Mozilla/5.0 (Linux; Android 9; Pixel 3 Build/PQ1A.181105.017.A1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.158 Mobile Safari/537.36",
        viewport: {
          width: 393,
          height: 786,
          deviceScaleFactor: 2.75,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Pixel 3 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 9; Pixel 3 Build/PQ1A.181105.017.A1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.158 Mobile Safari/537.36",
        viewport: {
          width: 786,
          height: 393,
          deviceScaleFactor: 2.75,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Pixel 4",
        userAgent: "Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Mobile Safari/537.36",
        viewport: {
          width: 353,
          height: 745,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Pixel 4 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Mobile Safari/537.36",
        viewport: {
          width: 745,
          height: 353,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Pixel 4a (5G)",
        userAgent: "Mozilla/5.0 (Linux; Android 11; Pixel 4a (5G)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",
        viewport: {
          width: 353,
          height: 745,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Pixel 4a (5G) landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 11; Pixel 4a (5G)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",
        viewport: {
          width: 745,
          height: 353,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Pixel 5",
        userAgent: "Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",
        viewport: {
          width: 393,
          height: 851,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Pixel 5 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",
        viewport: {
          width: 851,
          height: 393,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Moto G4",
        userAgent: "Mozilla/5.0 (Linux; Android 7.0; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",
        viewport: {
          width: 360,
          height: 640,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Moto G4 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 7.0; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",
        viewport: {
          width: 640,
          height: 360,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      }
    ];
    var knownDevicesByName = {};
    for (const device of knownDevices) {
      knownDevicesByName[device.name] = device;
    }
    exports2.KnownDevices = Object.freeze(knownDevicesByName);
  }
});

// node_modules/mitt/dist/mitt.mjs
var mitt_exports = {};
__export(mitt_exports, {
  default: () => mitt_default
});
function mitt_default(n) {
  return { all: n = n || /* @__PURE__ */ new Map(), on: function(t, e) {
    var i = n.get(t);
    i ? i.push(e) : n.set(t, [e]);
  }, off: function(t, e) {
    var i = n.get(t);
    i && (e ? i.splice(i.indexOf(e) >>> 0, 1) : n.set(t, []));
  }, emit: function(t, e) {
    var i = n.get(t);
    i && i.slice().map(function(n2) {
      n2(e);
    }), (i = n.get("*")) && i.slice().map(function(n2) {
      n2(t, e);
    });
  } };
}
var init_mitt = __esm({
  "node_modules/mitt/dist/mitt.mjs"() {
    init_prefix();
  }
});

// node_modules/chromium-bidi/lib/cjs/utils/EventEmitter.js
var require_EventEmitter2 = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/utils/EventEmitter.js"(exports2) {
    "use strict";
    init_prefix();
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.EventEmitter = void 0;
    var mitt_1 = __importDefault2((init_mitt(), __toCommonJS(mitt_exports)));
    var EventEmitter = class {
      #emitter = (0, mitt_1.default)();
      on(type, handler) {
        this.#emitter.on(type, handler);
        return this;
      }
      /**
       * Like `on` but the listener will only be fired once and then it will be removed.
       * @param event The event you'd like to listen to
       * @param handler The handler function to run when the event occurs
       * @return `this` to enable chaining method calls.
       */
      once(event, handler) {
        const onceHandler = (eventData) => {
          handler(eventData);
          this.off(event, onceHandler);
        };
        return this.on(event, onceHandler);
      }
      off(type, handler) {
        this.#emitter.off(type, handler);
        return this;
      }
      /**
       * Emits an event and call any associated listeners.
       *
       * @param event The event to emit.
       * @param eventData Any data to emit with the event.
       * @return `true` if there are any listeners, `false` otherwise.
       */
      emit(event, eventData) {
        this.#emitter.emit(event, eventData);
      }
      /**
       * Removes all listeners. If given an event argument, it will remove only
       * listeners for that event.
       * @param event - the event to remove listeners for.
       * @returns `this` to enable you to chain method calls.
       */
      removeAllListeners(event) {
        if (event) {
          this.#emitter.all.delete(event);
        } else {
          this.#emitter.all.clear();
        }
        return this;
      }
    };
    exports2.EventEmitter = EventEmitter;
  }
});

// node_modules/chromium-bidi/lib/cjs/utils/log.js
var require_log = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/utils/log.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LogType = void 0;
    var LogType;
    (function(LogType2) {
      LogType2["bidi"] = "bidi";
      LogType2["cdp"] = "cdp";
      LogType2["debug"] = "debug";
      LogType2["debugError"] = "debug:error";
      LogType2["debugInfo"] = "debug:info";
      LogType2["debugWarn"] = "debug:warn";
    })(LogType || (exports2.LogType = LogType = {}));
  }
});

// node_modules/chromium-bidi/lib/cjs/utils/ProcessingQueue.js
var require_ProcessingQueue = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/utils/ProcessingQueue.js"(exports2) {
    "use strict";
    init_prefix();
    var _a2;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ProcessingQueue = void 0;
    var log_js_1 = require_log();
    var ProcessingQueue = class {
      static LOGGER_PREFIX = `${log_js_1.LogType.debug}:queue`;
      #logger;
      #processor;
      #queue = [];
      // Flag to keep only 1 active processor.
      #isProcessing = false;
      constructor(processor, logger) {
        this.#processor = processor;
        this.#logger = logger;
      }
      add(entry, name) {
        this.#queue.push([entry, name]);
        void this.#processIfNeeded();
      }
      async #processIfNeeded() {
        if (this.#isProcessing) {
          return;
        }
        this.#isProcessing = true;
        while (this.#queue.length > 0) {
          const arrayEntry = this.#queue.shift();
          if (!arrayEntry) {
            continue;
          }
          const [entryPromise, name] = arrayEntry;
          this.#logger?.(_a2.LOGGER_PREFIX, "Processing event:", name);
          await entryPromise.then((entry) => {
            if (entry.kind === "error") {
              this.#logger?.(log_js_1.LogType.debugError, "Event threw before sending:", entry.error.message, entry.error.stack);
              return;
            }
            return this.#processor(entry.value);
          }).catch((error) => {
            this.#logger?.(log_js_1.LogType.debugError, "Event was not processed:", error?.message);
          });
        }
        this.#isProcessing = false;
      }
    };
    exports2.ProcessingQueue = ProcessingQueue;
    _a2 = ProcessingQueue;
  }
});

// node_modules/chromium-bidi/lib/cjs/protocol/cdp.js
var require_cdp2 = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/protocol/cdp.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
  }
});

// node_modules/chromium-bidi/lib/cjs/protocol/chromium-bidi.js
var require_chromium_bidi = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/protocol/chromium-bidi.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.EVENT_NAMES = exports2.Speculation = exports2.Bluetooth = exports2.Network = exports2.Input = exports2.BrowsingContext = exports2.Log = exports2.Script = exports2.BiDiModule = void 0;
    var BiDiModule;
    (function(BiDiModule2) {
      BiDiModule2["Bluetooth"] = "bluetooth";
      BiDiModule2["Browser"] = "browser";
      BiDiModule2["BrowsingContext"] = "browsingContext";
      BiDiModule2["Cdp"] = "goog:cdp";
      BiDiModule2["Input"] = "input";
      BiDiModule2["Log"] = "log";
      BiDiModule2["Network"] = "network";
      BiDiModule2["Script"] = "script";
      BiDiModule2["Session"] = "session";
      BiDiModule2["Speculation"] = "speculation";
    })(BiDiModule || (exports2.BiDiModule = BiDiModule = {}));
    var Script;
    (function(Script2) {
      let EventNames;
      (function(EventNames2) {
        EventNames2["Message"] = "script.message";
        EventNames2["RealmCreated"] = "script.realmCreated";
        EventNames2["RealmDestroyed"] = "script.realmDestroyed";
      })(EventNames = Script2.EventNames || (Script2.EventNames = {}));
    })(Script || (exports2.Script = Script = {}));
    var Log;
    (function(Log2) {
      let EventNames;
      (function(EventNames2) {
        EventNames2["LogEntryAdded"] = "log.entryAdded";
      })(EventNames = Log2.EventNames || (Log2.EventNames = {}));
    })(Log || (exports2.Log = Log = {}));
    var BrowsingContext;
    (function(BrowsingContext2) {
      let EventNames;
      (function(EventNames2) {
        EventNames2["ContextCreated"] = "browsingContext.contextCreated";
        EventNames2["ContextDestroyed"] = "browsingContext.contextDestroyed";
        EventNames2["DomContentLoaded"] = "browsingContext.domContentLoaded";
        EventNames2["DownloadEnd"] = "browsingContext.downloadEnd";
        EventNames2["DownloadWillBegin"] = "browsingContext.downloadWillBegin";
        EventNames2["FragmentNavigated"] = "browsingContext.fragmentNavigated";
        EventNames2["HistoryUpdated"] = "browsingContext.historyUpdated";
        EventNames2["Load"] = "browsingContext.load";
        EventNames2["NavigationAborted"] = "browsingContext.navigationAborted";
        EventNames2["NavigationCommitted"] = "browsingContext.navigationCommitted";
        EventNames2["NavigationFailed"] = "browsingContext.navigationFailed";
        EventNames2["NavigationStarted"] = "browsingContext.navigationStarted";
        EventNames2["UserPromptClosed"] = "browsingContext.userPromptClosed";
        EventNames2["UserPromptOpened"] = "browsingContext.userPromptOpened";
      })(EventNames = BrowsingContext2.EventNames || (BrowsingContext2.EventNames = {}));
    })(BrowsingContext || (exports2.BrowsingContext = BrowsingContext = {}));
    var Input;
    (function(Input2) {
      let EventNames;
      (function(EventNames2) {
        EventNames2["FileDialogOpened"] = "input.fileDialogOpened";
      })(EventNames = Input2.EventNames || (Input2.EventNames = {}));
    })(Input || (exports2.Input = Input = {}));
    var Network;
    (function(Network2) {
      let EventNames;
      (function(EventNames2) {
        EventNames2["AuthRequired"] = "network.authRequired";
        EventNames2["BeforeRequestSent"] = "network.beforeRequestSent";
        EventNames2["FetchError"] = "network.fetchError";
        EventNames2["ResponseCompleted"] = "network.responseCompleted";
        EventNames2["ResponseStarted"] = "network.responseStarted";
      })(EventNames = Network2.EventNames || (Network2.EventNames = {}));
    })(Network || (exports2.Network = Network = {}));
    var Bluetooth;
    (function(Bluetooth2) {
      let EventNames;
      (function(EventNames2) {
        EventNames2["RequestDevicePromptUpdated"] = "bluetooth.requestDevicePromptUpdated";
        EventNames2["GattConnectionAttempted"] = "bluetooth.gattConnectionAttempted";
        EventNames2["CharacteristicEventGenerated"] = "bluetooth.characteristicEventGenerated";
        EventNames2["DescriptorEventGenerated"] = "bluetooth.descriptorEventGenerated";
      })(EventNames = Bluetooth2.EventNames || (Bluetooth2.EventNames = {}));
    })(Bluetooth || (exports2.Bluetooth = Bluetooth = {}));
    var Speculation;
    (function(Speculation2) {
      let EventNames;
      (function(EventNames2) {
        EventNames2["PrefetchStatusUpdated"] = "speculation.prefetchStatusUpdated";
      })(EventNames = Speculation2.EventNames || (Speculation2.EventNames = {}));
    })(Speculation || (exports2.Speculation = Speculation = {}));
    exports2.EVENT_NAMES = /* @__PURE__ */ new Set([
      // keep-sorted start
      ...Object.values(BiDiModule),
      ...Object.values(Bluetooth.EventNames),
      ...Object.values(BrowsingContext.EventNames),
      ...Object.values(Input.EventNames),
      ...Object.values(Log.EventNames),
      ...Object.values(Network.EventNames),
      ...Object.values(Script.EventNames),
      ...Object.values(Speculation.EventNames)
      // keep-sorted end
    ]);
  }
});

// node_modules/chromium-bidi/lib/cjs/protocol/generated/webdriver-bidi.js
var require_webdriver_bidi = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/protocol/generated/webdriver-bidi.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
  }
});

// node_modules/chromium-bidi/lib/cjs/protocol/ErrorResponse.js
var require_ErrorResponse = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/protocol/ErrorResponse.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.UnavailableNetworkDataException = exports2.NoSuchNetworkDataException = exports2.NoSuchNetworkCollectorException = exports2.NoSuchWebExtensionException = exports2.InvalidWebExtensionException = exports2.UnderspecifiedStoragePartitionException = exports2.UnableToSetFileInputException = exports2.UnableToSetCookieException = exports2.NoSuchStoragePartitionException = exports2.UnsupportedOperationException = exports2.UnableToCloseBrowserException = exports2.UnableToCaptureScreenException = exports2.UnknownErrorException = exports2.UnknownCommandException = exports2.SessionNotCreatedException = exports2.NoSuchUserContextException = exports2.NoSuchScriptException = exports2.NoSuchRequestException = exports2.NoSuchNodeException = exports2.NoSuchInterceptException = exports2.NoSuchHistoryEntryException = exports2.NoSuchHandleException = exports2.NoSuchFrameException = exports2.NoSuchElementException = exports2.NoSuchAlertException = exports2.MoveTargetOutOfBoundsException = exports2.InvalidSessionIdException = exports2.InvalidSelectorException = exports2.InvalidArgumentException = exports2.Exception = void 0;
    var Exception = class extends Error {
      error;
      message;
      stacktrace;
      constructor(error, message, stacktrace) {
        super();
        this.error = error;
        this.message = message;
        this.stacktrace = stacktrace;
      }
      toErrorResponse(commandId) {
        return {
          type: "error",
          id: commandId,
          error: this.error,
          message: this.message,
          stacktrace: this.stacktrace
        };
      }
    };
    exports2.Exception = Exception;
    var InvalidArgumentException = class extends Exception {
      constructor(message, stacktrace) {
        super("invalid argument", message, stacktrace);
      }
    };
    exports2.InvalidArgumentException = InvalidArgumentException;
    var InvalidSelectorException = class extends Exception {
      constructor(message, stacktrace) {
        super("invalid selector", message, stacktrace);
      }
    };
    exports2.InvalidSelectorException = InvalidSelectorException;
    var InvalidSessionIdException = class extends Exception {
      constructor(message, stacktrace) {
        super("invalid session id", message, stacktrace);
      }
    };
    exports2.InvalidSessionIdException = InvalidSessionIdException;
    var MoveTargetOutOfBoundsException = class extends Exception {
      constructor(message, stacktrace) {
        super("move target out of bounds", message, stacktrace);
      }
    };
    exports2.MoveTargetOutOfBoundsException = MoveTargetOutOfBoundsException;
    var NoSuchAlertException = class extends Exception {
      constructor(message, stacktrace) {
        super("no such alert", message, stacktrace);
      }
    };
    exports2.NoSuchAlertException = NoSuchAlertException;
    var NoSuchElementException = class extends Exception {
      constructor(message, stacktrace) {
        super("no such element", message, stacktrace);
      }
    };
    exports2.NoSuchElementException = NoSuchElementException;
    var NoSuchFrameException = class extends Exception {
      constructor(message, stacktrace) {
        super("no such frame", message, stacktrace);
      }
    };
    exports2.NoSuchFrameException = NoSuchFrameException;
    var NoSuchHandleException = class extends Exception {
      constructor(message, stacktrace) {
        super("no such handle", message, stacktrace);
      }
    };
    exports2.NoSuchHandleException = NoSuchHandleException;
    var NoSuchHistoryEntryException = class extends Exception {
      constructor(message, stacktrace) {
        super("no such history entry", message, stacktrace);
      }
    };
    exports2.NoSuchHistoryEntryException = NoSuchHistoryEntryException;
    var NoSuchInterceptException = class extends Exception {
      constructor(message, stacktrace) {
        super("no such intercept", message, stacktrace);
      }
    };
    exports2.NoSuchInterceptException = NoSuchInterceptException;
    var NoSuchNodeException = class extends Exception {
      constructor(message, stacktrace) {
        super("no such node", message, stacktrace);
      }
    };
    exports2.NoSuchNodeException = NoSuchNodeException;
    var NoSuchRequestException = class extends Exception {
      constructor(message, stacktrace) {
        super("no such request", message, stacktrace);
      }
    };
    exports2.NoSuchRequestException = NoSuchRequestException;
    var NoSuchScriptException = class extends Exception {
      constructor(message, stacktrace) {
        super("no such script", message, stacktrace);
      }
    };
    exports2.NoSuchScriptException = NoSuchScriptException;
    var NoSuchUserContextException = class extends Exception {
      constructor(message, stacktrace) {
        super("no such user context", message, stacktrace);
      }
    };
    exports2.NoSuchUserContextException = NoSuchUserContextException;
    var SessionNotCreatedException = class extends Exception {
      constructor(message, stacktrace) {
        super("session not created", message, stacktrace);
      }
    };
    exports2.SessionNotCreatedException = SessionNotCreatedException;
    var UnknownCommandException = class extends Exception {
      constructor(message, stacktrace) {
        super("unknown command", message, stacktrace);
      }
    };
    exports2.UnknownCommandException = UnknownCommandException;
    var UnknownErrorException = class extends Exception {
      constructor(message, stacktrace = new Error().stack) {
        super("unknown error", message, stacktrace);
      }
    };
    exports2.UnknownErrorException = UnknownErrorException;
    var UnableToCaptureScreenException = class extends Exception {
      constructor(message, stacktrace) {
        super("unable to capture screen", message, stacktrace);
      }
    };
    exports2.UnableToCaptureScreenException = UnableToCaptureScreenException;
    var UnableToCloseBrowserException = class extends Exception {
      constructor(message, stacktrace) {
        super("unable to close browser", message, stacktrace);
      }
    };
    exports2.UnableToCloseBrowserException = UnableToCloseBrowserException;
    var UnsupportedOperationException = class extends Exception {
      constructor(message, stacktrace) {
        super("unsupported operation", message, stacktrace);
      }
    };
    exports2.UnsupportedOperationException = UnsupportedOperationException;
    var NoSuchStoragePartitionException = class extends Exception {
      constructor(message, stacktrace) {
        super("no such storage partition", message, stacktrace);
      }
    };
    exports2.NoSuchStoragePartitionException = NoSuchStoragePartitionException;
    var UnableToSetCookieException = class extends Exception {
      constructor(message, stacktrace) {
        super("unable to set cookie", message, stacktrace);
      }
    };
    exports2.UnableToSetCookieException = UnableToSetCookieException;
    var UnableToSetFileInputException = class extends Exception {
      constructor(message, stacktrace) {
        super("unable to set file input", message, stacktrace);
      }
    };
    exports2.UnableToSetFileInputException = UnableToSetFileInputException;
    var UnderspecifiedStoragePartitionException = class extends Exception {
      constructor(message, stacktrace) {
        super("underspecified storage partition", message, stacktrace);
      }
    };
    exports2.UnderspecifiedStoragePartitionException = UnderspecifiedStoragePartitionException;
    var InvalidWebExtensionException = class extends Exception {
      constructor(message, stacktrace) {
        super("invalid web extension", message, stacktrace);
      }
    };
    exports2.InvalidWebExtensionException = InvalidWebExtensionException;
    var NoSuchWebExtensionException = class extends Exception {
      constructor(message, stacktrace) {
        super("no such web extension", message, stacktrace);
      }
    };
    exports2.NoSuchWebExtensionException = NoSuchWebExtensionException;
    var NoSuchNetworkCollectorException = class extends Exception {
      constructor(message, stacktrace) {
        super("no such network collector", message, stacktrace);
      }
    };
    exports2.NoSuchNetworkCollectorException = NoSuchNetworkCollectorException;
    var NoSuchNetworkDataException = class extends Exception {
      constructor(message, stacktrace) {
        super("no such network data", message, stacktrace);
      }
    };
    exports2.NoSuchNetworkDataException = NoSuchNetworkDataException;
    var UnavailableNetworkDataException = class extends Exception {
      constructor(message, stacktrace) {
        super("unavailable network data", message, stacktrace);
      }
    };
    exports2.UnavailableNetworkDataException = UnavailableNetworkDataException;
  }
});

// node_modules/chromium-bidi/lib/cjs/protocol/generated/webdriver-bidi-permissions.js
var require_webdriver_bidi_permissions = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/protocol/generated/webdriver-bidi-permissions.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
  }
});

// node_modules/chromium-bidi/lib/cjs/protocol/generated/webdriver-bidi-bluetooth.js
var require_webdriver_bidi_bluetooth = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/protocol/generated/webdriver-bidi-bluetooth.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
  }
});

// node_modules/chromium-bidi/lib/cjs/protocol/generated/webdriver-bidi-nav-speculation.js
var require_webdriver_bidi_nav_speculation = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/protocol/generated/webdriver-bidi-nav-speculation.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
  }
});

// node_modules/chromium-bidi/lib/cjs/protocol/generated/webdriver-bidi-ua-client-hints.js
var require_webdriver_bidi_ua_client_hints = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/protocol/generated/webdriver-bidi-ua-client-hints.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
  }
});

// node_modules/chromium-bidi/lib/cjs/protocol/protocol.js
var require_protocol = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/protocol/protocol.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
      var ownKeys2 = function(o) {
        ownKeys2 = 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 ownKeys2(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]);
        }
        __setModuleDefault2(result, mod);
        return result;
      };
    })();
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.UAClientHints = exports2.ChromiumBidi = exports2.Cdp = void 0;
    exports2.Cdp = __importStar2(require_cdp2());
    exports2.ChromiumBidi = __importStar2(require_chromium_bidi());
    __exportStar2(require_webdriver_bidi(), exports2);
    __exportStar2(require_ErrorResponse(), exports2);
    __exportStar2(require_webdriver_bidi_permissions(), exports2);
    __exportStar2(require_webdriver_bidi_bluetooth(), exports2);
    __exportStar2(require_webdriver_bidi_nav_speculation(), exports2);
    exports2.UAClientHints = __importStar2(require_webdriver_bidi_ua_client_hints());
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/BidiNoOpParser.js
var require_BidiNoOpParser = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/BidiNoOpParser.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiNoOpParser = void 0;
    var BidiNoOpParser = class {
      // Bluetooth module
      // keep-sorted start block=yes
      parseDisableSimulationParameters(params) {
        return params;
      }
      parseHandleRequestDevicePromptParams(params) {
        return params;
      }
      parseSimulateAdapterParameters(params) {
        return params;
      }
      parseSimulateAdvertisementParameters(params) {
        return params;
      }
      parseSimulateCharacteristicParameters(params) {
        return params;
      }
      parseSimulateCharacteristicResponseParameters(params) {
        return params;
      }
      parseSimulateDescriptorParameters(params) {
        return params;
      }
      parseSimulateDescriptorResponseParameters(params) {
        return params;
      }
      parseSimulateGattConnectionResponseParameters(params) {
        return params;
      }
      parseSimulateGattDisconnectionParameters(params) {
        return params;
      }
      parseSimulatePreconnectedPeripheralParameters(params) {
        return params;
      }
      parseSimulateServiceParameters(params) {
        return params;
      }
      // keep-sorted end
      // Browser module
      // keep-sorted start block=yes
      parseCreateUserContextParameters(params) {
        return params;
      }
      parseRemoveUserContextParameters(params) {
        return params;
      }
      parseSetClientWindowStateParameters(params) {
        return params;
      }
      parseSetDownloadBehaviorParameters(params) {
        return params;
      }
      // keep-sorted end
      // Browsing Context module
      // keep-sorted start block=yes
      parseActivateParams(params) {
        return params;
      }
      parseCaptureScreenshotParams(params) {
        return params;
      }
      parseCloseParams(params) {
        return params;
      }
      parseCreateParams(params) {
        return params;
      }
      parseGetTreeParams(params) {
        return params;
      }
      parseHandleUserPromptParams(params) {
        return params;
      }
      parseLocateNodesParams(params) {
        return params;
      }
      parseNavigateParams(params) {
        return params;
      }
      parsePrintParams(params) {
        return params;
      }
      parseReloadParams(params) {
        return params;
      }
      parseSetViewportParams(params) {
        return params;
      }
      parseTraverseHistoryParams(params) {
        return params;
      }
      // keep-sorted end
      // CDP module
      // keep-sorted start block=yes
      parseGetSessionParams(params) {
        return params;
      }
      parseResolveRealmParams(params) {
        return params;
      }
      parseSendCommandParams(params) {
        return params;
      }
      // keep-sorted end
      // Emulation module
      // keep-sorted start block=yes
      parseSetClientHintsOverrideParams(params) {
        return params;
      }
      parseSetForcedColorsModeThemeOverrideParams(params) {
        return params;
      }
      parseSetGeolocationOverrideParams(params) {
        return params;
      }
      parseSetLocaleOverrideParams(params) {
        return params;
      }
      parseSetNetworkConditionsParams(params) {
        return params;
      }
      parseSetScreenOrientationOverrideParams(params) {
        return params;
      }
      parseSetScreenSettingsOverrideParams(params) {
        return params;
      }
      parseSetScriptingEnabledParams(params) {
        return params;
      }
      parseSetTimezoneOverrideParams(params) {
        return params;
      }
      parseSetTouchOverrideParams(params) {
        return params;
      }
      parseSetUserAgentOverrideParams(params) {
        return params;
      }
      // keep-sorted end
      // Script module
      // keep-sorted start block=yes
      parseAddPreloadScriptParams(params) {
        return params;
      }
      parseCallFunctionParams(params) {
        return params;
      }
      parseDisownParams(params) {
        return params;
      }
      parseEvaluateParams(params) {
        return params;
      }
      parseGetRealmsParams(params) {
        return params;
      }
      parseRemovePreloadScriptParams(params) {
        return params;
      }
      // keep-sorted end
      // Input module
      // keep-sorted start block=yes
      parsePerformActionsParams(params) {
        return params;
      }
      parseReleaseActionsParams(params) {
        return params;
      }
      parseSetFilesParams(params) {
        return params;
      }
      // keep-sorted end
      // Network module
      // keep-sorted start block=yes
      parseAddDataCollectorParams(params) {
        return params;
      }
      parseAddInterceptParams(params) {
        return params;
      }
      parseContinueRequestParams(params) {
        return params;
      }
      parseContinueResponseParams(params) {
        return params;
      }
      parseContinueWithAuthParams(params) {
        return params;
      }
      parseDisownDataParams(params) {
        return params;
      }
      parseFailRequestParams(params) {
        return params;
      }
      parseGetDataParams(params) {
        return params;
      }
      parseProvideResponseParams(params) {
        return params;
      }
      parseRemoveDataCollectorParams(params) {
        return params;
      }
      parseRemoveInterceptParams(params) {
        return params;
      }
      parseSetCacheBehaviorParams(params) {
        return params;
      }
      parseSetExtraHeadersParams(params) {
        return params;
      }
      // keep-sorted end
      // Permissions module
      // keep-sorted start block=yes
      parseSetPermissionsParams(params) {
        return params;
      }
      // keep-sorted end
      // Session module
      // keep-sorted start block=yes
      parseSubscribeParams(params) {
        return params;
      }
      parseUnsubscribeParams(params) {
        return params;
      }
      // keep-sorted end
      // Storage module
      // keep-sorted start block=yes
      parseDeleteCookiesParams(params) {
        return params;
      }
      parseGetCookiesParams(params) {
        return params;
      }
      parseSetCookieParams(params) {
        return params;
      }
      // keep-sorted end
      // WebExtenstion module
      // keep-sorted start block=yes
      parseInstallParams(params) {
        return params;
      }
      parseUninstallParams(params) {
        return params;
      }
    };
    exports2.BidiNoOpParser = BidiNoOpParser;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/browser/BrowserProcessor.js
var require_BrowserProcessor = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/browser/BrowserProcessor.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BrowserProcessor = void 0;
    exports2.getProxyStr = getProxyStr;
    var protocol_js_1 = require_protocol();
    var BrowserProcessor = class {
      #browserCdpClient;
      #browsingContextStorage;
      #configStorage;
      #userContextStorage;
      constructor(browserCdpClient, browsingContextStorage, configStorage, userContextStorage) {
        this.#browserCdpClient = browserCdpClient;
        this.#browsingContextStorage = browsingContextStorage;
        this.#configStorage = configStorage;
        this.#userContextStorage = userContextStorage;
      }
      close() {
        setTimeout(() => this.#browserCdpClient.sendCommand("Browser.close").catch(() => {
        }), 0);
        return {};
      }
      async createUserContext(params) {
        const w3cParams = params;
        const globalConfig = this.#configStorage.getGlobalConfig();
        if (w3cParams.acceptInsecureCerts !== void 0) {
          if (w3cParams.acceptInsecureCerts === false && globalConfig.acceptInsecureCerts === true)
            throw new protocol_js_1.UnknownErrorException(`Cannot set user context's "acceptInsecureCerts" to false, when a capability "acceptInsecureCerts" is set to true`);
        }
        const request = {};
        if (w3cParams.proxy) {
          const proxyStr = getProxyStr(w3cParams.proxy);
          if (proxyStr) {
            request.proxyServer = proxyStr;
          }
          if (w3cParams.proxy.noProxy) {
            request.proxyBypassList = w3cParams.proxy.noProxy.join(",");
          }
        } else {
          if (params["goog:proxyServer"] !== void 0) {
            request.proxyServer = params["goog:proxyServer"];
          }
          const proxyBypassList = params["goog:proxyBypassList"] ?? void 0;
          if (proxyBypassList) {
            request.proxyBypassList = proxyBypassList.join(",");
          }
        }
        const context = await this.#browserCdpClient.sendCommand("Target.createBrowserContext", request);
        await this.#applyDownloadBehavior(globalConfig.downloadBehavior ?? null, context.browserContextId);
        this.#configStorage.updateUserContextConfig(context.browserContextId, {
          acceptInsecureCerts: params["acceptInsecureCerts"],
          userPromptHandler: params["unhandledPromptBehavior"]
        });
        return {
          userContext: context.browserContextId
        };
      }
      async removeUserContext(params) {
        const userContext = params.userContext;
        if (userContext === "default") {
          throw new protocol_js_1.InvalidArgumentException("`default` user context cannot be removed");
        }
        try {
          await this.#browserCdpClient.sendCommand("Target.disposeBrowserContext", {
            browserContextId: userContext
          });
        } catch (err) {
          if (err.message.startsWith("Failed to find context with id")) {
            throw new protocol_js_1.NoSuchUserContextException(err.message);
          }
          throw err;
        }
        return {};
      }
      async getUserContexts() {
        return {
          userContexts: await this.#userContextStorage.getUserContexts()
        };
      }
      async #getWindowInfo(targetId) {
        const windowInfo = await this.#browserCdpClient.sendCommand("Browser.getWindowForTarget", { targetId });
        return {
          // `active` is not supported in CDP yet.
          active: false,
          clientWindow: `${windowInfo.windowId}`,
          state: windowInfo.bounds.windowState ?? "normal",
          height: windowInfo.bounds.height ?? 0,
          width: windowInfo.bounds.width ?? 0,
          x: windowInfo.bounds.left ?? 0,
          y: windowInfo.bounds.top ?? 0
        };
      }
      async setClientWindowState(params) {
        const { clientWindow } = params;
        const bounds = {
          windowState: params.state
        };
        if (params.state === "normal") {
          if (params.width !== void 0) {
            bounds.width = params.width;
          }
          if (params.height !== void 0) {
            bounds.height = params.height;
          }
          if (params.x !== void 0) {
            bounds.left = params.x;
          }
          if (params.y !== void 0) {
            bounds.top = params.y;
          }
        }
        const windowId = Number.parseInt(clientWindow);
        if (isNaN(windowId)) {
          throw new protocol_js_1.InvalidArgumentException("no such client window");
        }
        await this.#browserCdpClient.sendCommand("Browser.setWindowBounds", {
          windowId,
          bounds
        });
        const result = await this.#browserCdpClient.sendCommand("Browser.getWindowBounds", {
          windowId
        });
        return {
          active: false,
          clientWindow: `${windowId}`,
          state: result.bounds.windowState ?? "normal",
          height: result.bounds.height ?? 0,
          width: result.bounds.width ?? 0,
          x: result.bounds.left ?? 0,
          y: result.bounds.top ?? 0
        };
      }
      async getClientWindows() {
        const topLevelTargetIds = this.#browsingContextStorage.getTopLevelContexts().map((b) => b.cdpTarget.id);
        const clientWindows = await Promise.all(topLevelTargetIds.map(async (targetId) => await this.#getWindowInfo(targetId)));
        const uniqueClientWindowIds = /* @__PURE__ */ new Set();
        const uniqueClientWindows = new Array();
        for (const window2 of clientWindows) {
          if (!uniqueClientWindowIds.has(window2.clientWindow)) {
            uniqueClientWindowIds.add(window2.clientWindow);
            uniqueClientWindows.push(window2);
          }
        }
        return { clientWindows: uniqueClientWindows };
      }
      #toCdpDownloadBehavior(downloadBehavior) {
        if (downloadBehavior === null)
          return {
            behavior: "default"
          };
        if (downloadBehavior?.type === "denied")
          return {
            behavior: "deny"
          };
        if (downloadBehavior?.type === "allowed") {
          return {
            behavior: "allow",
            downloadPath: downloadBehavior.destinationFolder
          };
        }
        throw new protocol_js_1.UnknownErrorException("Unexpected download behavior");
      }
      async #applyDownloadBehavior(downloadBehavior, userContext) {
        await this.#browserCdpClient.sendCommand("Browser.setDownloadBehavior", {
          ...this.#toCdpDownloadBehavior(downloadBehavior),
          browserContextId: userContext === "default" ? void 0 : userContext,
          // Required for enabling download events.
          eventsEnabled: true
        });
      }
      async setDownloadBehavior(params) {
        let userContexts;
        if (params.userContexts === void 0) {
          userContexts = (await this.#userContextStorage.getUserContexts()).map((c) => c.userContext);
        } else {
          userContexts = Array.from(await this.#userContextStorage.verifyUserContextIdList(params.userContexts));
        }
        if (params.userContexts === void 0) {
          this.#configStorage.updateGlobalConfig({
            downloadBehavior: params.downloadBehavior
          });
        } else {
          params.userContexts.map((userContext) => this.#configStorage.updateUserContextConfig(userContext, {
            downloadBehavior: params.downloadBehavior
          }));
        }
        await Promise.all(userContexts.map(async (userContext) => {
          const downloadBehavior = this.#configStorage.getActiveConfig(void 0, userContext).downloadBehavior ?? null;
          await this.#applyDownloadBehavior(downloadBehavior, userContext);
        }));
        return {};
      }
    };
    exports2.BrowserProcessor = BrowserProcessor;
    function getProxyStr(proxyConfig) {
      if (proxyConfig.proxyType === "direct" || proxyConfig.proxyType === "system") {
        return void 0;
      }
      if (proxyConfig.proxyType === "pac") {
        throw new protocol_js_1.UnsupportedOperationException(`PAC proxy configuration is not supported per user context`);
      }
      if (proxyConfig.proxyType === "autodetect") {
        throw new protocol_js_1.UnsupportedOperationException(`Autodetect proxy is not supported per user context`);
      }
      if (proxyConfig.proxyType === "manual") {
        const servers = [];
        if (proxyConfig.httpProxy !== void 0) {
          servers.push(`http=${proxyConfig.httpProxy}`);
        }
        if (proxyConfig.sslProxy !== void 0) {
          servers.push(`https=${proxyConfig.sslProxy}`);
        }
        if (proxyConfig.socksProxy !== void 0 || proxyConfig.socksVersion !== void 0) {
          if (proxyConfig.socksProxy === void 0) {
            throw new protocol_js_1.InvalidArgumentException(`'socksVersion' cannot be set without 'socksProxy'`);
          }
          if (proxyConfig.socksVersion === void 0 || typeof proxyConfig.socksVersion !== "number" || !Number.isInteger(proxyConfig.socksVersion) || proxyConfig.socksVersion < 0 || proxyConfig.socksVersion > 255) {
            throw new protocol_js_1.InvalidArgumentException(`'socksVersion' must be between 0 and 255`);
          }
          servers.push(`socks=socks${proxyConfig.socksVersion}://${proxyConfig.socksProxy}`);
        }
        if (servers.length === 0) {
          return void 0;
        }
        return servers.join(";");
      }
      throw new protocol_js_1.UnknownErrorException(`Unknown proxy type`);
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/cdp/CdpProcessor.js
var require_CdpProcessor = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/cdp/CdpProcessor.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CdpProcessor = void 0;
    var protocol_js_1 = require_protocol();
    var CdpProcessor = class {
      #browsingContextStorage;
      #realmStorage;
      #cdpConnection;
      #browserCdpClient;
      constructor(browsingContextStorage, realmStorage, cdpConnection, browserCdpClient) {
        this.#browsingContextStorage = browsingContextStorage;
        this.#realmStorage = realmStorage;
        this.#cdpConnection = cdpConnection;
        this.#browserCdpClient = browserCdpClient;
      }
      getSession(params) {
        const context = params.context;
        const sessionId = this.#browsingContextStorage.getContext(context).cdpTarget.cdpSessionId;
        if (sessionId === void 0) {
          return {};
        }
        return { session: sessionId };
      }
      resolveRealm(params) {
        const context = params.realm;
        const realm = this.#realmStorage.getRealm({ realmId: context });
        if (realm === void 0) {
          throw new protocol_js_1.UnknownErrorException(`Could not find realm ${params.realm}`);
        }
        return { executionContextId: realm.executionContextId };
      }
      async sendCommand(params) {
        const client2 = params.session ? this.#cdpConnection.getCdpClient(params.session) : this.#browserCdpClient;
        const result = await client2.sendCommand(params.method, params.params);
        return {
          result,
          session: params.session
        };
      }
    };
    exports2.CdpProcessor = CdpProcessor;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/context/BrowsingContextProcessor.js
var require_BrowsingContextProcessor = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/context/BrowsingContextProcessor.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BrowsingContextProcessor = void 0;
    var protocol_js_1 = require_protocol();
    var BrowsingContextProcessor = class {
      #browserCdpClient;
      #browsingContextStorage;
      #contextConfigStorage;
      #eventManager;
      #userContextStorage;
      constructor(browserCdpClient, browsingContextStorage, userContextStorage, contextConfigStorage, eventManager) {
        this.#contextConfigStorage = contextConfigStorage;
        this.#userContextStorage = userContextStorage;
        this.#browserCdpClient = browserCdpClient;
        this.#browsingContextStorage = browsingContextStorage;
        this.#eventManager = eventManager;
        this.#eventManager.addSubscribeHook(protocol_js_1.ChromiumBidi.BrowsingContext.EventNames.ContextCreated, this.#onContextCreatedSubscribeHook.bind(this));
      }
      getTree(params) {
        const resultContexts = params.root === void 0 ? this.#browsingContextStorage.getTopLevelContexts() : [this.#browsingContextStorage.getContext(params.root)];
        return {
          contexts: resultContexts.map((c) => c.serializeToBidiValue(params.maxDepth ?? Number.MAX_VALUE))
        };
      }
      async create(params) {
        let referenceContext;
        let userContext = "default";
        if (params.referenceContext !== void 0) {
          referenceContext = this.#browsingContextStorage.getContext(params.referenceContext);
          if (!referenceContext.isTopLevelContext()) {
            throw new protocol_js_1.InvalidArgumentException(`referenceContext should be a top-level context`);
          }
          userContext = referenceContext.userContext;
        }
        if (params.userContext !== void 0) {
          userContext = params.userContext;
        }
        const existingContexts = this.#browsingContextStorage.getAllContexts().filter((context2) => context2.userContext === userContext);
        let newWindow = false;
        switch (params.type) {
          case "tab":
            newWindow = false;
            break;
          case "window":
            newWindow = true;
            break;
        }
        if (!existingContexts.length) {
          newWindow = true;
        }
        let result;
        try {
          result = await this.#browserCdpClient.sendCommand("Target.createTarget", {
            url: "about:blank",
            newWindow,
            browserContextId: userContext === "default" ? void 0 : userContext,
            background: params.background === true
          });
        } catch (err) {
          if (
            // See https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/devtools/protocol/target_handler.cc;l=90;drc=e80392ac11e48a691f4309964cab83a3a59e01c8
            err.message.startsWith("Failed to find browser context with id") || // See https://source.chromium.org/chromium/chromium/src/+/main:headless/lib/browser/protocol/target_handler.cc;l=49;drc=e80392ac11e48a691f4309964cab83a3a59e01c8
            err.message === "browserContextId"
          ) {
            throw new protocol_js_1.NoSuchUserContextException(`The context ${userContext} was not found`);
          }
          throw err;
        }
        const context = await this.#browsingContextStorage.waitForContext(result.targetId);
        await context.lifecycleLoaded();
        return { context: context.id };
      }
      navigate(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        return context.navigate(
          params.url,
          params.wait ?? "none"
          /* BrowsingContext.ReadinessState.None */
        );
      }
      reload(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        return context.reload(
          params.ignoreCache ?? false,
          params.wait ?? "none"
          /* BrowsingContext.ReadinessState.None */
        );
      }
      async activate(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        if (!context.isTopLevelContext()) {
          throw new protocol_js_1.InvalidArgumentException("Activation is only supported on the top-level context");
        }
        await context.activate();
        return {};
      }
      async captureScreenshot(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        return await context.captureScreenshot(params);
      }
      async print(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        return await context.print(params);
      }
      async setViewport(params) {
        const maxDimensionSize = 1e7;
        if ((params.viewport?.height ?? 0) > maxDimensionSize || (params.viewport?.width ?? 0) > maxDimensionSize) {
          throw new protocol_js_1.UnsupportedOperationException(`Viewport dimension over ${maxDimensionSize} are not supported`);
        }
        const config2 = {};
        if (params.devicePixelRatio !== void 0) {
          config2.devicePixelRatio = params.devicePixelRatio;
        }
        if (params.viewport !== void 0) {
          config2.viewport = params.viewport;
        }
        const impactedTopLevelContexts = await this.#getRelatedTopLevelBrowsingContexts(params.context, params.userContexts);
        for (const userContextId of params.userContexts ?? []) {
          this.#contextConfigStorage.updateUserContextConfig(userContextId, config2);
        }
        if (params.context !== void 0) {
          this.#contextConfigStorage.updateBrowsingContextConfig(params.context, config2);
        }
        await Promise.all(impactedTopLevelContexts.map(async (context) => {
          const config3 = this.#contextConfigStorage.getActiveConfig(context.id, context.userContext);
          await context.setViewport(config3.viewport ?? null, config3.devicePixelRatio ?? null, config3.screenOrientation ?? null);
        }));
        return {};
      }
      /**
       * Returns a list of top-level browsing context ids.
       */
      async #getRelatedTopLevelBrowsingContexts(browsingContextId, userContextIds) {
        if (browsingContextId === void 0 && userContextIds === void 0) {
          throw new protocol_js_1.InvalidArgumentException("Either userContexts or context must be provided");
        }
        if (browsingContextId !== void 0 && userContextIds !== void 0) {
          throw new protocol_js_1.InvalidArgumentException("userContexts and context are mutually exclusive");
        }
        if (browsingContextId !== void 0) {
          const context = this.#browsingContextStorage.getContext(browsingContextId);
          if (!context.isTopLevelContext()) {
            throw new protocol_js_1.InvalidArgumentException("Emulating viewport is only supported on the top-level context");
          }
          return [context];
        }
        await this.#userContextStorage.verifyUserContextIdList(userContextIds);
        const result = [];
        for (const userContextId of userContextIds) {
          const topLevelBrowsingContexts = this.#browsingContextStorage.getTopLevelContexts().filter((browsingContext) => browsingContext.userContext === userContextId);
          result.push(...topLevelBrowsingContexts);
        }
        return [...new Set(result).values()];
      }
      async traverseHistory(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        if (!context) {
          throw new protocol_js_1.InvalidArgumentException(`No browsing context with id ${params.context}`);
        }
        if (!context.isTopLevelContext()) {
          throw new protocol_js_1.InvalidArgumentException("Traversing history is only supported on the top-level context");
        }
        await context.traverseHistory(params.delta);
        return {};
      }
      async handleUserPrompt(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        try {
          await context.handleUserPrompt(params.accept, params.userText);
        } catch (error) {
          if (error.message?.includes("No dialog is showing")) {
            throw new protocol_js_1.NoSuchAlertException("No dialog is showing");
          }
          throw error;
        }
        return {};
      }
      async close(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        if (!context.isTopLevelContext()) {
          throw new protocol_js_1.InvalidArgumentException(`Non top-level browsing context ${context.id} cannot be closed.`);
        }
        const parentCdpClient = context.cdpTarget.parentCdpClient;
        try {
          const detachedFromTargetPromise = new Promise((resolve5) => {
            const onContextDestroyed = (event) => {
              if (event.targetId === params.context) {
                parentCdpClient.off("Target.detachedFromTarget", onContextDestroyed);
                resolve5();
              }
            };
            parentCdpClient.on("Target.detachedFromTarget", onContextDestroyed);
          });
          try {
            if (params.promptUnload) {
              await context.close();
            } else {
              await parentCdpClient.sendCommand("Target.closeTarget", {
                targetId: params.context
              });
            }
          } catch (error) {
            if (!parentCdpClient.isCloseError(error)) {
              throw error;
            }
          }
          await detachedFromTargetPromise;
        } catch (error) {
          if (!(error.code === -32e3 && error.message === "Not attached to an active page")) {
            throw error;
          }
        }
        return {};
      }
      async locateNodes(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        return await context.locateNodes(params);
      }
      #onContextCreatedSubscribeHook(contextId) {
        const context = this.#browsingContextStorage.getContext(contextId);
        const contextsToReport = [
          context,
          ...this.#browsingContextStorage.getContext(contextId).allChildren
        ];
        contextsToReport.forEach((context2) => {
          this.#eventManager.registerEvent({
            type: "event",
            method: protocol_js_1.ChromiumBidi.BrowsingContext.EventNames.ContextCreated,
            params: context2.serializeToBidiValue()
          }, context2.id);
        });
        return Promise.resolve();
      }
    };
    exports2.BrowsingContextProcessor = BrowsingContextProcessor;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/emulation/EmulationProcessor.js
var require_EmulationProcessor = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/emulation/EmulationProcessor.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.EmulationProcessor = void 0;
    exports2.isValidLocale = isValidLocale;
    exports2.isValidTimezone = isValidTimezone;
    exports2.isTimeZoneOffsetString = isTimeZoneOffsetString;
    var protocol_js_1 = require_protocol();
    var EmulationProcessor = class {
      #userContextStorage;
      #browsingContextStorage;
      #contextConfigStorage;
      constructor(browsingContextStorage, userContextStorage, contextConfigStorage) {
        this.#userContextStorage = userContextStorage;
        this.#browsingContextStorage = browsingContextStorage;
        this.#contextConfigStorage = contextConfigStorage;
      }
      async setGeolocationOverride(params) {
        if ("coordinates" in params && "error" in params) {
          throw new protocol_js_1.InvalidArgumentException("Coordinates and error cannot be set at the same time");
        }
        let geolocation = null;
        if ("coordinates" in params) {
          if ((params.coordinates?.altitude ?? null) === null && (params.coordinates?.altitudeAccuracy ?? null) !== null) {
            throw new protocol_js_1.InvalidArgumentException("Geolocation altitudeAccuracy can be set only with altitude");
          }
          geolocation = params.coordinates;
        } else if ("error" in params) {
          if (params.error.type !== "positionUnavailable") {
            throw new protocol_js_1.InvalidArgumentException(`Unknown geolocation error ${params.error.type}`);
          }
          geolocation = params.error;
        } else {
          throw new protocol_js_1.InvalidArgumentException(`Coordinates or error should be set`);
        }
        const browsingContexts = await this.#getRelatedTopLevelBrowsingContexts(params.contexts, params.userContexts);
        for (const browsingContextId of params.contexts ?? []) {
          this.#contextConfigStorage.updateBrowsingContextConfig(browsingContextId, {
            geolocation
          });
        }
        for (const userContextId of params.userContexts ?? []) {
          this.#contextConfigStorage.updateUserContextConfig(userContextId, {
            geolocation
          });
        }
        await Promise.all(browsingContexts.map(async (context) => {
          const config2 = this.#contextConfigStorage.getActiveConfig(context.id, context.userContext);
          await context.setGeolocationOverride(config2.geolocation ?? null);
        }));
        return {};
      }
      async setLocaleOverride(params) {
        const locale = params.locale ?? null;
        if (locale !== null && !isValidLocale(locale)) {
          throw new protocol_js_1.InvalidArgumentException(`Invalid locale "${locale}"`);
        }
        const browsingContexts = await this.#getRelatedTopLevelBrowsingContexts(params.contexts, params.userContexts);
        for (const browsingContextId of params.contexts ?? []) {
          this.#contextConfigStorage.updateBrowsingContextConfig(browsingContextId, {
            locale
          });
        }
        for (const userContextId of params.userContexts ?? []) {
          this.#contextConfigStorage.updateUserContextConfig(userContextId, {
            locale
          });
        }
        await Promise.all(browsingContexts.map(async (context) => {
          const config2 = this.#contextConfigStorage.getActiveConfig(context.id, context.userContext);
          await Promise.all([
            context.setLocaleOverride(config2.locale ?? null),
            // Set `AcceptLanguage` to locale.
            context.setUserAgentAndAcceptLanguage(config2.userAgent, config2.locale, config2.clientHints)
          ]);
        }));
        return {};
      }
      async setScriptingEnabled(params) {
        const scriptingEnabled = params.enabled;
        const browsingContexts = await this.#getRelatedTopLevelBrowsingContexts(params.contexts, params.userContexts);
        for (const browsingContextId of params.contexts ?? []) {
          this.#contextConfigStorage.updateBrowsingContextConfig(browsingContextId, {
            scriptingEnabled
          });
        }
        for (const userContextId of params.userContexts ?? []) {
          this.#contextConfigStorage.updateUserContextConfig(userContextId, {
            scriptingEnabled
          });
        }
        await Promise.all(browsingContexts.map(async (context) => {
          const config2 = this.#contextConfigStorage.getActiveConfig(context.id, context.userContext);
          await context.setScriptingEnabled(config2.scriptingEnabled ?? null);
        }));
        return {};
      }
      async setScreenOrientationOverride(params) {
        const browsingContexts = await this.#getRelatedTopLevelBrowsingContexts(params.contexts, params.userContexts);
        for (const browsingContextId of params.contexts ?? []) {
          this.#contextConfigStorage.updateBrowsingContextConfig(browsingContextId, {
            screenOrientation: params.screenOrientation
          });
        }
        for (const userContextId of params.userContexts ?? []) {
          this.#contextConfigStorage.updateUserContextConfig(userContextId, {
            screenOrientation: params.screenOrientation
          });
        }
        await Promise.all(browsingContexts.map(async (context) => {
          const config2 = this.#contextConfigStorage.getActiveConfig(context.id, context.userContext);
          await context.setViewport(config2.viewport ?? null, config2.devicePixelRatio ?? null, config2.screenOrientation ?? null);
        }));
        return {};
      }
      async setScreenSettingsOverride(params) {
        const browsingContexts = await this.#getRelatedTopLevelBrowsingContexts(params.contexts, params.userContexts);
        for (const browsingContextId of params.contexts ?? []) {
          this.#contextConfigStorage.updateBrowsingContextConfig(browsingContextId, {
            screenArea: params.screenArea
          });
        }
        for (const userContextId of params.userContexts ?? []) {
          this.#contextConfigStorage.updateUserContextConfig(userContextId, {
            screenArea: params.screenArea
          });
        }
        await Promise.all(browsingContexts.map(async (context) => {
          const config2 = this.#contextConfigStorage.getActiveConfig(context.id, context.userContext);
          await context.setViewport(config2.viewport ?? null, config2.devicePixelRatio ?? null, config2.screenOrientation ?? null);
        }));
        return {};
      }
      /**
       * Returns a list of top-level browsing contexts.
       */
      async #getRelatedTopLevelBrowsingContexts(browsingContextIds, userContextIds, allowGlobal = false) {
        if (browsingContextIds === void 0 && userContextIds === void 0) {
          if (allowGlobal) {
            return this.#browsingContextStorage.getTopLevelContexts();
          }
          throw new protocol_js_1.InvalidArgumentException("Either user contexts or browsing contexts must be provided");
        }
        if (browsingContextIds !== void 0 && userContextIds !== void 0) {
          throw new protocol_js_1.InvalidArgumentException("User contexts and browsing contexts are mutually exclusive");
        }
        const result = [];
        if (browsingContextIds === void 0) {
          if (userContextIds.length === 0) {
            throw new protocol_js_1.InvalidArgumentException("user context should be provided");
          }
          await this.#userContextStorage.verifyUserContextIdList(userContextIds);
          for (const userContextId of userContextIds) {
            const topLevelBrowsingContexts = this.#browsingContextStorage.getTopLevelContexts().filter((browsingContext) => browsingContext.userContext === userContextId);
            result.push(...topLevelBrowsingContexts);
          }
        } else {
          if (browsingContextIds.length === 0) {
            throw new protocol_js_1.InvalidArgumentException("browsing context should be provided");
          }
          for (const browsingContextId of browsingContextIds) {
            const browsingContext = this.#browsingContextStorage.getContext(browsingContextId);
            if (!browsingContext.isTopLevelContext()) {
              throw new protocol_js_1.InvalidArgumentException("The command is only supported on the top-level context");
            }
            result.push(browsingContext);
          }
        }
        return [...new Set(result).values()];
      }
      async setTimezoneOverride(params) {
        let timezone = params.timezone ?? null;
        if (timezone !== null && !isValidTimezone(timezone)) {
          throw new protocol_js_1.InvalidArgumentException(`Invalid timezone "${timezone}"`);
        }
        if (timezone !== null && isTimeZoneOffsetString(timezone)) {
          timezone = `GMT${timezone}`;
        }
        const browsingContexts = await this.#getRelatedTopLevelBrowsingContexts(params.contexts, params.userContexts);
        for (const browsingContextId of params.contexts ?? []) {
          this.#contextConfigStorage.updateBrowsingContextConfig(browsingContextId, {
            timezone
          });
        }
        for (const userContextId of params.userContexts ?? []) {
          this.#contextConfigStorage.updateUserContextConfig(userContextId, {
            timezone
          });
        }
        await Promise.all(browsingContexts.map(async (context) => {
          const config2 = this.#contextConfigStorage.getActiveConfig(context.id, context.userContext);
          await context.setTimezoneOverride(config2.timezone ?? null);
        }));
        return {};
      }
      async setTouchOverride(params) {
        const maxTouchPoints = params.maxTouchPoints;
        const browsingContexts = await this.#getRelatedTopLevelBrowsingContexts(params.contexts, params.userContexts, true);
        for (const browsingContextId of params.contexts ?? []) {
          this.#contextConfigStorage.updateBrowsingContextConfig(browsingContextId, {
            maxTouchPoints
          });
        }
        for (const userContextId of params.userContexts ?? []) {
          this.#contextConfigStorage.updateUserContextConfig(userContextId, {
            maxTouchPoints
          });
        }
        if (params.contexts === void 0 && params.userContexts === void 0) {
          this.#contextConfigStorage.updateGlobalConfig({
            maxTouchPoints
          });
        }
        await Promise.all(browsingContexts.map(async (context) => {
          const config2 = this.#contextConfigStorage.getActiveConfig(context.id, context.userContext);
          await context.setTouchOverride(config2.maxTouchPoints ?? null);
        }));
        return {};
      }
      async setUserAgentOverrideParams(params) {
        if (params.userAgent === "") {
          throw new protocol_js_1.UnsupportedOperationException("empty user agent string is not supported");
        }
        const browsingContexts = await this.#getRelatedTopLevelBrowsingContexts(params.contexts, params.userContexts, true);
        for (const browsingContextId of params.contexts ?? []) {
          this.#contextConfigStorage.updateBrowsingContextConfig(browsingContextId, {
            userAgent: params.userAgent
          });
        }
        for (const userContextId of params.userContexts ?? []) {
          this.#contextConfigStorage.updateUserContextConfig(userContextId, {
            userAgent: params.userAgent
          });
        }
        if (params.contexts === void 0 && params.userContexts === void 0) {
          this.#contextConfigStorage.updateGlobalConfig({
            userAgent: params.userAgent
          });
        }
        await Promise.all(browsingContexts.map(async (context) => {
          const config2 = this.#contextConfigStorage.getActiveConfig(context.id, context.userContext);
          await context.setUserAgentAndAcceptLanguage(config2.userAgent, config2.locale, config2.clientHints);
        }));
        return {};
      }
      async setClientHintsOverride(params) {
        const clientHints = params.clientHints ?? null;
        const browsingContexts = await this.#getRelatedTopLevelBrowsingContexts(params.contexts, params.userContexts, true);
        for (const browsingContextId of params.contexts ?? []) {
          this.#contextConfigStorage.updateBrowsingContextConfig(browsingContextId, {
            clientHints
          });
        }
        for (const userContextId of params.userContexts ?? []) {
          this.#contextConfigStorage.updateUserContextConfig(userContextId, {
            clientHints
          });
        }
        if (params.contexts === void 0 && params.userContexts === void 0) {
          this.#contextConfigStorage.updateGlobalConfig({
            clientHints
          });
        }
        await Promise.all(browsingContexts.map(async (context) => {
          const config2 = this.#contextConfigStorage.getActiveConfig(context.id, context.userContext);
          await context.setUserAgentAndAcceptLanguage(config2.userAgent, config2.locale, config2.clientHints);
        }));
        return {};
      }
      async setNetworkConditions(params) {
        const browsingContexts = await this.#getRelatedTopLevelBrowsingContexts(params.contexts, params.userContexts, true);
        for (const browsingContextId of params.contexts ?? []) {
          this.#contextConfigStorage.updateBrowsingContextConfig(browsingContextId, {
            emulatedNetworkConditions: params.networkConditions
          });
        }
        for (const userContextId of params.userContexts ?? []) {
          this.#contextConfigStorage.updateUserContextConfig(userContextId, {
            emulatedNetworkConditions: params.networkConditions
          });
        }
        if (params.contexts === void 0 && params.userContexts === void 0) {
          this.#contextConfigStorage.updateGlobalConfig({
            emulatedNetworkConditions: params.networkConditions
          });
        }
        if (params.networkConditions !== null && params.networkConditions.type !== "offline") {
          throw new protocol_js_1.UnsupportedOperationException(`Unsupported network conditions ${params.networkConditions.type}`);
        }
        await Promise.all(browsingContexts.map(async (context) => {
          const config2 = this.#contextConfigStorage.getActiveConfig(context.id, context.userContext);
          await context.setEmulatedNetworkConditions(config2.emulatedNetworkConditions ?? null);
        }));
        return {};
      }
    };
    exports2.EmulationProcessor = EmulationProcessor;
    function isValidLocale(locale) {
      try {
        new Intl.Locale(locale);
        return true;
      } catch (e) {
        if (e instanceof RangeError) {
          return false;
        }
        throw e;
      }
    }
    function isValidTimezone(timezone) {
      try {
        Intl.DateTimeFormat(void 0, { timeZone: timezone });
        return true;
      } catch (e) {
        if (e instanceof RangeError) {
          return false;
        }
        throw e;
      }
    }
    function isTimeZoneOffsetString(timezone) {
      return /^[+-](?:2[0-3]|[01]\d)(?::[0-5]\d)?$/.test(timezone);
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/utils/assert.js
var require_assert2 = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/utils/assert.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.assert = assert;
    function assert(predicate, message) {
      if (!predicate) {
        throw new Error(message ?? "Internal assertion failed.");
      }
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/utils/graphemeTools.js
var require_graphemeTools = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/utils/graphemeTools.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isSingleComplexGrapheme = isSingleComplexGrapheme;
    exports2.isSingleGrapheme = isSingleGrapheme;
    function isSingleComplexGrapheme(value) {
      return isSingleGrapheme(value) && value.length > 1;
    }
    function isSingleGrapheme(value) {
      const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
      return [...segmenter.segment(value)].length === 1;
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/input/InputSource.js
var require_InputSource = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/input/InputSource.js"(exports2) {
    "use strict";
    init_prefix();
    var _a2;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.WheelSource = exports2.PointerSource = exports2.KeySource = exports2.NoneSource = void 0;
    var NoneSource = class {
      type = "none";
    };
    exports2.NoneSource = NoneSource;
    var KeySource = class {
      type = "key";
      pressed = /* @__PURE__ */ new Set();
      // This is a bitfield that matches the modifiers parameter of
      // https://chromedevtools.github.io/devtools-protocol/tot/Input/#method-dispatchKeyEvent
      #modifiers = 0;
      get modifiers() {
        return this.#modifiers;
      }
      get alt() {
        return (this.#modifiers & 1) === 1;
      }
      set alt(value) {
        this.#setModifier(value, 1);
      }
      get ctrl() {
        return (this.#modifiers & 2) === 2;
      }
      set ctrl(value) {
        this.#setModifier(value, 2);
      }
      get meta() {
        return (this.#modifiers & 4) === 4;
      }
      set meta(value) {
        this.#setModifier(value, 4);
      }
      get shift() {
        return (this.#modifiers & 8) === 8;
      }
      set shift(value) {
        this.#setModifier(value, 8);
      }
      #setModifier(value, bit) {
        if (value) {
          this.#modifiers |= bit;
        } else {
          this.#modifiers &= ~bit;
        }
      }
    };
    exports2.KeySource = KeySource;
    var PointerSource = class {
      type = "pointer";
      subtype;
      pointerId;
      pressed = /* @__PURE__ */ new Set();
      x = 0;
      y = 0;
      radiusX;
      radiusY;
      force;
      constructor(id, subtype) {
        this.pointerId = id;
        this.subtype = subtype;
      }
      // This is a bitfield that matches the buttons parameter of
      // https://chromedevtools.github.io/devtools-protocol/tot/Input/#method-dispatchMouseEvent
      get buttons() {
        let buttons = 0;
        for (const button of this.pressed) {
          switch (button) {
            case 0:
              buttons |= 1;
              break;
            case 1:
              buttons |= 4;
              break;
            case 2:
              buttons |= 2;
              break;
            case 3:
              buttons |= 8;
              break;
            case 4:
              buttons |= 16;
              break;
          }
        }
        return buttons;
      }
      // --- Platform-specific code starts here ---
      // Input.dispatchMouseEvent doesn't know the concept of double click, so we
      // need to create the logic, similar to how it's done for OSes:
      // https://source.chromium.org/chromium/chromium/src/+/refs/heads/main:ui/events/event.cc;l=479
      static ClickContext = class ClickContext {
        static #DOUBLE_CLICK_TIME_MS = 500;
        static #MAX_DOUBLE_CLICK_RADIUS = 2;
        count = 0;
        #x;
        #y;
        #time;
        constructor(x, y, time) {
          this.#x = x;
          this.#y = y;
          this.#time = time;
        }
        compare(context) {
          return (
            // The click needs to be within a certain amount of ms.
            context.#time - this.#time > ClickContext.#DOUBLE_CLICK_TIME_MS || // The click needs to be within a certain square radius.
            Math.abs(context.#x - this.#x) > ClickContext.#MAX_DOUBLE_CLICK_RADIUS || Math.abs(context.#y - this.#y) > ClickContext.#MAX_DOUBLE_CLICK_RADIUS
          );
        }
      };
      #clickContexts = /* @__PURE__ */ new Map();
      setClickCount(button, context) {
        let storedContext = this.#clickContexts.get(button);
        if (!storedContext || storedContext.compare(context)) {
          storedContext = context;
        }
        ++storedContext.count;
        this.#clickContexts.set(button, storedContext);
        return storedContext.count;
      }
      getClickCount(button) {
        return this.#clickContexts.get(button)?.count ?? 0;
      }
      /**
       * Resets click count. Resets consequent click counter. Prevents grouping clicks in
       * different `performActions` calls, so that they are not grouped as double, triple etc
       * clicks. Required for https://github.com/GoogleChromeLabs/chromium-bidi/issues/3043.
       */
      resetClickCount() {
        this.#clickContexts = /* @__PURE__ */ new Map();
      }
    };
    exports2.PointerSource = PointerSource;
    _a2 = PointerSource;
    var WheelSource = class {
      type = "wheel";
    };
    exports2.WheelSource = WheelSource;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/input/keyUtils.js
var require_keyUtils = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/input/keyUtils.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getNormalizedKey = getNormalizedKey;
    exports2.getKeyCode = getKeyCode;
    exports2.getKeyLocation = getKeyLocation;
    function getNormalizedKey(value) {
      switch (value) {
        case "\uE000":
          return "Unidentified";
        case "\uE001":
          return "Cancel";
        case "\uE002":
          return "Help";
        case "\uE003":
          return "Backspace";
        case "\uE004":
          return "Tab";
        case "\uE005":
          return "Clear";
        // Specification declares the '\uE006' to be `Return`, but it is not supported by
        // Chrome, so fall back to `Enter`, which aligns with WPT.
        case "\uE006":
        case "\uE007":
          return "Enter";
        case "\uE008":
          return "Shift";
        case "\uE009":
          return "Control";
        case "\uE00A":
          return "Alt";
        case "\uE00B":
          return "Pause";
        case "\uE00C":
          return "Escape";
        case "\uE00D":
          return " ";
        case "\uE00E":
          return "PageUp";
        case "\uE00F":
          return "PageDown";
        case "\uE010":
          return "End";
        case "\uE011":
          return "Home";
        case "\uE012":
          return "ArrowLeft";
        case "\uE013":
          return "ArrowUp";
        case "\uE014":
          return "ArrowRight";
        case "\uE015":
          return "ArrowDown";
        case "\uE016":
          return "Insert";
        case "\uE017":
          return "Delete";
        case "\uE018":
          return ";";
        case "\uE019":
          return "=";
        case "\uE01A":
          return "0";
        case "\uE01B":
          return "1";
        case "\uE01C":
          return "2";
        case "\uE01D":
          return "3";
        case "\uE01E":
          return "4";
        case "\uE01F":
          return "5";
        case "\uE020":
          return "6";
        case "\uE021":
          return "7";
        case "\uE022":
          return "8";
        case "\uE023":
          return "9";
        case "\uE024":
          return "*";
        case "\uE025":
          return "+";
        case "\uE026":
          return ",";
        case "\uE027":
          return "-";
        case "\uE028":
          return ".";
        case "\uE029":
          return "/";
        case "\uE031":
          return "F1";
        case "\uE032":
          return "F2";
        case "\uE033":
          return "F3";
        case "\uE034":
          return "F4";
        case "\uE035":
          return "F5";
        case "\uE036":
          return "F6";
        case "\uE037":
          return "F7";
        case "\uE038":
          return "F8";
        case "\uE039":
          return "F9";
        case "\uE03A":
          return "F10";
        case "\uE03B":
          return "F11";
        case "\uE03C":
          return "F12";
        case "\uE03D":
          return "Meta";
        case "\uE040":
          return "ZenkakuHankaku";
        case "\uE050":
          return "Shift";
        case "\uE051":
          return "Control";
        case "\uE052":
          return "Alt";
        case "\uE053":
          return "Meta";
        case "\uE054":
          return "PageUp";
        case "\uE055":
          return "PageDown";
        case "\uE056":
          return "End";
        case "\uE057":
          return "Home";
        case "\uE058":
          return "ArrowLeft";
        case "\uE059":
          return "ArrowUp";
        case "\uE05A":
          return "ArrowRight";
        case "\uE05B":
          return "ArrowDown";
        case "\uE05C":
          return "Insert";
        case "\uE05D":
          return "Delete";
        default:
          return value;
      }
    }
    function getKeyCode(key) {
      switch (key) {
        case "`":
        case "~":
          return "Backquote";
        case "\\":
        case "|":
          return "Backslash";
        case "\uE003":
          return "Backspace";
        case "[":
        case "{":
          return "BracketLeft";
        case "]":
        case "}":
          return "BracketRight";
        case ",":
        case "<":
          return "Comma";
        case "0":
        case ")":
          return "Digit0";
        case "1":
        case "!":
          return "Digit1";
        case "2":
        case "@":
          return "Digit2";
        case "3":
        case "#":
          return "Digit3";
        case "4":
        case "$":
          return "Digit4";
        case "5":
        case "%":
          return "Digit5";
        case "6":
        case "^":
          return "Digit6";
        case "7":
        case "&":
          return "Digit7";
        case "8":
        case "*":
          return "Digit8";
        case "9":
        case "(":
          return "Digit9";
        case "=":
        case "+":
          return "Equal";
        // The spec declares the '<' to be `IntlBackslash` as well, but it is already covered
        // in the `Comma` above.
        case ">":
          return "IntlBackslash";
        case "a":
        case "A":
          return "KeyA";
        case "b":
        case "B":
          return "KeyB";
        case "c":
        case "C":
          return "KeyC";
        case "d":
        case "D":
          return "KeyD";
        case "e":
        case "E":
          return "KeyE";
        case "f":
        case "F":
          return "KeyF";
        case "g":
        case "G":
          return "KeyG";
        case "h":
        case "H":
          return "KeyH";
        case "i":
        case "I":
          return "KeyI";
        case "j":
        case "J":
          return "KeyJ";
        case "k":
        case "K":
          return "KeyK";
        case "l":
        case "L":
          return "KeyL";
        case "m":
        case "M":
          return "KeyM";
        case "n":
        case "N":
          return "KeyN";
        case "o":
        case "O":
          return "KeyO";
        case "p":
        case "P":
          return "KeyP";
        case "q":
        case "Q":
          return "KeyQ";
        case "r":
        case "R":
          return "KeyR";
        case "s":
        case "S":
          return "KeyS";
        case "t":
        case "T":
          return "KeyT";
        case "u":
        case "U":
          return "KeyU";
        case "v":
        case "V":
          return "KeyV";
        case "w":
        case "W":
          return "KeyW";
        case "x":
        case "X":
          return "KeyX";
        case "y":
        case "Y":
          return "KeyY";
        case "z":
        case "Z":
          return "KeyZ";
        case "-":
        case "_":
          return "Minus";
        case ".":
          return "Period";
        case "'":
        case '"':
          return "Quote";
        case ";":
        case ":":
          return "Semicolon";
        case "/":
        case "?":
          return "Slash";
        case "\uE00A":
          return "AltLeft";
        case "\uE052":
          return "AltRight";
        case "\uE009":
          return "ControlLeft";
        case "\uE051":
          return "ControlRight";
        case "\uE006":
          return "Enter";
        case "\uE00B":
          return "Pause";
        case "\uE03D":
          return "MetaLeft";
        case "\uE053":
          return "MetaRight";
        case "\uE008":
          return "ShiftLeft";
        case "\uE050":
          return "ShiftRight";
        case " ":
        case "\uE00D":
          return "Space";
        case "\uE004":
          return "Tab";
        case "\uE017":
          return "Delete";
        case "\uE010":
          return "End";
        case "\uE002":
          return "Help";
        case "\uE011":
          return "Home";
        case "\uE016":
          return "Insert";
        case "\uE00F":
          return "PageDown";
        case "\uE00E":
          return "PageUp";
        case "\uE015":
          return "ArrowDown";
        case "\uE012":
          return "ArrowLeft";
        case "\uE014":
          return "ArrowRight";
        case "\uE013":
          return "ArrowUp";
        case "\uE00C":
          return "Escape";
        case "\uE031":
          return "F1";
        case "\uE032":
          return "F2";
        case "\uE033":
          return "F3";
        case "\uE034":
          return "F4";
        case "\uE035":
          return "F5";
        case "\uE036":
          return "F6";
        case "\uE037":
          return "F7";
        case "\uE038":
          return "F8";
        case "\uE039":
          return "F9";
        case "\uE03A":
          return "F10";
        case "\uE03B":
          return "F11";
        case "\uE03C":
          return "F12";
        case "\uE019":
          return "NumpadEqual";
        case "\uE01A":
        case "\uE05C":
          return "Numpad0";
        case "\uE01B":
        case "\uE056":
          return "Numpad1";
        case "\uE01C":
        case "\uE05B":
          return "Numpad2";
        case "\uE01D":
        case "\uE055":
          return "Numpad3";
        case "\uE01E":
        case "\uE058":
          return "Numpad4";
        case "\uE01F":
          return "Numpad5";
        case "\uE020":
        case "\uE05A":
          return "Numpad6";
        case "\uE021":
        case "\uE057":
          return "Numpad7";
        case "\uE022":
        case "\uE059":
          return "Numpad8";
        case "\uE023":
        case "\uE054":
          return "Numpad9";
        case "\uE025":
          return "NumpadAdd";
        case "\uE026":
          return "NumpadComma";
        case "\uE028":
        case "\uE05D":
          return "NumpadDecimal";
        case "\uE029":
          return "NumpadDivide";
        case "\uE007":
          return "NumpadEnter";
        case "\uE024":
          return "NumpadMultiply";
        case "\uE027":
          return "NumpadSubtract";
        default:
          return;
      }
    }
    function getKeyLocation(key) {
      switch (key) {
        case "\uE007":
        case "\uE008":
        case "\uE009":
        case "\uE00A":
        case "\uE03D":
          return 1;
        case "\uE019":
        case "\uE01A":
        case "\uE01B":
        case "\uE01C":
        case "\uE01D":
        case "\uE01E":
        case "\uE01F":
        case "\uE020":
        case "\uE021":
        case "\uE022":
        case "\uE023":
        case "\uE024":
        case "\uE025":
        case "\uE026":
        case "\uE027":
        case "\uE028":
        case "\uE029":
        case "\uE054":
        case "\uE055":
        case "\uE056":
        case "\uE057":
        case "\uE058":
        case "\uE059":
        case "\uE05A":
        case "\uE05B":
        case "\uE05C":
        case "\uE05D":
          return 3;
        case "\uE050":
        case "\uE051":
        case "\uE052":
        case "\uE053":
          return 2;
        default:
          return 0;
      }
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/input/USKeyboardLayout.js
var require_USKeyboardLayout2 = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/input/USKeyboardLayout.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.KeyToKeyCode = void 0;
    exports2.KeyToKeyCode = {
      "0": 48,
      "1": 49,
      "2": 50,
      "3": 51,
      "4": 52,
      "5": 53,
      "6": 54,
      "7": 55,
      "8": 56,
      "9": 57,
      Abort: 3,
      Help: 6,
      Backspace: 8,
      Tab: 9,
      Numpad5: 12,
      NumpadEnter: 13,
      Enter: 13,
      "\\r": 13,
      "\\n": 13,
      ShiftLeft: 16,
      ShiftRight: 16,
      ControlLeft: 17,
      ControlRight: 17,
      AltLeft: 18,
      AltRight: 18,
      Pause: 19,
      CapsLock: 20,
      Escape: 27,
      Convert: 28,
      NonConvert: 29,
      Space: 32,
      Numpad9: 33,
      PageUp: 33,
      Numpad3: 34,
      PageDown: 34,
      End: 35,
      Numpad1: 35,
      Home: 36,
      Numpad7: 36,
      ArrowLeft: 37,
      Numpad4: 37,
      Numpad8: 38,
      ArrowUp: 38,
      ArrowRight: 39,
      Numpad6: 39,
      Numpad2: 40,
      ArrowDown: 40,
      Select: 41,
      Open: 43,
      PrintScreen: 44,
      Insert: 45,
      Numpad0: 45,
      Delete: 46,
      NumpadDecimal: 46,
      Digit0: 48,
      Digit1: 49,
      Digit2: 50,
      Digit3: 51,
      Digit4: 52,
      Digit5: 53,
      Digit6: 54,
      Digit7: 55,
      Digit8: 56,
      Digit9: 57,
      KeyA: 65,
      KeyB: 66,
      KeyC: 67,
      KeyD: 68,
      KeyE: 69,
      KeyF: 70,
      KeyG: 71,
      KeyH: 72,
      KeyI: 73,
      KeyJ: 74,
      KeyK: 75,
      KeyL: 76,
      KeyM: 77,
      KeyN: 78,
      KeyO: 79,
      KeyP: 80,
      KeyQ: 81,
      KeyR: 82,
      KeyS: 83,
      KeyT: 84,
      KeyU: 85,
      KeyV: 86,
      KeyW: 87,
      KeyX: 88,
      KeyY: 89,
      KeyZ: 90,
      MetaLeft: 91,
      MetaRight: 92,
      ContextMenu: 93,
      NumpadMultiply: 106,
      NumpadAdd: 107,
      NumpadSubtract: 109,
      NumpadDivide: 111,
      F1: 112,
      F2: 113,
      F3: 114,
      F4: 115,
      F5: 116,
      F6: 117,
      F7: 118,
      F8: 119,
      F9: 120,
      F10: 121,
      F11: 122,
      F12: 123,
      F13: 124,
      F14: 125,
      F15: 126,
      F16: 127,
      F17: 128,
      F18: 129,
      F19: 130,
      F20: 131,
      F21: 132,
      F22: 133,
      F23: 134,
      F24: 135,
      NumLock: 144,
      ScrollLock: 145,
      AudioVolumeMute: 173,
      AudioVolumeDown: 174,
      AudioVolumeUp: 175,
      MediaTrackNext: 176,
      MediaTrackPrevious: 177,
      MediaStop: 178,
      MediaPlayPause: 179,
      Semicolon: 186,
      Equal: 187,
      NumpadEqual: 187,
      Comma: 188,
      Minus: 189,
      Period: 190,
      Slash: 191,
      Backquote: 192,
      BracketLeft: 219,
      Backslash: 220,
      BracketRight: 221,
      Quote: 222,
      AltGraph: 225,
      Props: 247,
      Cancel: 3,
      Clear: 12,
      Shift: 16,
      Control: 17,
      Alt: 18,
      Accept: 30,
      ModeChange: 31,
      " ": 32,
      Print: 42,
      Execute: 43,
      "\\u0000": 46,
      a: 65,
      b: 66,
      c: 67,
      d: 68,
      e: 69,
      f: 70,
      g: 71,
      h: 72,
      i: 73,
      j: 74,
      k: 75,
      l: 76,
      m: 77,
      n: 78,
      o: 79,
      p: 80,
      q: 81,
      r: 82,
      s: 83,
      t: 84,
      u: 85,
      v: 86,
      w: 87,
      x: 88,
      y: 89,
      z: 90,
      Meta: 91,
      "*": 106,
      "+": 107,
      "-": 109,
      "/": 111,
      ";": 186,
      "=": 187,
      ",": 188,
      ".": 190,
      "`": 192,
      "[": 219,
      "\\\\": 220,
      "]": 221,
      "'": 222,
      Attn: 246,
      CrSel: 247,
      ExSel: 248,
      EraseEof: 249,
      Play: 250,
      ZoomOut: 251,
      ")": 48,
      "!": 49,
      "@": 50,
      "#": 51,
      $: 52,
      "%": 53,
      "^": 54,
      "&": 55,
      "(": 57,
      A: 65,
      B: 66,
      C: 67,
      D: 68,
      E: 69,
      F: 70,
      G: 71,
      H: 72,
      I: 73,
      J: 74,
      K: 75,
      L: 76,
      M: 77,
      N: 78,
      O: 79,
      P: 80,
      Q: 81,
      R: 82,
      S: 83,
      T: 84,
      U: 85,
      V: 86,
      W: 87,
      X: 88,
      Y: 89,
      Z: 90,
      ":": 186,
      "<": 188,
      _: 189,
      ">": 190,
      "?": 191,
      "~": 192,
      "{": 219,
      "|": 220,
      "}": 221,
      '"': 222,
      Camera: 44,
      EndCall: 95,
      VolumeDown: 182,
      VolumeUp: 183
    };
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/input/ActionDispatcher.js
var require_ActionDispatcher = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/input/ActionDispatcher.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ActionDispatcher = void 0;
    var protocol_js_1 = require_protocol();
    var assert_js_1 = require_assert2();
    var graphemeTools_js_1 = require_graphemeTools();
    var InputSource_js_1 = require_InputSource();
    var keyUtils_js_1 = require_keyUtils();
    var USKeyboardLayout_js_1 = require_USKeyboardLayout2();
    var CALCULATE_IN_VIEW_CENTER_PT_DECL = ((i) => {
      const t = i.getClientRects()[0], e = Math.max(0, Math.min(t.x, t.x + t.width)), n = Math.min(window.innerWidth, Math.max(t.x, t.x + t.width)), h = Math.max(0, Math.min(t.y, t.y + t.height)), m = Math.min(window.innerHeight, Math.max(t.y, t.y + t.height));
      return [e + (n - e >> 1), h + (m - h >> 1)];
    }).toString();
    var IS_MAC_DECL = (() => {
      return navigator.platform.toLowerCase().includes("mac");
    }).toString();
    async function getElementCenter(context, element) {
      const hiddenSandboxRealm = await context.getOrCreateHiddenSandbox();
      const result = await hiddenSandboxRealm.callFunction(CALCULATE_IN_VIEW_CENTER_PT_DECL, false, { type: "undefined" }, [element]);
      if (result.type === "exception") {
        throw new protocol_js_1.NoSuchElementException(`Origin element ${element.sharedId} was not found`);
      }
      (0, assert_js_1.assert)(result.result.type === "array");
      (0, assert_js_1.assert)(result.result.value?.[0]?.type === "number");
      (0, assert_js_1.assert)(result.result.value?.[1]?.type === "number");
      const { result: { value: [{ value: x }, { value: y }] } } = result;
      return { x, y };
    }
    var ActionDispatcher = class {
      static isMacOS = async (context) => {
        const hiddenSandboxRealm = await context.getOrCreateHiddenSandbox();
        const result = await hiddenSandboxRealm.callFunction(IS_MAC_DECL, false);
        (0, assert_js_1.assert)(result.type !== "exception");
        (0, assert_js_1.assert)(result.result.type === "boolean");
        return result.result.value;
      };
      #browsingContextStorage;
      #tickStart = 0;
      #tickDuration = 0;
      #inputState;
      #contextId;
      #isMacOS;
      constructor(inputState, browsingContextStorage, contextId, isMacOS) {
        this.#browsingContextStorage = browsingContextStorage;
        this.#inputState = inputState;
        this.#contextId = contextId;
        this.#isMacOS = isMacOS;
      }
      /**
       * The context can be disposed between action ticks, so need to get it each time.
       */
      get #context() {
        return this.#browsingContextStorage.getContext(this.#contextId);
      }
      async dispatchActions(optionsByTick) {
        await this.#inputState.queue.run(async () => {
          for (const options of optionsByTick) {
            await this.dispatchTickActions(options);
          }
        });
      }
      async dispatchTickActions(options) {
        this.#tickStart = performance.now();
        this.#tickDuration = 0;
        for (const { action } of options) {
          if ("duration" in action && action.duration !== void 0) {
            this.#tickDuration = Math.max(this.#tickDuration, action.duration);
          }
        }
        const promises = [
          new Promise((resolve5) => setTimeout(resolve5, this.#tickDuration))
        ];
        for (const option of options) {
          promises.push(this.#dispatchAction(option));
        }
        await Promise.all(promises);
      }
      async #dispatchAction({ id, action }) {
        const source = this.#inputState.get(id);
        const keyState = this.#inputState.getGlobalKeyState();
        switch (action.type) {
          case "keyDown": {
            await this.#dispatchKeyDownAction(source, action);
            this.#inputState.cancelList.push({
              id,
              action: {
                ...action,
                type: "keyUp"
              }
            });
            break;
          }
          case "keyUp": {
            await this.#dispatchKeyUpAction(source, action);
            break;
          }
          case "pause": {
            break;
          }
          case "pointerDown": {
            await this.#dispatchPointerDownAction(source, keyState, action);
            this.#inputState.cancelList.push({
              id,
              action: {
                ...action,
                type: "pointerUp"
              }
            });
            break;
          }
          case "pointerMove": {
            await this.#dispatchPointerMoveAction(source, keyState, action);
            break;
          }
          case "pointerUp": {
            await this.#dispatchPointerUpAction(source, keyState, action);
            break;
          }
          case "scroll": {
            await this.#dispatchScrollAction(source, keyState, action);
            break;
          }
        }
      }
      async #dispatchPointerDownAction(source, keyState, action) {
        const { button } = action;
        if (source.pressed.has(button)) {
          return;
        }
        source.pressed.add(button);
        const { x, y, subtype: pointerType } = source;
        const { width, height, pressure, twist, tangentialPressure } = action;
        const { tiltX, tiltY } = getTilt(action);
        const { modifiers } = keyState;
        const { radiusX, radiusY } = getRadii(width ?? 1, height ?? 1);
        switch (pointerType) {
          case "mouse":
          case "pen":
            await this.#context.cdpTarget.cdpClient.sendCommand("Input.dispatchMouseEvent", {
              type: "mousePressed",
              x,
              y,
              modifiers,
              button: getCdpButton(button),
              buttons: source.buttons,
              clickCount: source.setClickCount(button, new InputSource_js_1.PointerSource.ClickContext(x, y, performance.now())),
              pointerType,
              tangentialPressure,
              tiltX,
              tiltY,
              twist,
              force: pressure
            });
            break;
          case "touch":
            await this.#context.cdpTarget.cdpClient.sendCommand("Input.dispatchTouchEvent", {
              type: "touchStart",
              touchPoints: [
                {
                  x,
                  y,
                  radiusX,
                  radiusY,
                  tangentialPressure,
                  tiltX,
                  tiltY,
                  twist,
                  force: pressure,
                  id: source.pointerId
                }
              ],
              modifiers
            });
            break;
        }
        source.radiusX = radiusX;
        source.radiusY = radiusY;
        source.force = pressure;
      }
      #dispatchPointerUpAction(source, keyState, action) {
        const { button } = action;
        if (!source.pressed.has(button)) {
          return;
        }
        source.pressed.delete(button);
        const { x, y, force, radiusX, radiusY, subtype: pointerType } = source;
        const { modifiers } = keyState;
        switch (pointerType) {
          case "mouse":
          case "pen":
            return this.#context.cdpTarget.cdpClient.sendCommand("Input.dispatchMouseEvent", {
              type: "mouseReleased",
              x,
              y,
              modifiers,
              button: getCdpButton(button),
              buttons: source.buttons,
              clickCount: source.getClickCount(button),
              pointerType
            });
          case "touch":
            return this.#context.cdpTarget.cdpClient.sendCommand("Input.dispatchTouchEvent", {
              type: "touchEnd",
              touchPoints: [
                {
                  x,
                  y,
                  id: source.pointerId,
                  force,
                  radiusX,
                  radiusY
                }
              ],
              modifiers
            });
        }
      }
      async #dispatchPointerMoveAction(source, keyState, action) {
        const { x: startX, y: startY, subtype: pointerType } = source;
        const { width, height, pressure, twist, tangentialPressure, x: offsetX, y: offsetY, origin = "viewport", duration = this.#tickDuration } = action;
        const { tiltX, tiltY } = getTilt(action);
        const { radiusX, radiusY } = getRadii(width ?? 1, height ?? 1);
        const { targetX, targetY } = await this.#getCoordinateFromOrigin(origin, offsetX, offsetY, startX, startY);
        if (targetX < 0 || targetY < 0) {
          throw new protocol_js_1.MoveTargetOutOfBoundsException(`Cannot move beyond viewport (x: ${targetX}, y: ${targetY})`);
        }
        let last;
        do {
          const ratio = duration > 0 ? (performance.now() - this.#tickStart) / duration : 1;
          last = ratio >= 1;
          let x;
          let y;
          if (last) {
            x = targetX;
            y = targetY;
          } else {
            x = Math.round(ratio * (targetX - startX) + startX);
            y = Math.round(ratio * (targetY - startY) + startY);
          }
          if (source.x !== x || source.y !== y) {
            const { modifiers } = keyState;
            switch (pointerType) {
              case "mouse":
                await this.#context.cdpTarget.cdpClient.sendCommand("Input.dispatchMouseEvent", {
                  type: "mouseMoved",
                  x,
                  y,
                  modifiers,
                  clickCount: 0,
                  button: getCdpButton(source.pressed.values().next().value ?? 5),
                  buttons: source.buttons,
                  pointerType,
                  tangentialPressure,
                  tiltX,
                  tiltY,
                  twist,
                  force: pressure
                });
                break;
              case "pen":
                if (source.pressed.size !== 0) {
                  await this.#context.cdpTarget.cdpClient.sendCommand("Input.dispatchMouseEvent", {
                    type: "mouseMoved",
                    x,
                    y,
                    modifiers,
                    clickCount: 0,
                    button: getCdpButton(source.pressed.values().next().value ?? 5),
                    buttons: source.buttons,
                    pointerType,
                    tangentialPressure,
                    tiltX,
                    tiltY,
                    twist,
                    force: pressure ?? 0.5
                  });
                }
                break;
              case "touch":
                if (source.pressed.size !== 0) {
                  await this.#context.cdpTarget.cdpClient.sendCommand("Input.dispatchTouchEvent", {
                    type: "touchMove",
                    touchPoints: [
                      {
                        x,
                        y,
                        radiusX,
                        radiusY,
                        tangentialPressure,
                        tiltX,
                        tiltY,
                        twist,
                        force: pressure,
                        id: source.pointerId
                      }
                    ],
                    modifiers
                  });
                }
                break;
            }
            source.x = x;
            source.y = y;
            source.radiusX = radiusX;
            source.radiusY = radiusY;
            source.force = pressure;
          }
        } while (!last);
      }
      async #getFrameOffset() {
        if (this.#context.id === this.#context.cdpTarget.id) {
          return { x: 0, y: 0 };
        }
        const { backendNodeId } = await this.#context.cdpTarget.cdpClient.sendCommand("DOM.getFrameOwner", { frameId: this.#context.id });
        const { model: frameBoxModel } = await this.#context.cdpTarget.cdpClient.sendCommand("DOM.getBoxModel", {
          backendNodeId
        });
        return { x: frameBoxModel.content[0], y: frameBoxModel.content[1] };
      }
      async #getCoordinateFromOrigin(origin, offsetX, offsetY, startX, startY) {
        let targetX;
        let targetY;
        const frameOffset = await this.#getFrameOffset();
        switch (origin) {
          case "viewport":
            targetX = offsetX + frameOffset.x;
            targetY = offsetY + frameOffset.y;
            break;
          case "pointer":
            targetX = startX + offsetX + frameOffset.x;
            targetY = startY + offsetY + frameOffset.y;
            break;
          default: {
            const { x: posX, y: posY } = await getElementCenter(this.#context, origin.element);
            targetX = posX + offsetX + frameOffset.x;
            targetY = posY + offsetY + frameOffset.y;
            break;
          }
        }
        return { targetX, targetY };
      }
      async #dispatchScrollAction(_source, keyState, action) {
        const { deltaX: targetDeltaX, deltaY: targetDeltaY, x: offsetX, y: offsetY, origin = "viewport", duration = this.#tickDuration } = action;
        if (origin === "pointer") {
          throw new protocol_js_1.InvalidArgumentException('"pointer" origin is invalid for scrolling.');
        }
        const { targetX, targetY } = await this.#getCoordinateFromOrigin(origin, offsetX, offsetY, 0, 0);
        if (targetX < 0 || targetY < 0) {
          throw new protocol_js_1.MoveTargetOutOfBoundsException(`Cannot move beyond viewport (x: ${targetX}, y: ${targetY})`);
        }
        let currentDeltaX = 0;
        let currentDeltaY = 0;
        let last;
        do {
          const ratio = duration > 0 ? (performance.now() - this.#tickStart) / duration : 1;
          last = ratio >= 1;
          let deltaX;
          let deltaY;
          if (last) {
            deltaX = targetDeltaX - currentDeltaX;
            deltaY = targetDeltaY - currentDeltaY;
          } else {
            deltaX = Math.round(ratio * targetDeltaX - currentDeltaX);
            deltaY = Math.round(ratio * targetDeltaY - currentDeltaY);
          }
          if (deltaX !== 0 || deltaY !== 0) {
            const { modifiers } = keyState;
            await this.#context.cdpTarget.cdpClient.sendCommand("Input.dispatchMouseEvent", {
              type: "mouseWheel",
              deltaX,
              deltaY,
              x: targetX,
              y: targetY,
              modifiers
            });
            currentDeltaX += deltaX;
            currentDeltaY += deltaY;
          }
        } while (!last);
      }
      async #dispatchKeyDownAction(source, action) {
        const rawKey = action.value;
        if (!(0, graphemeTools_js_1.isSingleGrapheme)(rawKey)) {
          throw new protocol_js_1.InvalidArgumentException(`Invalid key value: ${rawKey}`);
        }
        const isGrapheme = (0, graphemeTools_js_1.isSingleComplexGrapheme)(rawKey);
        const key = (0, keyUtils_js_1.getNormalizedKey)(rawKey);
        const repeat = source.pressed.has(key);
        const code = (0, keyUtils_js_1.getKeyCode)(rawKey);
        const location2 = (0, keyUtils_js_1.getKeyLocation)(rawKey);
        switch (key) {
          case "Alt":
            source.alt = true;
            break;
          case "Shift":
            source.shift = true;
            break;
          case "Control":
            source.ctrl = true;
            break;
          case "Meta":
            source.meta = true;
            break;
        }
        source.pressed.add(key);
        const { modifiers } = source;
        const unmodifiedText = getKeyEventUnmodifiedText(key, source, isGrapheme);
        const text = getKeyEventText(code ?? "", source) ?? unmodifiedText;
        let command2;
        if (this.#isMacOS && source.meta) {
          switch (code) {
            case "KeyA":
              command2 = "SelectAll";
              break;
            case "KeyC":
              command2 = "Copy";
              break;
            case "KeyV":
              command2 = source.shift ? "PasteAndMatchStyle" : "Paste";
              break;
            case "KeyX":
              command2 = "Cut";
              break;
            case "KeyZ":
              command2 = source.shift ? "Redo" : "Undo";
              break;
            default:
          }
        }
        const promises = [
          this.#context.cdpTarget.cdpClient.sendCommand("Input.dispatchKeyEvent", {
            type: text ? "keyDown" : "rawKeyDown",
            windowsVirtualKeyCode: USKeyboardLayout_js_1.KeyToKeyCode[key],
            key,
            code,
            text,
            unmodifiedText,
            autoRepeat: repeat,
            isSystemKey: source.alt || void 0,
            location: location2 < 3 ? location2 : void 0,
            isKeypad: location2 === 3,
            modifiers,
            commands: command2 ? [command2] : void 0
          })
        ];
        if (key === "Escape") {
          if (!source.alt && (this.#isMacOS && !source.ctrl && !source.meta || !this.#isMacOS)) {
            promises.push(this.#context.cdpTarget.cdpClient.sendCommand("Input.cancelDragging"));
          }
        }
        await Promise.all(promises);
      }
      #dispatchKeyUpAction(source, action) {
        const rawKey = action.value;
        if (!(0, graphemeTools_js_1.isSingleGrapheme)(rawKey)) {
          throw new protocol_js_1.InvalidArgumentException(`Invalid key value: ${rawKey}`);
        }
        const isGrapheme = (0, graphemeTools_js_1.isSingleComplexGrapheme)(rawKey);
        const key = (0, keyUtils_js_1.getNormalizedKey)(rawKey);
        if (!source.pressed.has(key)) {
          return;
        }
        const code = (0, keyUtils_js_1.getKeyCode)(rawKey);
        const location2 = (0, keyUtils_js_1.getKeyLocation)(rawKey);
        switch (key) {
          case "Alt":
            source.alt = false;
            break;
          case "Shift":
            source.shift = false;
            break;
          case "Control":
            source.ctrl = false;
            break;
          case "Meta":
            source.meta = false;
            break;
        }
        source.pressed.delete(key);
        const { modifiers } = source;
        const unmodifiedText = getKeyEventUnmodifiedText(key, source, isGrapheme);
        const text = getKeyEventText(code ?? "", source) ?? unmodifiedText;
        return this.#context.cdpTarget.cdpClient.sendCommand("Input.dispatchKeyEvent", {
          type: "keyUp",
          windowsVirtualKeyCode: USKeyboardLayout_js_1.KeyToKeyCode[key],
          key,
          code,
          text,
          unmodifiedText,
          location: location2 < 3 ? location2 : void 0,
          isSystemKey: source.alt || void 0,
          isKeypad: location2 === 3,
          modifiers
        });
      }
    };
    exports2.ActionDispatcher = ActionDispatcher;
    var getKeyEventUnmodifiedText = (key, source, isGrapheme) => {
      if (isGrapheme) {
        return key;
      }
      if (key === "Enter") {
        return "\r";
      }
      return [...key].length === 1 ? source.shift ? key.toLocaleUpperCase("en-US") : key : void 0;
    };
    var getKeyEventText = (code, source) => {
      if (source.ctrl) {
        switch (code) {
          case "Digit2":
            if (source.shift) {
              return "\0";
            }
            break;
          case "KeyA":
            return "";
          case "KeyB":
            return "";
          case "KeyC":
            return "";
          case "KeyD":
            return "";
          case "KeyE":
            return "";
          case "KeyF":
            return "";
          case "KeyG":
            return "\x07";
          case "KeyH":
            return "\b";
          case "KeyI":
            return "	";
          case "KeyJ":
            return "\n";
          case "KeyK":
            return "\v";
          case "KeyL":
            return "\f";
          case "KeyM":
            return "\r";
          case "KeyN":
            return "";
          case "KeyO":
            return "";
          case "KeyP":
            return "";
          case "KeyQ":
            return "";
          case "KeyR":
            return "";
          case "KeyS":
            return "";
          case "KeyT":
            return "";
          case "KeyU":
            return "";
          case "KeyV":
            return "";
          case "KeyW":
            return "";
          case "KeyX":
            return "";
          case "KeyY":
            return "";
          case "KeyZ":
            return "";
          case "BracketLeft":
            return "\x1B";
          case "Backslash":
            return "";
          case "BracketRight":
            return "";
          case "Digit6":
            if (source.shift) {
              return "";
            }
            break;
          case "Minus":
            return "";
        }
        return "";
      }
      if (source.alt) {
        return "";
      }
      return;
    };
    function getCdpButton(button) {
      switch (button) {
        case 0:
          return "left";
        case 1:
          return "middle";
        case 2:
          return "right";
        case 3:
          return "back";
        case 4:
          return "forward";
        default:
          return "none";
      }
    }
    function getTilt(action) {
      const altitudeAngle = action.altitudeAngle ?? Math.PI / 2;
      const azimuthAngle = action.azimuthAngle ?? 0;
      let tiltXRadians = 0;
      let tiltYRadians = 0;
      if (altitudeAngle === 0) {
        if (azimuthAngle === 0 || azimuthAngle === 2 * Math.PI) {
          tiltXRadians = Math.PI / 2;
        }
        if (azimuthAngle === Math.PI / 2) {
          tiltYRadians = Math.PI / 2;
        }
        if (azimuthAngle === Math.PI) {
          tiltXRadians = -Math.PI / 2;
        }
        if (azimuthAngle === 3 * Math.PI / 2) {
          tiltYRadians = -Math.PI / 2;
        }
        if (azimuthAngle > 0 && azimuthAngle < Math.PI / 2) {
          tiltXRadians = Math.PI / 2;
          tiltYRadians = Math.PI / 2;
        }
        if (azimuthAngle > Math.PI / 2 && azimuthAngle < Math.PI) {
          tiltXRadians = -Math.PI / 2;
          tiltYRadians = Math.PI / 2;
        }
        if (azimuthAngle > Math.PI && azimuthAngle < 3 * Math.PI / 2) {
          tiltXRadians = -Math.PI / 2;
          tiltYRadians = -Math.PI / 2;
        }
        if (azimuthAngle > 3 * Math.PI / 2 && azimuthAngle < 2 * Math.PI) {
          tiltXRadians = Math.PI / 2;
          tiltYRadians = -Math.PI / 2;
        }
      }
      if (altitudeAngle !== 0) {
        const tanAlt = Math.tan(altitudeAngle);
        tiltXRadians = Math.atan(Math.cos(azimuthAngle) / tanAlt);
        tiltYRadians = Math.atan(Math.sin(azimuthAngle) / tanAlt);
      }
      const factor = 180 / Math.PI;
      return {
        tiltX: Math.round(tiltXRadians * factor),
        tiltY: Math.round(tiltYRadians * factor)
      };
    }
    function getRadii(width, height) {
      return {
        radiusX: width ? width / 2 : 0.5,
        radiusY: height ? height / 2 : 0.5
      };
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/utils/Mutex.js
var require_Mutex2 = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/utils/Mutex.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Mutex = void 0;
    var Mutex = class {
      #locked = false;
      #acquirers = [];
      // This is FIFO.
      acquire() {
        const state = { resolved: false };
        if (this.#locked) {
          return new Promise((resolve5) => {
            this.#acquirers.push(() => resolve5(this.#release.bind(this, state)));
          });
        }
        this.#locked = true;
        return Promise.resolve(this.#release.bind(this, state));
      }
      #release(state) {
        if (state.resolved) {
          throw new Error("Cannot release more than once.");
        }
        state.resolved = true;
        const resolve5 = this.#acquirers.shift();
        if (!resolve5) {
          this.#locked = false;
          return;
        }
        resolve5();
      }
      async run(action) {
        const release = await this.acquire();
        try {
          const result = await action();
          return result;
        } finally {
          release();
        }
      }
    };
    exports2.Mutex = Mutex;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/input/InputState.js
var require_InputState = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/input/InputState.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InputState = void 0;
    var protocol_js_1 = require_protocol();
    var Mutex_js_1 = require_Mutex2();
    var InputSource_js_1 = require_InputSource();
    var InputState = class {
      cancelList = [];
      #sources = /* @__PURE__ */ new Map();
      #mutex = new Mutex_js_1.Mutex();
      getOrCreate(id, type, subtype) {
        let source = this.#sources.get(id);
        if (!source) {
          switch (type) {
            case "none":
              source = new InputSource_js_1.NoneSource();
              break;
            case "key":
              source = new InputSource_js_1.KeySource();
              break;
            case "pointer": {
              let pointerId = subtype === "mouse" ? 0 : 2;
              const pointerIds = /* @__PURE__ */ new Set();
              for (const [, source2] of this.#sources) {
                if (source2.type === "pointer") {
                  pointerIds.add(source2.pointerId);
                }
              }
              while (pointerIds.has(pointerId)) {
                ++pointerId;
              }
              source = new InputSource_js_1.PointerSource(pointerId, subtype);
              break;
            }
            case "wheel":
              source = new InputSource_js_1.WheelSource();
              break;
            default:
              throw new protocol_js_1.InvalidArgumentException(`Expected "${"none"}", "${"key"}", "${"pointer"}", or "${"wheel"}". Found unknown source type ${type}.`);
          }
          this.#sources.set(id, source);
          return source;
        }
        if (source.type !== type) {
          throw new protocol_js_1.InvalidArgumentException(`Input source type of ${id} is ${source.type}, but received ${type}.`);
        }
        return source;
      }
      get(id) {
        const source = this.#sources.get(id);
        if (!source) {
          throw new protocol_js_1.UnknownErrorException(`Internal error.`);
        }
        return source;
      }
      getGlobalKeyState() {
        const state = new InputSource_js_1.KeySource();
        for (const [, source] of this.#sources) {
          if (source.type !== "key") {
            continue;
          }
          for (const pressed of source.pressed) {
            state.pressed.add(pressed);
          }
          state.alt ||= source.alt;
          state.ctrl ||= source.ctrl;
          state.meta ||= source.meta;
          state.shift ||= source.shift;
        }
        return state;
      }
      get queue() {
        return this.#mutex;
      }
    };
    exports2.InputState = InputState;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/input/InputStateManager.js
var require_InputStateManager = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/input/InputStateManager.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InputStateManager = void 0;
    var assert_js_1 = require_assert2();
    var InputState_js_1 = require_InputState();
    var InputStateManager = class extends WeakMap {
      get(context) {
        (0, assert_js_1.assert)(context.isTopLevelContext());
        if (!this.has(context)) {
          this.set(context, new InputState_js_1.InputState());
        }
        return super.get(context);
      }
    };
    exports2.InputStateManager = InputStateManager;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/input/InputProcessor.js
var require_InputProcessor = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/input/InputProcessor.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InputProcessor = void 0;
    var protocol_js_1 = require_protocol();
    var assert_js_1 = require_assert2();
    var ActionDispatcher_js_1 = require_ActionDispatcher();
    var InputStateManager_js_1 = require_InputStateManager();
    var InputProcessor = class {
      #browsingContextStorage;
      #inputStateManager = new InputStateManager_js_1.InputStateManager();
      constructor(browsingContextStorage) {
        this.#browsingContextStorage = browsingContextStorage;
      }
      async performActions(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        const inputState = this.#inputStateManager.get(context.top);
        const actionsByTick = this.#getActionsByTick(params, inputState);
        const dispatcher = new ActionDispatcher_js_1.ActionDispatcher(inputState, this.#browsingContextStorage, params.context, await ActionDispatcher_js_1.ActionDispatcher.isMacOS(context).catch(() => false));
        await dispatcher.dispatchActions(actionsByTick);
        return {};
      }
      async releaseActions(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        const topContext = context.top;
        const inputState = this.#inputStateManager.get(topContext);
        const dispatcher = new ActionDispatcher_js_1.ActionDispatcher(inputState, this.#browsingContextStorage, params.context, await ActionDispatcher_js_1.ActionDispatcher.isMacOS(context).catch(() => false));
        await dispatcher.dispatchTickActions(inputState.cancelList.reverse());
        this.#inputStateManager.delete(topContext);
        return {};
      }
      async setFiles(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        const hiddenSandboxRealm = await context.getOrCreateHiddenSandbox();
        let result;
        try {
          result = await hiddenSandboxRealm.callFunction(String(function getFiles(fileListLength) {
            if (!(this instanceof HTMLInputElement)) {
              if (this instanceof Element) {
                return 1;
              }
              return 0;
            }
            if (this.type !== "file") {
              return 2;
            }
            if (this.disabled) {
              return 3;
            }
            if (fileListLength > 1 && !this.multiple) {
              return 4;
            }
            return;
          }), false, params.element, [{ type: "number", value: params.files.length }]);
        } catch {
          throw new protocol_js_1.NoSuchNodeException(`Could not find element ${params.element.sharedId}`);
        }
        (0, assert_js_1.assert)(result.type === "success");
        if (result.result.type === "number") {
          switch (result.result.value) {
            case 0: {
              throw new protocol_js_1.NoSuchElementException(`Could not find element ${params.element.sharedId}`);
            }
            case 1: {
              throw new protocol_js_1.UnableToSetFileInputException(`Element ${params.element.sharedId} is not a input`);
            }
            case 2: {
              throw new protocol_js_1.UnableToSetFileInputException(`Input element ${params.element.sharedId} is not a file type`);
            }
            case 3: {
              throw new protocol_js_1.UnableToSetFileInputException(`Input element ${params.element.sharedId} is disabled`);
            }
            case 4: {
              throw new protocol_js_1.UnableToSetFileInputException(`Cannot set multiple files on a non-multiple input element`);
            }
          }
        }
        if (params.files.length === 0) {
          await hiddenSandboxRealm.callFunction(String(function dispatchEvent() {
            if (this.files?.length === 0) {
              this.dispatchEvent(new Event("cancel", {
                bubbles: true
              }));
              return;
            }
            this.files = new DataTransfer().files;
            this.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
            this.dispatchEvent(new Event("change", { bubbles: true }));
          }), false, params.element);
          return {};
        }
        const paths = [];
        for (let i = 0; i < params.files.length; ++i) {
          const result2 = await hiddenSandboxRealm.callFunction(
            String(function getFiles(index) {
              return this.files?.item(index);
            }),
            false,
            params.element,
            [{ type: "number", value: 0 }],
            "root"
            /* Script.ResultOwnership.Root */
          );
          (0, assert_js_1.assert)(result2.type === "success");
          if (result2.result.type !== "object") {
            break;
          }
          const { handle } = result2.result;
          (0, assert_js_1.assert)(handle !== void 0);
          const { path: path2 } = await hiddenSandboxRealm.cdpClient.sendCommand("DOM.getFileInfo", {
            objectId: handle
          });
          paths.push(path2);
          void hiddenSandboxRealm.disown(handle).catch(void 0);
        }
        paths.sort();
        const sortedFiles = [...params.files].sort();
        if (paths.length !== params.files.length || sortedFiles.some((path2, index) => {
          return paths[index] !== path2;
        })) {
          const { objectId } = await hiddenSandboxRealm.deserializeForCdp(params.element);
          (0, assert_js_1.assert)(objectId !== void 0);
          await hiddenSandboxRealm.cdpClient.sendCommand("DOM.setFileInputFiles", {
            files: params.files,
            objectId
          });
        } else {
          await hiddenSandboxRealm.callFunction(String(function dispatchEvent() {
            this.dispatchEvent(new Event("cancel", {
              bubbles: true
            }));
          }), false, params.element);
        }
        return {};
      }
      #getActionsByTick(params, inputState) {
        const actionsByTick = [];
        for (const action of params.actions) {
          switch (action.type) {
            case "pointer": {
              action.parameters ??= {
                pointerType: "mouse"
                /* Input.PointerType.Mouse */
              };
              action.parameters.pointerType ??= "mouse";
              const source = inputState.getOrCreate(action.id, "pointer", action.parameters.pointerType);
              if (source.subtype !== action.parameters.pointerType) {
                throw new protocol_js_1.InvalidArgumentException(`Expected input source ${action.id} to be ${source.subtype}; got ${action.parameters.pointerType}.`);
              }
              source.resetClickCount();
              break;
            }
            default:
              inputState.getOrCreate(action.id, action.type);
          }
          const actions = action.actions.map((item) => ({
            id: action.id,
            action: item
          }));
          for (let i = 0; i < actions.length; i++) {
            if (actionsByTick.length === i) {
              actionsByTick.push([]);
            }
            actionsByTick[i].push(actions[i]);
          }
        }
        return actionsByTick;
      }
    };
    exports2.InputProcessor = InputProcessor;
  }
});

// node_modules/chromium-bidi/lib/cjs/utils/base64.js
var require_base64 = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/utils/base64.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.base64ToString = base64ToString;
    function base64ToString(base64Str) {
      if ("atob" in globalThis) {
        return globalThis.atob(base64Str);
      }
      return Buffer.from(base64Str, "base64").toString("ascii");
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/network/NetworkUtils.js
var require_NetworkUtils = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/network/NetworkUtils.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.computeHeadersSize = computeHeadersSize;
    exports2.stringToBase64 = stringToBase64;
    exports2.bidiNetworkHeadersFromCdpNetworkHeaders = bidiNetworkHeadersFromCdpNetworkHeaders;
    exports2.bidiNetworkHeadersFromCdpNetworkHeadersEntries = bidiNetworkHeadersFromCdpNetworkHeadersEntries;
    exports2.cdpNetworkHeadersFromBidiNetworkHeaders = cdpNetworkHeadersFromBidiNetworkHeaders;
    exports2.bidiNetworkHeadersFromCdpFetchHeaders = bidiNetworkHeadersFromCdpFetchHeaders;
    exports2.cdpFetchHeadersFromBidiNetworkHeaders = cdpFetchHeadersFromBidiNetworkHeaders;
    exports2.networkHeaderFromCookieHeaders = networkHeaderFromCookieHeaders;
    exports2.cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction = cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction;
    exports2.cdpToBiDiCookie = cdpToBiDiCookie;
    exports2.deserializeByteValue = deserializeByteValue;
    exports2.bidiToCdpCookie = bidiToCdpCookie;
    exports2.sameSiteBiDiToCdp = sameSiteBiDiToCdp;
    exports2.isSpecialScheme = isSpecialScheme;
    exports2.matchUrlPattern = matchUrlPattern;
    exports2.bidiBodySizeFromCdpPostDataEntries = bidiBodySizeFromCdpPostDataEntries;
    exports2.getTiming = getTiming;
    var ErrorResponse_js_1 = require_ErrorResponse();
    var base64_js_1 = require_base64();
    function computeHeadersSize(headers) {
      const requestHeaders = headers.reduce((acc, header) => {
        return `${acc}${header.name}: ${header.value.value}\r
`;
      }, "");
      return new TextEncoder().encode(requestHeaders).length;
    }
    function stringToBase64(str) {
      return typedArrayToBase64(new TextEncoder().encode(str));
    }
    function typedArrayToBase64(typedArray) {
      const chunkSize = 65534;
      const chunks = [];
      for (let i = 0; i < typedArray.length; i += chunkSize) {
        const chunk = typedArray.subarray(i, i + chunkSize);
        chunks.push(String.fromCodePoint.apply(null, chunk));
      }
      const binaryString = chunks.join("");
      return btoa(binaryString);
    }
    function bidiNetworkHeadersFromCdpNetworkHeaders(headers) {
      if (!headers) {
        return [];
      }
      return Object.entries(headers).map(([name, value]) => ({
        name,
        value: {
          type: "string",
          value
        }
      }));
    }
    function bidiNetworkHeadersFromCdpNetworkHeadersEntries(headers) {
      if (!headers) {
        return [];
      }
      return headers.map(({ name, value }) => ({
        name,
        value: {
          type: "string",
          value
        }
      }));
    }
    function cdpNetworkHeadersFromBidiNetworkHeaders(headers) {
      if (headers === void 0) {
        return void 0;
      }
      return headers.reduce((result, header) => {
        result[header.name] = header.value.value;
        return result;
      }, {});
    }
    function bidiNetworkHeadersFromCdpFetchHeaders(headers) {
      if (!headers) {
        return [];
      }
      return headers.map(({ name, value }) => ({
        name,
        value: {
          type: "string",
          value
        }
      }));
    }
    function cdpFetchHeadersFromBidiNetworkHeaders(headers) {
      if (headers === void 0) {
        return void 0;
      }
      return headers.map(({ name, value }) => ({
        name,
        value: value.value
      }));
    }
    function networkHeaderFromCookieHeaders(headers) {
      if (headers === void 0) {
        return void 0;
      }
      const value = headers.reduce((acc, value2, index) => {
        if (index > 0) {
          acc += ";";
        }
        const cookieValue = value2.value.type === "base64" ? btoa(value2.value.value) : value2.value.value;
        acc += `${value2.name}=${cookieValue}`;
        return acc;
      }, "");
      return {
        name: "Cookie",
        value: {
          type: "string",
          value
        }
      };
    }
    function cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction(action) {
      switch (action) {
        case "default":
          return "Default";
        case "cancel":
          return "CancelAuth";
        case "provideCredentials":
          return "ProvideCredentials";
      }
    }
    function cdpToBiDiCookie(cookie) {
      const result = {
        name: cookie.name,
        value: { type: "string", value: cookie.value },
        domain: cookie.domain,
        path: cookie.path,
        size: cookie.size,
        httpOnly: cookie.httpOnly,
        secure: cookie.secure,
        sameSite: cookie.sameSite === void 0 ? "none" : sameSiteCdpToBiDi(cookie.sameSite),
        ...cookie.expires >= 0 ? { expiry: Math.round(cookie.expires) } : void 0
      };
      result[`goog:session`] = cookie.session;
      result[`goog:priority`] = cookie.priority;
      result[`goog:sourceScheme`] = cookie.sourceScheme;
      result[`goog:sourcePort`] = cookie.sourcePort;
      if (cookie.partitionKey !== void 0) {
        result[`goog:partitionKey`] = cookie.partitionKey;
      }
      if (cookie.partitionKeyOpaque !== void 0) {
        result[`goog:partitionKeyOpaque`] = cookie.partitionKeyOpaque;
      }
      return result;
    }
    function deserializeByteValue(value) {
      if (value.type === "base64") {
        return (0, base64_js_1.base64ToString)(value.value);
      }
      return value.value;
    }
    function bidiToCdpCookie(params, partitionKey) {
      const deserializedValue = deserializeByteValue(params.cookie.value);
      const result = {
        name: params.cookie.name,
        value: deserializedValue,
        domain: params.cookie.domain,
        path: params.cookie.path ?? "/",
        secure: params.cookie.secure ?? false,
        httpOnly: params.cookie.httpOnly ?? false,
        ...partitionKey.sourceOrigin !== void 0 && {
          partitionKey: {
            hasCrossSiteAncestor: false,
            // CDP's `partitionKey.topLevelSite` is the BiDi's `partition.sourceOrigin`.
            topLevelSite: partitionKey.sourceOrigin
          }
        },
        ...params.cookie.expiry !== void 0 && {
          expires: params.cookie.expiry
        },
        ...params.cookie.sameSite !== void 0 && {
          sameSite: sameSiteBiDiToCdp(params.cookie.sameSite)
        }
      };
      if (params.cookie[`goog:url`] !== void 0) {
        result.url = params.cookie[`goog:url`];
      }
      if (params.cookie[`goog:priority`] !== void 0) {
        result.priority = params.cookie[`goog:priority`];
      }
      if (params.cookie[`goog:sourceScheme`] !== void 0) {
        result.sourceScheme = params.cookie[`goog:sourceScheme`];
      }
      if (params.cookie[`goog:sourcePort`] !== void 0) {
        result.sourcePort = params.cookie[`goog:sourcePort`];
      }
      return result;
    }
    function sameSiteCdpToBiDi(sameSite) {
      switch (sameSite) {
        case "Strict":
          return "strict";
        case "None":
          return "none";
        case "Lax":
          return "lax";
        default:
          return "lax";
      }
    }
    function sameSiteBiDiToCdp(sameSite) {
      switch (sameSite) {
        case "none":
          return "None";
        case "strict":
          return "Strict";
        // Defaults to `Lax`:
        // https://web.dev/articles/samesite-cookies-explained#samesitelax_by_default
        case "default":
        case "lax":
          return "Lax";
      }
      throw new ErrorResponse_js_1.InvalidArgumentException(`Unknown 'sameSite' value ${sameSite}`);
    }
    function isSpecialScheme(protocol) {
      return ["ftp", "file", "http", "https", "ws", "wss"].includes(protocol.replace(/:$/, ""));
    }
    function getScheme(url) {
      return url.protocol.replace(/:$/, "");
    }
    function matchUrlPattern(pattern, url) {
      const parsedUrl = new URL(url);
      if (pattern.protocol !== void 0 && pattern.protocol !== getScheme(parsedUrl)) {
        return false;
      }
      if (pattern.hostname !== void 0 && pattern.hostname !== parsedUrl.hostname) {
        return false;
      }
      if (pattern.port !== void 0 && pattern.port !== parsedUrl.port) {
        return false;
      }
      if (pattern.pathname !== void 0 && pattern.pathname !== parsedUrl.pathname) {
        return false;
      }
      if (pattern.search !== void 0 && pattern.search !== parsedUrl.search) {
        return false;
      }
      return true;
    }
    function bidiBodySizeFromCdpPostDataEntries(entries) {
      let size = 0;
      for (const entry of entries) {
        size += atob(entry.bytes ?? "").length;
      }
      return size;
    }
    function getTiming(timing, offset = 0) {
      if (!timing) {
        return 0;
      }
      if (timing <= 0 || timing + offset <= 0) {
        return 0;
      }
      return timing + offset;
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/network/NetworkProcessor.js
var require_NetworkProcessor = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/network/NetworkProcessor.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NetworkProcessor = void 0;
    exports2.parseBiDiHeaders = parseBiDiHeaders;
    var protocol_js_1 = require_protocol();
    var NetworkUtils_js_1 = require_NetworkUtils();
    var NetworkProcessor = class _NetworkProcessor {
      #browsingContextStorage;
      #networkStorage;
      #userContextStorage;
      #contextConfigStorage;
      constructor(browsingContextStorage, networkStorage, userContextStorage, contextConfigStorage) {
        this.#userContextStorage = userContextStorage;
        this.#browsingContextStorage = browsingContextStorage;
        this.#networkStorage = networkStorage;
        this.#contextConfigStorage = contextConfigStorage;
      }
      async addIntercept(params) {
        this.#browsingContextStorage.verifyTopLevelContextsList(params.contexts);
        const urlPatterns = params.urlPatterns ?? [];
        const parsedUrlPatterns = _NetworkProcessor.parseUrlPatterns(urlPatterns);
        const intercept = this.#networkStorage.addIntercept({
          urlPatterns: parsedUrlPatterns,
          phases: params.phases,
          contexts: params.contexts
        });
        await this.#toggleNetwork();
        return {
          intercept
        };
      }
      async continueRequest(params) {
        if (params.url !== void 0) {
          _NetworkProcessor.parseUrlString(params.url);
        }
        if (params.method !== void 0) {
          if (!_NetworkProcessor.isMethodValid(params.method)) {
            throw new protocol_js_1.InvalidArgumentException(`Method '${params.method}' is invalid.`);
          }
        }
        if (params.headers) {
          _NetworkProcessor.validateHeaders(params.headers);
        }
        const request = this.#getBlockedRequestOrFail(params.request, [
          "beforeRequestSent"
        ]);
        try {
          await request.continueRequest(params);
        } catch (error) {
          throw _NetworkProcessor.wrapInterceptionError(error);
        }
        return {};
      }
      async continueResponse(params) {
        if (params.headers) {
          _NetworkProcessor.validateHeaders(params.headers);
        }
        const request = this.#getBlockedRequestOrFail(params.request, [
          "authRequired",
          "responseStarted"
        ]);
        try {
          await request.continueResponse(params);
        } catch (error) {
          throw _NetworkProcessor.wrapInterceptionError(error);
        }
        return {};
      }
      async continueWithAuth(params) {
        const networkId = params.request;
        const request = this.#getBlockedRequestOrFail(networkId, [
          "authRequired"
        ]);
        await request.continueWithAuth(params);
        return {};
      }
      async failRequest({ request: networkId }) {
        const request = this.#getRequestOrFail(networkId);
        if (request.interceptPhase === "authRequired") {
          throw new protocol_js_1.InvalidArgumentException(`Request '${networkId}' in 'authRequired' phase cannot be failed`);
        }
        if (!request.interceptPhase) {
          throw new protocol_js_1.NoSuchRequestException(`No blocked request found for network id '${networkId}'`);
        }
        await request.failRequest("Failed");
        return {};
      }
      async provideResponse(params) {
        if (params.headers) {
          _NetworkProcessor.validateHeaders(params.headers);
        }
        const request = this.#getBlockedRequestOrFail(params.request, [
          "beforeRequestSent",
          "responseStarted",
          "authRequired"
        ]);
        try {
          await request.provideResponse(params);
        } catch (error) {
          throw _NetworkProcessor.wrapInterceptionError(error);
        }
        return {};
      }
      /**
       * In some states CDP Network and Fetch domains are not required, but in some they have
       * to be updated. Whenever potential change in these kinds of states is introduced,
       * update the states of all the CDP targets.
       */
      async #toggleNetwork() {
        await Promise.all(this.#browsingContextStorage.getAllContexts().map((context) => {
          return context.cdpTarget.toggleNetwork();
        }));
      }
      async removeIntercept(params) {
        this.#networkStorage.removeIntercept(params.intercept);
        await this.#toggleNetwork();
        return {};
      }
      async setCacheBehavior(params) {
        const contexts = this.#browsingContextStorage.verifyTopLevelContextsList(params.contexts);
        if (contexts.size === 0) {
          this.#networkStorage.defaultCacheBehavior = params.cacheBehavior;
          await Promise.all(this.#browsingContextStorage.getAllContexts().map((context) => {
            return context.cdpTarget.toggleSetCacheDisabled();
          }));
          return {};
        }
        const cacheDisabled = params.cacheBehavior === "bypass";
        await Promise.all([...contexts.values()].map((context) => {
          return context.cdpTarget.toggleSetCacheDisabled(cacheDisabled);
        }));
        return {};
      }
      #getRequestOrFail(id) {
        const request = this.#networkStorage.getRequestById(id);
        if (!request) {
          throw new protocol_js_1.NoSuchRequestException(`Network request with ID '${id}' doesn't exist`);
        }
        return request;
      }
      #getBlockedRequestOrFail(id, phases) {
        const request = this.#getRequestOrFail(id);
        if (!request.interceptPhase) {
          throw new protocol_js_1.NoSuchRequestException(`No blocked request found for network id '${id}'`);
        }
        if (request.interceptPhase && !phases.includes(request.interceptPhase)) {
          throw new protocol_js_1.InvalidArgumentException(`Blocked request for network id '${id}' is in '${request.interceptPhase}' phase`);
        }
        return request;
      }
      /**
       * Validate https://fetch.spec.whatwg.org/#header-value
       */
      static validateHeaders(headers) {
        for (const header of headers) {
          let headerValue;
          if (header.value.type === "string") {
            headerValue = header.value.value;
          } else {
            headerValue = atob(header.value.value);
          }
          if (headerValue !== headerValue.trim() || headerValue.includes("\n") || headerValue.includes("\0")) {
            throw new protocol_js_1.InvalidArgumentException(`Header value '${headerValue}' is not acceptable value`);
          }
        }
      }
      static isMethodValid(method) {
        return /^[!#$%&'*+\-.^_`|~a-zA-Z\d]+$/.test(method);
      }
      /**
       * Attempts to parse the given url.
       * Throws an InvalidArgumentException if the url is invalid.
       */
      static parseUrlString(url) {
        try {
          return new URL(url);
        } catch (error) {
          throw new protocol_js_1.InvalidArgumentException(`Invalid URL '${url}': ${error}`);
        }
      }
      static parseUrlPatterns(urlPatterns) {
        return urlPatterns.map((urlPattern) => {
          let patternUrl = "";
          let hasProtocol = true;
          let hasHostname = true;
          let hasPort = true;
          let hasPathname = true;
          let hasSearch = true;
          switch (urlPattern.type) {
            case "string": {
              patternUrl = unescapeURLPattern(urlPattern.pattern);
              break;
            }
            case "pattern": {
              if (urlPattern.protocol === void 0) {
                hasProtocol = false;
                patternUrl += "http";
              } else {
                if (urlPattern.protocol === "") {
                  throw new protocol_js_1.InvalidArgumentException("URL pattern must specify a protocol");
                }
                urlPattern.protocol = unescapeURLPattern(urlPattern.protocol);
                if (!urlPattern.protocol.match(/^[a-zA-Z+-.]+$/)) {
                  throw new protocol_js_1.InvalidArgumentException("Forbidden characters");
                }
                patternUrl += urlPattern.protocol;
              }
              const scheme = patternUrl.toLocaleLowerCase();
              patternUrl += ":";
              if ((0, NetworkUtils_js_1.isSpecialScheme)(scheme)) {
                patternUrl += "//";
              }
              if (urlPattern.hostname === void 0) {
                if (scheme !== "file") {
                  patternUrl += "placeholder";
                }
                hasHostname = false;
              } else {
                if (urlPattern.hostname === "") {
                  throw new protocol_js_1.InvalidArgumentException("URL pattern must specify a hostname");
                }
                if (urlPattern.protocol === "file") {
                  throw new protocol_js_1.InvalidArgumentException(`URL pattern protocol cannot be 'file'`);
                }
                urlPattern.hostname = unescapeURLPattern(urlPattern.hostname);
                let insideBrackets = false;
                for (const c of urlPattern.hostname) {
                  if (c === "/" || c === "?" || c === "#") {
                    throw new protocol_js_1.InvalidArgumentException(`'/', '?', '#' are forbidden in hostname`);
                  }
                  if (!insideBrackets && c === ":") {
                    throw new protocol_js_1.InvalidArgumentException(`':' is only allowed inside brackets in hostname`);
                  }
                  if (c === "[") {
                    insideBrackets = true;
                  }
                  if (c === "]") {
                    insideBrackets = false;
                  }
                }
                patternUrl += urlPattern.hostname;
              }
              if (urlPattern.port === void 0) {
                hasPort = false;
              } else {
                if (urlPattern.port === "") {
                  throw new protocol_js_1.InvalidArgumentException(`URL pattern must specify a port`);
                }
                urlPattern.port = unescapeURLPattern(urlPattern.port);
                patternUrl += ":";
                if (!urlPattern.port.match(/^\d+$/)) {
                  throw new protocol_js_1.InvalidArgumentException("Forbidden characters");
                }
                patternUrl += urlPattern.port;
              }
              if (urlPattern.pathname === void 0) {
                hasPathname = false;
              } else {
                urlPattern.pathname = unescapeURLPattern(urlPattern.pathname);
                if (urlPattern.pathname[0] !== "/") {
                  patternUrl += "/";
                }
                if (urlPattern.pathname.includes("#") || urlPattern.pathname.includes("?")) {
                  throw new protocol_js_1.InvalidArgumentException("Forbidden characters");
                }
                patternUrl += urlPattern.pathname;
              }
              if (urlPattern.search === void 0) {
                hasSearch = false;
              } else {
                urlPattern.search = unescapeURLPattern(urlPattern.search);
                if (urlPattern.search[0] !== "?") {
                  patternUrl += "?";
                }
                if (urlPattern.search.includes("#")) {
                  throw new protocol_js_1.InvalidArgumentException("Forbidden characters");
                }
                patternUrl += urlPattern.search;
              }
              break;
            }
          }
          const serializePort = (url) => {
            const defaultPorts = {
              "ftp:": 21,
              "file:": null,
              "http:": 80,
              "https:": 443,
              "ws:": 80,
              "wss:": 443
            };
            if ((0, NetworkUtils_js_1.isSpecialScheme)(url.protocol) && defaultPorts[url.protocol] !== null && (!url.port || String(defaultPorts[url.protocol]) === url.port)) {
              return "";
            } else if (url.port) {
              return url.port;
            }
            return void 0;
          };
          try {
            const url = new URL(patternUrl);
            return {
              protocol: hasProtocol ? url.protocol.replace(/:$/, "") : void 0,
              hostname: hasHostname ? url.hostname : void 0,
              port: hasPort ? serializePort(url) : void 0,
              pathname: hasPathname && url.pathname ? url.pathname : void 0,
              search: hasSearch ? url.search : void 0
            };
          } catch (err) {
            throw new protocol_js_1.InvalidArgumentException(`${err.message} '${patternUrl}'`);
          }
        });
      }
      static wrapInterceptionError(error) {
        if (error?.message.includes("Invalid header") || error?.message.includes("Unsafe header")) {
          return new protocol_js_1.InvalidArgumentException(error.message);
        }
        return error;
      }
      async addDataCollector(params) {
        if (params.userContexts !== void 0 && params.contexts !== void 0) {
          throw new protocol_js_1.InvalidArgumentException("'contexts' and 'userContexts' are mutually exclusive");
        }
        if (params.userContexts !== void 0) {
          await this.#userContextStorage.verifyUserContextIdList(params.userContexts);
        }
        if (params.contexts !== void 0) {
          for (const browsingContextId of params.contexts) {
            const browsingContext = this.#browsingContextStorage.getContext(browsingContextId);
            if (!browsingContext.isTopLevelContext()) {
              throw new protocol_js_1.InvalidArgumentException(`Data collectors are available only on top-level browsing contexts`);
            }
          }
        }
        const collectorId = this.#networkStorage.addDataCollector(params);
        await this.#toggleNetwork();
        return { collector: collectorId };
      }
      async getData(params) {
        return await this.#networkStorage.getCollectedData(params);
      }
      async removeDataCollector(params) {
        this.#networkStorage.removeDataCollector(params);
        await this.#toggleNetwork();
        return {};
      }
      disownData(params) {
        this.#networkStorage.disownData(params);
        return {};
      }
      async #getRelatedTopLevelBrowsingContexts(browsingContextIds, userContextIds) {
        if (browsingContextIds === void 0 && userContextIds === void 0) {
          return this.#browsingContextStorage.getTopLevelContexts();
        }
        if (browsingContextIds !== void 0 && userContextIds !== void 0) {
          throw new protocol_js_1.InvalidArgumentException("User contexts and browsing contexts are mutually exclusive");
        }
        const result = [];
        if (userContextIds !== void 0) {
          if (userContextIds.length === 0) {
            throw new protocol_js_1.InvalidArgumentException("user context should be provided");
          }
          await this.#userContextStorage.verifyUserContextIdList(userContextIds);
          for (const userContextId of userContextIds) {
            const topLevelBrowsingContexts = this.#browsingContextStorage.getTopLevelContexts().filter((browsingContext) => browsingContext.userContext === userContextId);
            result.push(...topLevelBrowsingContexts);
          }
        }
        if (browsingContextIds !== void 0) {
          if (browsingContextIds.length === 0) {
            throw new protocol_js_1.InvalidArgumentException("browsing context should be provided");
          }
          for (const browsingContextId of browsingContextIds) {
            const browsingContext = this.#browsingContextStorage.getContext(browsingContextId);
            if (!browsingContext.isTopLevelContext()) {
              throw new protocol_js_1.InvalidArgumentException("The command is only supported on the top-level context");
            }
            result.push(browsingContext);
          }
        }
        return [...new Set(result).values()];
      }
      async setExtraHeaders(params) {
        const affectedBrowsingContexts = await this.#getRelatedTopLevelBrowsingContexts(params.contexts, params.userContexts);
        const cdpExtraHeaders = parseBiDiHeaders(params.headers);
        if (params.userContexts === void 0 && params.contexts === void 0) {
          this.#contextConfigStorage.updateGlobalConfig({
            extraHeaders: cdpExtraHeaders
          });
        }
        if (params.userContexts !== void 0) {
          params.userContexts.forEach((userContext) => {
            this.#contextConfigStorage.updateUserContextConfig(userContext, {
              extraHeaders: cdpExtraHeaders
            });
          });
        }
        if (params.contexts !== void 0) {
          params.contexts.forEach((browsingContextId) => {
            this.#contextConfigStorage.updateBrowsingContextConfig(browsingContextId, { extraHeaders: cdpExtraHeaders });
          });
        }
        await Promise.all(affectedBrowsingContexts.map(async (context) => {
          const extraHeaders = this.#contextConfigStorage.getActiveConfig(context.id, context.userContext).extraHeaders ?? {};
          await context.setExtraHeaders(extraHeaders);
        }));
        return {};
      }
    };
    exports2.NetworkProcessor = NetworkProcessor;
    function unescapeURLPattern(pattern) {
      const forbidden = /* @__PURE__ */ new Set(["(", ")", "*", "{", "}"]);
      let result = "";
      let isEscaped = false;
      for (const c of pattern) {
        if (!isEscaped) {
          if (forbidden.has(c)) {
            throw new protocol_js_1.InvalidArgumentException("Forbidden characters");
          }
          if (c === "\\") {
            isEscaped = true;
            continue;
          }
        }
        result += c;
        isEscaped = false;
      }
      return result;
    }
    var FORBIDDEN_HEADER_NAME_SYMBOLS = /* @__PURE__ */ new Set([
      " ",
      "	",
      "\n",
      '"',
      "(",
      ")",
      ",",
      "/",
      ":",
      ";",
      "<",
      "=",
      ">",
      "?",
      "@",
      "[",
      "\\",
      "]",
      "{",
      "}"
    ]);
    var FORBIDDEN_HEADER_VALUE_SYMBOLS = /* @__PURE__ */ new Set(["\0", "\n", "\r"]);
    function includesChar(str, chars) {
      for (const char of str) {
        if (chars.has(char)) {
          return true;
        }
      }
      return false;
    }
    function parseBiDiHeaders(headers) {
      const parsedHeaders = {};
      for (const bidiHeader of headers) {
        if (bidiHeader.value.type === "string") {
          const name = bidiHeader.name;
          const value = bidiHeader.value.value;
          if (name.length === 0) {
            throw new protocol_js_1.InvalidArgumentException(`Empty header name is not allowed`);
          }
          if (includesChar(name, FORBIDDEN_HEADER_NAME_SYMBOLS)) {
            throw new protocol_js_1.InvalidArgumentException(`Header name '${name}' contains forbidden symbols`);
          }
          if (includesChar(value, FORBIDDEN_HEADER_VALUE_SYMBOLS)) {
            throw new protocol_js_1.InvalidArgumentException(`Header value '${value}' contains forbidden symbols`);
          }
          if (value.trim() !== value) {
            throw new protocol_js_1.InvalidArgumentException(`Header value should not contain trailing or ending whitespaces`);
          }
          parsedHeaders[bidiHeader.name] = bidiHeader.value.value;
        } else {
          throw new protocol_js_1.UnsupportedOperationException("Only string headers values are supported");
        }
      }
      return parsedHeaders;
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/permissions/PermissionsProcessor.js
var require_PermissionsProcessor = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/permissions/PermissionsProcessor.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PermissionsProcessor = void 0;
    var protocol_js_1 = require_protocol();
    var PermissionsProcessor = class {
      #browserCdpClient;
      constructor(browserCdpClient) {
        this.#browserCdpClient = browserCdpClient;
      }
      async setPermissions(params) {
        try {
          const userContextId = params["goog:userContext"] || params.userContext;
          await this.#browserCdpClient.sendCommand("Browser.setPermission", {
            origin: params.origin,
            embeddedOrigin: params.embeddedOrigin,
            browserContextId: userContextId && userContextId !== "default" ? userContextId : void 0,
            permission: {
              name: params.descriptor.name
            },
            setting: params.state
          });
        } catch (err) {
          if (err.message === `Permission can't be granted to opaque origins.`) {
            return {};
          }
          throw new protocol_js_1.InvalidArgumentException(err.message);
        }
        return {};
      }
    };
    exports2.PermissionsProcessor = PermissionsProcessor;
  }
});

// node_modules/chromium-bidi/lib/cjs/utils/uuid.js
var require_uuid = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/utils/uuid.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.uuidv4 = uuidv4;
    function bytesToHex(bytes) {
      return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");
    }
    function uuidv4() {
      if ("crypto" in globalThis && "randomUUID" in globalThis.crypto) {
        return globalThis.crypto.randomUUID();
      }
      const randomValues = new Uint8Array(16);
      if ("crypto" in globalThis && "getRandomValues" in globalThis.crypto) {
        globalThis.crypto.getRandomValues(randomValues);
      } else {
        require("crypto").webcrypto.getRandomValues(randomValues);
      }
      randomValues[6] = randomValues[6] & 15 | 64;
      randomValues[8] = randomValues[8] & 63 | 128;
      return [
        bytesToHex(randomValues.subarray(0, 4)),
        bytesToHex(randomValues.subarray(4, 6)),
        bytesToHex(randomValues.subarray(6, 8)),
        bytesToHex(randomValues.subarray(8, 10)),
        bytesToHex(randomValues.subarray(10, 16))
      ].join("-");
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/script/ChannelProxy.js
var require_ChannelProxy = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/script/ChannelProxy.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ChannelProxy = void 0;
    var protocol_js_1 = require_protocol();
    var log_js_1 = require_log();
    var uuid_js_1 = require_uuid();
    var ChannelProxy = class _ChannelProxy {
      #properties;
      #id = (0, uuid_js_1.uuidv4)();
      #logger;
      constructor(channel, logger) {
        this.#properties = channel;
        this.#logger = logger;
      }
      /**
       * Creates a channel proxy in the given realm, initialises listener and
       * returns a handle to `sendMessage` delegate.
       */
      async init(realm, eventManager) {
        const channelHandle = await _ChannelProxy.#createAndGetHandleInRealm(realm);
        const sendMessageHandle = await _ChannelProxy.#createSendMessageHandle(realm, channelHandle);
        void this.#startListener(realm, channelHandle, eventManager);
        return sendMessageHandle;
      }
      /** Gets a ChannelProxy from window and returns its handle. */
      async startListenerFromWindow(realm, eventManager) {
        try {
          const channelHandle = await this.#getHandleFromWindow(realm);
          void this.#startListener(realm, channelHandle, eventManager);
        } catch (error) {
          this.#logger?.(log_js_1.LogType.debugError, error);
        }
      }
      /**
       * Evaluation string which creates a ChannelProxy object on the client side.
       */
      static #createChannelProxyEvalStr() {
        const functionStr = String(() => {
          const queue = [];
          let queueNonEmptyResolver = null;
          return {
            /**
             * Gets a promise, which is resolved as soon as a message occurs
             * in the queue.
             */
            async getMessage() {
              const onMessage = queue.length > 0 ? Promise.resolve() : new Promise((resolve5) => {
                queueNonEmptyResolver = resolve5;
              });
              await onMessage;
              return queue.shift();
            },
            /**
             * Adds a message to the queue.
             * Resolves the pending promise if needed.
             */
            sendMessage(message) {
              queue.push(message);
              if (queueNonEmptyResolver !== null) {
                queueNonEmptyResolver();
                queueNonEmptyResolver = null;
              }
            }
          };
        });
        return `(${functionStr})()`;
      }
      /** Creates a ChannelProxy in the given realm. */
      static async #createAndGetHandleInRealm(realm) {
        const createChannelHandleResult = await realm.cdpClient.sendCommand("Runtime.evaluate", {
          expression: this.#createChannelProxyEvalStr(),
          contextId: realm.executionContextId,
          serializationOptions: {
            serialization: "idOnly"
          }
        });
        if (createChannelHandleResult.exceptionDetails || createChannelHandleResult.result.objectId === void 0) {
          throw new Error(`Cannot create channel`);
        }
        return createChannelHandleResult.result.objectId;
      }
      /** Gets a handle to `sendMessage` delegate from the ChannelProxy handle. */
      static async #createSendMessageHandle(realm, channelHandle) {
        const sendMessageArgResult = await realm.cdpClient.sendCommand("Runtime.callFunctionOn", {
          functionDeclaration: String((channelHandle2) => {
            return channelHandle2.sendMessage;
          }),
          arguments: [{ objectId: channelHandle }],
          executionContextId: realm.executionContextId,
          serializationOptions: {
            serialization: "idOnly"
          }
        });
        return sendMessageArgResult.result.objectId;
      }
      /** Starts listening for the channel events of the provided ChannelProxy. */
      async #startListener(realm, channelHandle, eventManager) {
        for (; ; ) {
          try {
            const message = await realm.cdpClient.sendCommand("Runtime.callFunctionOn", {
              functionDeclaration: String(async (channelHandle2) => await channelHandle2.getMessage()),
              arguments: [
                {
                  objectId: channelHandle
                }
              ],
              awaitPromise: true,
              executionContextId: realm.executionContextId,
              serializationOptions: {
                serialization: "deep",
                maxDepth: this.#properties.serializationOptions?.maxObjectDepth ?? void 0
              }
            });
            if (message.exceptionDetails) {
              throw new Error("Runtime.callFunctionOn in ChannelProxy", {
                cause: message.exceptionDetails
              });
            }
            for (const browsingContext of realm.associatedBrowsingContexts) {
              eventManager.registerEvent({
                type: "event",
                method: protocol_js_1.ChromiumBidi.Script.EventNames.Message,
                params: {
                  channel: this.#properties.channel,
                  data: realm.cdpToBidiValue(
                    message,
                    this.#properties.ownership ?? "none"
                    /* Script.ResultOwnership.None */
                  ),
                  source: realm.source
                }
              }, browsingContext.id);
            }
          } catch (error) {
            this.#logger?.(log_js_1.LogType.debugError, error);
            break;
          }
        }
      }
      /**
       * Returns a handle of ChannelProxy from window's property which was set there
       * by `getEvalInWindowStr`. If window property is not set yet, sets a promise
       * resolver to the window property, so that `getEvalInWindowStr` can resolve
       * the promise later on with the channel.
       * This is needed because `getEvalInWindowStr` can be called before or
       * after this method.
       */
      async #getHandleFromWindow(realm) {
        const channelHandleResult = await realm.cdpClient.sendCommand("Runtime.callFunctionOn", {
          functionDeclaration: String((id) => {
            const w = window;
            if (w[id] === void 0) {
              return new Promise((resolve5) => w[id] = resolve5);
            }
            const channelProxy = w[id];
            delete w[id];
            return channelProxy;
          }),
          arguments: [{ value: this.#id }],
          executionContextId: realm.executionContextId,
          awaitPromise: true,
          serializationOptions: {
            serialization: "idOnly"
          }
        });
        if (channelHandleResult.exceptionDetails !== void 0 || channelHandleResult.result.objectId === void 0) {
          throw new Error(`ChannelHandle not found in window["${this.#id}"]`);
        }
        return channelHandleResult.result.objectId;
      }
      /**
       * String to be evaluated to create a ProxyChannel and put it to window.
       * Returns the delegate `sendMessage`. Used to provide an argument for preload
       * script. Does the following:
       * 1. Creates a ChannelProxy.
       * 2. Puts the ChannelProxy to window['${this.#id}'] or resolves the promise
       *    by calling delegate stored in window['${this.#id}'].
       *    This is needed because `#getHandleFromWindow` can be called before or
       *    after this method.
       * 3. Returns the delegate `sendMessage` of the created ChannelProxy.
       */
      getEvalInWindowStr() {
        const delegate = String((id, channelProxy) => {
          const w = window;
          if (w[id] === void 0) {
            w[id] = channelProxy;
          } else {
            w[id](channelProxy);
            delete w[id];
          }
          return channelProxy.sendMessage;
        });
        const channelProxyEval = _ChannelProxy.#createChannelProxyEvalStr();
        return `(${delegate})('${this.#id}',${channelProxyEval})`;
      }
    };
    exports2.ChannelProxy = ChannelProxy;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/script/PreloadScript.js
var require_PreloadScript = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/script/PreloadScript.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PreloadScript = void 0;
    var uuid_js_1 = require_uuid();
    var ChannelProxy_js_1 = require_ChannelProxy();
    var PreloadScript = class {
      /** BiDi ID, an automatically generated UUID. */
      #id = (0, uuid_js_1.uuidv4)();
      /** CDP preload scripts. */
      #cdpPreloadScripts = [];
      /** The script itself, in a format expected by the spec i.e. a function. */
      #functionDeclaration;
      /** Targets, in which the preload script is initialized. */
      #targetIds = /* @__PURE__ */ new Set();
      /** Channels to be added as arguments to functionDeclaration. */
      #channels;
      /** The script sandbox / world name. */
      #sandbox;
      /** The browsing contexts to execute the preload scripts in, if any. */
      #contexts;
      /** The browsing contexts to execute the preload scripts in, if any. */
      #userContexts;
      get id() {
        return this.#id;
      }
      get targetIds() {
        return this.#targetIds;
      }
      constructor(params, logger) {
        this.#channels = params.arguments?.map((a) => new ChannelProxy_js_1.ChannelProxy(a.value, logger)) ?? [];
        this.#functionDeclaration = params.functionDeclaration;
        this.#sandbox = params.sandbox;
        this.#contexts = params.contexts;
        this.#userContexts = params.userContexts;
      }
      /** Channels of the preload script. */
      get channels() {
        return this.#channels;
      }
      /** Contexts of the preload script, if any */
      get contexts() {
        return this.#contexts;
      }
      /** UserContexts of the preload script, if any */
      get userContexts() {
        return this.#userContexts;
      }
      /**
       * String to be evaluated. Wraps user-provided function so that the following
       * steps are run:
       * 1. Create channels.
       * 2. Store the created channels in window.
       * 3. Call the user-provided function with channels as arguments.
       */
      #getEvaluateString() {
        const channelsArgStr = `[${this.channels.map((c) => c.getEvalInWindowStr()).join(", ")}]`;
        return `(()=>{(${this.#functionDeclaration})(...${channelsArgStr})})()`;
      }
      /**
       * Adds the script to the given CDP targets by calling the
       * `Page.addScriptToEvaluateOnNewDocument` command.
       */
      async initInTargets(cdpTargets, runImmediately) {
        await Promise.all(Array.from(cdpTargets).map((cdpTarget) => this.initInTarget(cdpTarget, runImmediately)));
      }
      /**
       * Adds the script to the given CDP target by calling the
       * `Page.addScriptToEvaluateOnNewDocument` command.
       */
      async initInTarget(cdpTarget, runImmediately) {
        const addCdpPreloadScriptResult = await cdpTarget.cdpClient.sendCommand("Page.addScriptToEvaluateOnNewDocument", {
          source: this.#getEvaluateString(),
          worldName: this.#sandbox,
          runImmediately
        });
        this.#cdpPreloadScripts.push({
          target: cdpTarget,
          preloadScriptId: addCdpPreloadScriptResult.identifier
        });
        this.#targetIds.add(cdpTarget.id);
      }
      /**
       * Removes this script from all CDP targets.
       */
      async remove() {
        await Promise.all([
          this.#cdpPreloadScripts.map(async (cdpPreloadScript) => {
            const cdpTarget = cdpPreloadScript.target;
            const cdpPreloadScriptId = cdpPreloadScript.preloadScriptId;
            return await cdpTarget.cdpClient.sendCommand("Page.removeScriptToEvaluateOnNewDocument", {
              identifier: cdpPreloadScriptId
            });
          })
        ]);
      }
      /** Removes the provided cdp target from the list of cdp preload scripts. */
      dispose(cdpTargetId) {
        this.#cdpPreloadScripts = this.#cdpPreloadScripts.filter((cdpPreloadScript) => cdpPreloadScript.target?.id !== cdpTargetId);
        this.#targetIds.delete(cdpTargetId);
      }
    };
    exports2.PreloadScript = PreloadScript;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/script/ScriptProcessor.js
var require_ScriptProcessor = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/script/ScriptProcessor.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ScriptProcessor = void 0;
    var protocol_js_1 = require_protocol();
    var PreloadScript_js_1 = require_PreloadScript();
    var ScriptProcessor = class {
      #eventManager;
      #browsingContextStorage;
      #realmStorage;
      #preloadScriptStorage;
      #userContextStorage;
      #logger;
      constructor(eventManager, browsingContextStorage, realmStorage, preloadScriptStorage, userContextStorage, logger) {
        this.#browsingContextStorage = browsingContextStorage;
        this.#realmStorage = realmStorage;
        this.#preloadScriptStorage = preloadScriptStorage;
        this.#userContextStorage = userContextStorage;
        this.#logger = logger;
        this.#eventManager = eventManager;
        this.#eventManager.addSubscribeHook(protocol_js_1.ChromiumBidi.Script.EventNames.RealmCreated, this.#onRealmCreatedSubscribeHook.bind(this));
      }
      #onRealmCreatedSubscribeHook(contextId) {
        const context = this.#browsingContextStorage.getContext(contextId);
        const contextsToReport = [
          context,
          ...this.#browsingContextStorage.getContext(contextId).allChildren
        ];
        const realms = /* @__PURE__ */ new Set();
        for (const reportContext of contextsToReport) {
          const realmsForContext = this.#realmStorage.findRealms({
            browsingContextId: reportContext.id
          });
          for (const realm of realmsForContext) {
            realms.add(realm);
          }
        }
        for (const realm of realms) {
          this.#eventManager.registerEvent({
            type: "event",
            method: protocol_js_1.ChromiumBidi.Script.EventNames.RealmCreated,
            params: realm.realmInfo
          }, context.id);
        }
        return Promise.resolve();
      }
      async addPreloadScript(params) {
        if (params.userContexts?.length && params.contexts?.length) {
          throw new protocol_js_1.InvalidArgumentException("Both userContexts and contexts cannot be specified.");
        }
        const userContexts = await this.#userContextStorage.verifyUserContextIdList(params.userContexts ?? []);
        const browsingContexts = this.#browsingContextStorage.verifyTopLevelContextsList(params.contexts);
        const preloadScript = new PreloadScript_js_1.PreloadScript(params, this.#logger);
        this.#preloadScriptStorage.add(preloadScript);
        let contextsToRunIn = [];
        if (userContexts.size) {
          contextsToRunIn = this.#browsingContextStorage.getTopLevelContexts().filter((context) => {
            return userContexts.has(context.userContext);
          });
        } else if (browsingContexts.size) {
          contextsToRunIn = [...browsingContexts.values()];
        } else {
          contextsToRunIn = this.#browsingContextStorage.getTopLevelContexts();
        }
        const cdpTargets = new Set(contextsToRunIn.map((context) => context.cdpTarget));
        await preloadScript.initInTargets(cdpTargets, false);
        return {
          script: preloadScript.id
        };
      }
      async removePreloadScript(params) {
        const { script: id } = params;
        const script = this.#preloadScriptStorage.getPreloadScript(id);
        await script.remove();
        this.#preloadScriptStorage.remove(id);
        return {};
      }
      async callFunction(params) {
        const realm = await this.#getRealm(params.target);
        return await realm.callFunction(params.functionDeclaration, params.awaitPromise, params.this, params.arguments, params.resultOwnership, params.serializationOptions, params.userActivation);
      }
      async evaluate(params) {
        const realm = await this.#getRealm(params.target);
        return await realm.evaluate(params.expression, params.awaitPromise, params.resultOwnership, params.serializationOptions, params.userActivation);
      }
      async disown(params) {
        const realm = await this.#getRealm(params.target);
        await Promise.all(params.handles.map(async (handle) => await realm.disown(handle)));
        return {};
      }
      getRealms(params) {
        if (params.context !== void 0) {
          this.#browsingContextStorage.getContext(params.context);
        }
        const realms = this.#realmStorage.findRealms({
          browsingContextId: params.context,
          type: params.type,
          isHidden: false
        }).map((realm) => realm.realmInfo);
        return { realms };
      }
      async #getRealm(target) {
        if ("context" in target) {
          const context = this.#browsingContextStorage.getContext(target.context);
          return await context.getOrCreateUserSandbox(target.sandbox);
        }
        return this.#realmStorage.getRealm({
          realmId: target.realm,
          isHidden: false
        });
      }
    };
    exports2.ScriptProcessor = ScriptProcessor;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/session/SessionProcessor.js
var require_SessionProcessor = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/session/SessionProcessor.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SessionProcessor = void 0;
    var protocol_js_1 = require_protocol();
    var SessionProcessor = class {
      #eventManager;
      #browserCdpClient;
      #initConnection;
      #created = false;
      constructor(eventManager, browserCdpClient, initConnection) {
        this.#eventManager = eventManager;
        this.#browserCdpClient = browserCdpClient;
        this.#initConnection = initConnection;
      }
      status() {
        return { ready: false, message: "already connected" };
      }
      #mergeCapabilities(capabilitiesRequest) {
        const mergedCapabilities = [];
        for (const first of capabilitiesRequest.firstMatch ?? [{}]) {
          const result = {
            ...capabilitiesRequest.alwaysMatch
          };
          for (const key of Object.keys(first)) {
            if (result[key] !== void 0) {
              throw new protocol_js_1.InvalidArgumentException(`Capability ${key} in firstMatch is already defined in alwaysMatch`);
            }
            result[key] = first[key];
          }
          mergedCapabilities.push(result);
        }
        const match = mergedCapabilities.find((c) => c.browserName === "chrome") ?? mergedCapabilities[0] ?? {};
        match.unhandledPromptBehavior = this.#getUnhandledPromptBehavior(match.unhandledPromptBehavior);
        return match;
      }
      #getUnhandledPromptBehavior(capabilityValue) {
        if (capabilityValue === void 0) {
          return void 0;
        }
        if (typeof capabilityValue === "object") {
          return capabilityValue;
        }
        if (typeof capabilityValue !== "string") {
          throw new protocol_js_1.InvalidArgumentException(`Unexpected 'unhandledPromptBehavior' type: ${typeof capabilityValue}`);
        }
        switch (capabilityValue) {
          // `beforeUnload: accept` has higher priority over string capability, as the latest
          // one is set to "fallbackDefault".
          // https://w3c.github.io/webdriver/#dfn-deserialize-as-an-unhandled-prompt-behavior
          // https://w3c.github.io/webdriver/#dfn-get-the-prompt-handler
          case "accept":
          case "accept and notify":
            return {
              default: "accept",
              beforeUnload: "accept"
            };
          case "dismiss":
          case "dismiss and notify":
            return {
              default: "dismiss",
              beforeUnload: "accept"
            };
          case "ignore":
            return {
              default: "ignore",
              beforeUnload: "accept"
            };
          default:
            throw new protocol_js_1.InvalidArgumentException(`Unexpected 'unhandledPromptBehavior' value: ${capabilityValue}`);
        }
      }
      async new(params) {
        if (this.#created) {
          throw new Error("Session has been already created.");
        }
        this.#created = true;
        const matchedCapabitlites = this.#mergeCapabilities(params.capabilities);
        await this.#initConnection(matchedCapabitlites);
        const version = await this.#browserCdpClient.sendCommand("Browser.getVersion");
        return {
          sessionId: "unknown",
          capabilities: {
            ...matchedCapabitlites,
            acceptInsecureCerts: matchedCapabitlites.acceptInsecureCerts ?? false,
            browserName: version.product,
            browserVersion: version.revision,
            platformName: "",
            setWindowRect: false,
            webSocketUrl: "",
            userAgent: version.userAgent
          }
        };
      }
      async subscribe(params, googChannel = null) {
        const subscription = await this.#eventManager.subscribe(params.events, params.contexts ?? [], params.userContexts ?? [], googChannel);
        return {
          subscription
        };
      }
      async unsubscribe(params, googChannel = null) {
        if ("subscriptions" in params) {
          await this.#eventManager.unsubscribeByIds(params.subscriptions);
          return {};
        }
        await this.#eventManager.unsubscribe(params.events, googChannel);
        return {};
      }
    };
    exports2.SessionProcessor = SessionProcessor;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/storage/StorageProcessor.js
var require_StorageProcessor = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/storage/StorageProcessor.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.StorageProcessor = void 0;
    var protocol_js_1 = require_protocol();
    var assert_js_1 = require_assert2();
    var log_js_1 = require_log();
    var NetworkProcessor_js_1 = require_NetworkProcessor();
    var NetworkUtils_js_1 = require_NetworkUtils();
    var StorageProcessor = class {
      #browserCdpClient;
      #browsingContextStorage;
      #logger;
      constructor(browserCdpClient, browsingContextStorage, logger) {
        this.#browsingContextStorage = browsingContextStorage;
        this.#browserCdpClient = browserCdpClient;
        this.#logger = logger;
      }
      async deleteCookies(params) {
        const partitionKey = this.#expandStoragePartitionSpec(params.partition);
        let cdpResponse;
        try {
          cdpResponse = await this.#browserCdpClient.sendCommand("Storage.getCookies", {
            browserContextId: this.#getCdpBrowserContextId(partitionKey)
          });
        } catch (err) {
          if (this.#isNoSuchUserContextError(err)) {
            throw new protocol_js_1.NoSuchUserContextException(err.message);
          }
          throw err;
        }
        const cdpCookiesToDelete = cdpResponse.cookies.filter(
          // CDP's partition key is the source origin. If the request specifies the
          // `sourceOrigin` partition key, only cookies with the requested source origin
          // are returned.
          (c) => partitionKey.sourceOrigin === void 0 || c.partitionKey?.topLevelSite === partitionKey.sourceOrigin
        ).filter((cdpCookie) => {
          const bidiCookie = (0, NetworkUtils_js_1.cdpToBiDiCookie)(cdpCookie);
          return this.#matchCookie(bidiCookie, params.filter);
        }).map((cookie) => ({
          ...cookie,
          // Set expiry to pass date to delete the cookie.
          expires: 1
        }));
        await this.#browserCdpClient.sendCommand("Storage.setCookies", {
          cookies: cdpCookiesToDelete,
          browserContextId: this.#getCdpBrowserContextId(partitionKey)
        });
        return {
          partitionKey
        };
      }
      async getCookies(params) {
        const partitionKey = this.#expandStoragePartitionSpec(params.partition);
        let cdpResponse;
        try {
          cdpResponse = await this.#browserCdpClient.sendCommand("Storage.getCookies", {
            browserContextId: this.#getCdpBrowserContextId(partitionKey)
          });
        } catch (err) {
          if (this.#isNoSuchUserContextError(err)) {
            throw new protocol_js_1.NoSuchUserContextException(err.message);
          }
          throw err;
        }
        const filteredBiDiCookies = cdpResponse.cookies.filter(
          // CDP's partition key is the source origin. If the request specifies the
          // `sourceOrigin` partition key, only cookies with the requested source origin
          // are returned.
          (c) => partitionKey.sourceOrigin === void 0 || c.partitionKey?.topLevelSite === partitionKey.sourceOrigin
        ).map((c) => (0, NetworkUtils_js_1.cdpToBiDiCookie)(c)).filter((c) => this.#matchCookie(c, params.filter));
        return {
          cookies: filteredBiDiCookies,
          partitionKey
        };
      }
      async setCookie(params) {
        const partitionKey = this.#expandStoragePartitionSpec(params.partition);
        const cdpCookie = (0, NetworkUtils_js_1.bidiToCdpCookie)(params, partitionKey);
        try {
          await this.#browserCdpClient.sendCommand("Storage.setCookies", {
            cookies: [cdpCookie],
            browserContextId: this.#getCdpBrowserContextId(partitionKey)
          });
        } catch (err) {
          if (this.#isNoSuchUserContextError(err)) {
            throw new protocol_js_1.NoSuchUserContextException(err.message);
          }
          this.#logger?.(log_js_1.LogType.debugError, err);
          throw new protocol_js_1.UnableToSetCookieException(err.toString());
        }
        return {
          partitionKey
        };
      }
      #isNoSuchUserContextError(err) {
        return err.message?.startsWith("Failed to find browser context for id");
      }
      #getCdpBrowserContextId(partitionKey) {
        return partitionKey.userContext === "default" ? void 0 : partitionKey.userContext;
      }
      #expandStoragePartitionSpecByBrowsingContext(descriptor) {
        const browsingContextId = descriptor.context;
        const browsingContext = this.#browsingContextStorage.getContext(browsingContextId);
        return {
          userContext: browsingContext.userContext
        };
      }
      #expandStoragePartitionSpecByStorageKey(descriptor) {
        const unsupportedPartitionKeys = /* @__PURE__ */ new Map();
        let sourceOrigin = descriptor.sourceOrigin;
        if (sourceOrigin !== void 0) {
          const url = NetworkProcessor_js_1.NetworkProcessor.parseUrlString(sourceOrigin);
          if (url.origin === "null") {
            sourceOrigin = url.origin;
          } else {
            sourceOrigin = `${url.protocol}//${url.hostname}`;
          }
        }
        for (const [key, value] of Object.entries(descriptor)) {
          if (key !== void 0 && value !== void 0 && !["type", "sourceOrigin", "userContext"].includes(key)) {
            unsupportedPartitionKeys.set(key, value);
          }
        }
        if (unsupportedPartitionKeys.size > 0) {
          this.#logger?.(log_js_1.LogType.debugInfo, `Unsupported partition keys: ${JSON.stringify(Object.fromEntries(unsupportedPartitionKeys))}`);
        }
        const userContext = descriptor.userContext ?? "default";
        return {
          userContext,
          ...sourceOrigin === void 0 ? {} : { sourceOrigin }
        };
      }
      #expandStoragePartitionSpec(partitionSpec) {
        if (partitionSpec === void 0) {
          return { userContext: "default" };
        }
        if (partitionSpec.type === "context") {
          return this.#expandStoragePartitionSpecByBrowsingContext(partitionSpec);
        }
        (0, assert_js_1.assert)(partitionSpec.type === "storageKey", "Unknown partition type");
        return this.#expandStoragePartitionSpecByStorageKey(partitionSpec);
      }
      #matchCookie(cookie, filter) {
        if (filter === void 0) {
          return true;
        }
        return (filter.domain === void 0 || filter.domain === cookie.domain) && (filter.name === void 0 || filter.name === cookie.name) && // `value` contains fields `type` and `value`.
        (filter.value === void 0 || (0, NetworkUtils_js_1.deserializeByteValue)(filter.value) === (0, NetworkUtils_js_1.deserializeByteValue)(cookie.value)) && (filter.path === void 0 || filter.path === cookie.path) && (filter.size === void 0 || filter.size === cookie.size) && (filter.httpOnly === void 0 || filter.httpOnly === cookie.httpOnly) && (filter.secure === void 0 || filter.secure === cookie.secure) && (filter.sameSite === void 0 || filter.sameSite === cookie.sameSite) && (filter.expiry === void 0 || filter.expiry === cookie.expiry);
      }
    };
    exports2.StorageProcessor = StorageProcessor;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/webExtension/WebExtensionProcessor.js
var require_WebExtensionProcessor = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/webExtension/WebExtensionProcessor.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.WebExtensionProcessor = void 0;
    var protocol_js_1 = require_protocol();
    var WebExtensionProcessor = class {
      #browserCdpClient;
      constructor(browserCdpClient) {
        this.#browserCdpClient = browserCdpClient;
      }
      async install(params) {
        switch (params.extensionData.type) {
          case "archivePath":
          case "base64":
            throw new protocol_js_1.UnsupportedOperationException("Archived and Base64 extensions are not supported");
          case "path":
            break;
        }
        try {
          const response = await this.#browserCdpClient.sendCommand("Extensions.loadUnpacked", {
            path: params.extensionData.path
          });
          return {
            extension: response.id
          };
        } catch (err) {
          if (err.message.startsWith("invalid web extension")) {
            throw new protocol_js_1.InvalidWebExtensionException(err.message);
          }
          throw err;
        }
      }
      async uninstall(params) {
        try {
          await this.#browserCdpClient.sendCommand("Extensions.uninstall", {
            id: params.extension
          });
          return {};
        } catch (err) {
          if (err.message === "Uninstall failed. Reason: could not find extension.") {
            throw new protocol_js_1.NoSuchWebExtensionException("no such web extension");
          }
          throw err;
        }
      }
    };
    exports2.WebExtensionProcessor = WebExtensionProcessor;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/OutgoingMessage.js
var require_OutgoingMessage = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/OutgoingMessage.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OutgoingMessage = void 0;
    var OutgoingMessage = class _OutgoingMessage {
      #message;
      #googChannel;
      constructor(message, googChannel = null) {
        this.#message = message;
        this.#googChannel = googChannel;
      }
      static createFromPromise(messagePromise, googChannel) {
        return messagePromise.then((message) => {
          if (message.kind === "success") {
            return {
              kind: "success",
              value: new _OutgoingMessage(message.value, googChannel)
            };
          }
          return message;
        });
      }
      static createResolved(message, googChannel = null) {
        return Promise.resolve({
          kind: "success",
          value: new _OutgoingMessage(message, googChannel)
        });
      }
      get message() {
        return this.#message;
      }
      get googChannel() {
        return this.#googChannel;
      }
    };
    exports2.OutgoingMessage = OutgoingMessage;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/CommandProcessor.js
var require_CommandProcessor = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/CommandProcessor.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CommandProcessor = void 0;
    var protocol_js_1 = require_protocol();
    var EventEmitter_js_1 = require_EventEmitter2();
    var log_js_1 = require_log();
    var BidiNoOpParser_js_1 = require_BidiNoOpParser();
    var BrowserProcessor_js_1 = require_BrowserProcessor();
    var CdpProcessor_js_1 = require_CdpProcessor();
    var BrowsingContextProcessor_js_1 = require_BrowsingContextProcessor();
    var EmulationProcessor_js_1 = require_EmulationProcessor();
    var InputProcessor_js_1 = require_InputProcessor();
    var NetworkProcessor_js_1 = require_NetworkProcessor();
    var PermissionsProcessor_js_1 = require_PermissionsProcessor();
    var ScriptProcessor_js_1 = require_ScriptProcessor();
    var SessionProcessor_js_1 = require_SessionProcessor();
    var StorageProcessor_js_1 = require_StorageProcessor();
    var WebExtensionProcessor_js_1 = require_WebExtensionProcessor();
    var OutgoingMessage_js_1 = require_OutgoingMessage();
    var CommandProcessor = class extends EventEmitter_js_1.EventEmitter {
      // keep-sorted start
      #bluetoothProcessor;
      #browserCdpClient;
      #browserProcessor;
      #browsingContextProcessor;
      #cdpProcessor;
      #emulationProcessor;
      #inputProcessor;
      #networkProcessor;
      #permissionsProcessor;
      #scriptProcessor;
      #sessionProcessor;
      #storageProcessor;
      #webExtensionProcessor;
      // keep-sorted end
      #parser;
      #logger;
      constructor(cdpConnection, browserCdpClient, eventManager, browsingContextStorage, realmStorage, preloadScriptStorage, networkStorage, contextConfigStorage, bluetoothProcessor, userContextStorage, parser2 = new BidiNoOpParser_js_1.BidiNoOpParser(), initConnection, logger) {
        super();
        this.#browserCdpClient = browserCdpClient;
        this.#parser = parser2;
        this.#logger = logger;
        this.#bluetoothProcessor = bluetoothProcessor;
        this.#browserProcessor = new BrowserProcessor_js_1.BrowserProcessor(browserCdpClient, browsingContextStorage, contextConfigStorage, userContextStorage);
        this.#browsingContextProcessor = new BrowsingContextProcessor_js_1.BrowsingContextProcessor(browserCdpClient, browsingContextStorage, userContextStorage, contextConfigStorage, eventManager);
        this.#cdpProcessor = new CdpProcessor_js_1.CdpProcessor(browsingContextStorage, realmStorage, cdpConnection, browserCdpClient);
        this.#emulationProcessor = new EmulationProcessor_js_1.EmulationProcessor(browsingContextStorage, userContextStorage, contextConfigStorage);
        this.#inputProcessor = new InputProcessor_js_1.InputProcessor(browsingContextStorage);
        this.#networkProcessor = new NetworkProcessor_js_1.NetworkProcessor(browsingContextStorage, networkStorage, userContextStorage, contextConfigStorage);
        this.#permissionsProcessor = new PermissionsProcessor_js_1.PermissionsProcessor(browserCdpClient);
        this.#scriptProcessor = new ScriptProcessor_js_1.ScriptProcessor(eventManager, browsingContextStorage, realmStorage, preloadScriptStorage, userContextStorage, logger);
        this.#sessionProcessor = new SessionProcessor_js_1.SessionProcessor(eventManager, browserCdpClient, initConnection);
        this.#storageProcessor = new StorageProcessor_js_1.StorageProcessor(browserCdpClient, browsingContextStorage, logger);
        this.#webExtensionProcessor = new WebExtensionProcessor_js_1.WebExtensionProcessor(browserCdpClient);
      }
      async #processCommand(command2) {
        switch (command2.method) {
          // Bluetooth module
          // keep-sorted start block=yes
          case "bluetooth.disableSimulation":
            return await this.#bluetoothProcessor.disableSimulation(this.#parser.parseDisableSimulationParameters(command2.params));
          case "bluetooth.handleRequestDevicePrompt":
            return await this.#bluetoothProcessor.handleRequestDevicePrompt(this.#parser.parseHandleRequestDevicePromptParams(command2.params));
          case "bluetooth.simulateAdapter":
            return await this.#bluetoothProcessor.simulateAdapter(this.#parser.parseSimulateAdapterParameters(command2.params));
          case "bluetooth.simulateAdvertisement":
            return await this.#bluetoothProcessor.simulateAdvertisement(this.#parser.parseSimulateAdvertisementParameters(command2.params));
          case "bluetooth.simulateCharacteristic":
            return await this.#bluetoothProcessor.simulateCharacteristic(this.#parser.parseSimulateCharacteristicParameters(command2.params));
          case "bluetooth.simulateCharacteristicResponse":
            return await this.#bluetoothProcessor.simulateCharacteristicResponse(this.#parser.parseSimulateCharacteristicResponseParameters(command2.params));
          case "bluetooth.simulateDescriptor":
            return await this.#bluetoothProcessor.simulateDescriptor(this.#parser.parseSimulateDescriptorParameters(command2.params));
          case "bluetooth.simulateDescriptorResponse":
            return await this.#bluetoothProcessor.simulateDescriptorResponse(this.#parser.parseSimulateDescriptorResponseParameters(command2.params));
          case "bluetooth.simulateGattConnectionResponse":
            return await this.#bluetoothProcessor.simulateGattConnectionResponse(this.#parser.parseSimulateGattConnectionResponseParameters(command2.params));
          case "bluetooth.simulateGattDisconnection":
            return await this.#bluetoothProcessor.simulateGattDisconnection(this.#parser.parseSimulateGattDisconnectionParameters(command2.params));
          case "bluetooth.simulatePreconnectedPeripheral":
            return await this.#bluetoothProcessor.simulatePreconnectedPeripheral(this.#parser.parseSimulatePreconnectedPeripheralParameters(command2.params));
          case "bluetooth.simulateService":
            return await this.#bluetoothProcessor.simulateService(this.#parser.parseSimulateServiceParameters(command2.params));
          // keep-sorted end
          // Browser module
          // keep-sorted start block=yes
          case "browser.close":
            return this.#browserProcessor.close();
          case "browser.createUserContext":
            return await this.#browserProcessor.createUserContext(this.#parser.parseCreateUserContextParameters(command2.params));
          case "browser.getClientWindows":
            return await this.#browserProcessor.getClientWindows();
          case "browser.getUserContexts":
            return await this.#browserProcessor.getUserContexts();
          case "browser.removeUserContext":
            return await this.#browserProcessor.removeUserContext(this.#parser.parseRemoveUserContextParameters(command2.params));
          case "browser.setClientWindowState":
            return await this.#browserProcessor.setClientWindowState(this.#parser.parseSetClientWindowStateParameters(command2.params));
          case "browser.setDownloadBehavior":
            return await this.#browserProcessor.setDownloadBehavior(this.#parser.parseSetDownloadBehaviorParameters(command2.params));
          // keep-sorted end
          // Browsing Context module
          // keep-sorted start block=yes
          case "browsingContext.activate":
            return await this.#browsingContextProcessor.activate(this.#parser.parseActivateParams(command2.params));
          case "browsingContext.captureScreenshot":
            return await this.#browsingContextProcessor.captureScreenshot(this.#parser.parseCaptureScreenshotParams(command2.params));
          case "browsingContext.close":
            return await this.#browsingContextProcessor.close(this.#parser.parseCloseParams(command2.params));
          case "browsingContext.create":
            return await this.#browsingContextProcessor.create(this.#parser.parseCreateParams(command2.params));
          case "browsingContext.getTree":
            return this.#browsingContextProcessor.getTree(this.#parser.parseGetTreeParams(command2.params));
          case "browsingContext.handleUserPrompt":
            return await this.#browsingContextProcessor.handleUserPrompt(this.#parser.parseHandleUserPromptParams(command2.params));
          case "browsingContext.locateNodes":
            return await this.#browsingContextProcessor.locateNodes(this.#parser.parseLocateNodesParams(command2.params));
          case "browsingContext.navigate":
            return await this.#browsingContextProcessor.navigate(this.#parser.parseNavigateParams(command2.params));
          case "browsingContext.print":
            return await this.#browsingContextProcessor.print(this.#parser.parsePrintParams(command2.params));
          case "browsingContext.reload":
            return await this.#browsingContextProcessor.reload(this.#parser.parseReloadParams(command2.params));
          case "browsingContext.setViewport":
            return await this.#browsingContextProcessor.setViewport(this.#parser.parseSetViewportParams(command2.params));
          case "browsingContext.traverseHistory":
            return await this.#browsingContextProcessor.traverseHistory(this.#parser.parseTraverseHistoryParams(command2.params));
          // keep-sorted end
          // CDP module
          // keep-sorted start block=yes
          case "goog:cdp.getSession":
            return this.#cdpProcessor.getSession(this.#parser.parseGetSessionParams(command2.params));
          case "goog:cdp.resolveRealm":
            return this.#cdpProcessor.resolveRealm(this.#parser.parseResolveRealmParams(command2.params));
          case "goog:cdp.sendCommand":
            return await this.#cdpProcessor.sendCommand(this.#parser.parseSendCommandParams(command2.params));
          // keep-sorted end
          // Emulation module
          // keep-sorted start block=yes
          case "emulation.setForcedColorsModeThemeOverride":
            this.#parser.parseSetForcedColorsModeThemeOverrideParams(command2.params);
            throw new protocol_js_1.UnsupportedOperationException(`Method ${command2.method} is not implemented.`);
          case "emulation.setGeolocationOverride":
            return await this.#emulationProcessor.setGeolocationOverride(this.#parser.parseSetGeolocationOverrideParams(command2.params));
          case "emulation.setLocaleOverride":
            return await this.#emulationProcessor.setLocaleOverride(this.#parser.parseSetLocaleOverrideParams(command2.params));
          case "emulation.setNetworkConditions":
            return await this.#emulationProcessor.setNetworkConditions(this.#parser.parseSetNetworkConditionsParams(command2.params));
          case "emulation.setScreenOrientationOverride":
            return await this.#emulationProcessor.setScreenOrientationOverride(this.#parser.parseSetScreenOrientationOverrideParams(command2.params));
          case "emulation.setScreenSettingsOverride":
            return await this.#emulationProcessor.setScreenSettingsOverride(this.#parser.parseSetScreenSettingsOverrideParams(command2.params));
          case "emulation.setScriptingEnabled":
            return await this.#emulationProcessor.setScriptingEnabled(this.#parser.parseSetScriptingEnabledParams(command2.params));
          case "emulation.setTimezoneOverride":
            return await this.#emulationProcessor.setTimezoneOverride(this.#parser.parseSetTimezoneOverrideParams(command2.params));
          case "emulation.setTouchOverride":
            return await this.#emulationProcessor.setTouchOverride(this.#parser.parseSetTouchOverrideParams(command2.params));
          case "emulation.setUserAgentOverride":
            return await this.#emulationProcessor.setUserAgentOverrideParams(this.#parser.parseSetUserAgentOverrideParams(command2.params));
          case "userAgentClientHints.setClientHintsOverride":
            return await this.#emulationProcessor.setClientHintsOverride(this.#parser.parseSetClientHintsOverrideParams(command2.params));
          // keep-sorted end
          // Input module
          // keep-sorted start block=yes
          case "input.performActions":
            return await this.#inputProcessor.performActions(this.#parser.parsePerformActionsParams(command2.params));
          case "input.releaseActions":
            return await this.#inputProcessor.releaseActions(this.#parser.parseReleaseActionsParams(command2.params));
          case "input.setFiles":
            return await this.#inputProcessor.setFiles(this.#parser.parseSetFilesParams(command2.params));
          // keep-sorted end
          // Network module
          // keep-sorted start block=yes
          case "network.addDataCollector":
            return await this.#networkProcessor.addDataCollector(this.#parser.parseAddDataCollectorParams(command2.params));
          case "network.addIntercept":
            return await this.#networkProcessor.addIntercept(this.#parser.parseAddInterceptParams(command2.params));
          case "network.continueRequest":
            return await this.#networkProcessor.continueRequest(this.#parser.parseContinueRequestParams(command2.params));
          case "network.continueResponse":
            return await this.#networkProcessor.continueResponse(this.#parser.parseContinueResponseParams(command2.params));
          case "network.continueWithAuth":
            return await this.#networkProcessor.continueWithAuth(this.#parser.parseContinueWithAuthParams(command2.params));
          case "network.disownData":
            return this.#networkProcessor.disownData(this.#parser.parseDisownDataParams(command2.params));
          case "network.failRequest":
            return await this.#networkProcessor.failRequest(this.#parser.parseFailRequestParams(command2.params));
          case "network.getData":
            return await this.#networkProcessor.getData(this.#parser.parseGetDataParams(command2.params));
          case "network.provideResponse":
            return await this.#networkProcessor.provideResponse(this.#parser.parseProvideResponseParams(command2.params));
          case "network.removeDataCollector":
            return await this.#networkProcessor.removeDataCollector(this.#parser.parseRemoveDataCollectorParams(command2.params));
          case "network.removeIntercept":
            return await this.#networkProcessor.removeIntercept(this.#parser.parseRemoveInterceptParams(command2.params));
          case "network.setCacheBehavior":
            return await this.#networkProcessor.setCacheBehavior(this.#parser.parseSetCacheBehaviorParams(command2.params));
          case "network.setExtraHeaders":
            return await this.#networkProcessor.setExtraHeaders(this.#parser.parseSetExtraHeadersParams(command2.params));
          // keep-sorted end
          // Permissions module
          // keep-sorted start block=yes
          case "permissions.setPermission":
            return await this.#permissionsProcessor.setPermissions(this.#parser.parseSetPermissionsParams(command2.params));
          // keep-sorted end
          // Script module
          // keep-sorted start block=yes
          case "script.addPreloadScript":
            return await this.#scriptProcessor.addPreloadScript(this.#parser.parseAddPreloadScriptParams(command2.params));
          case "script.callFunction":
            return await this.#scriptProcessor.callFunction(this.#parser.parseCallFunctionParams(this.#processTargetParams(command2.params)));
          case "script.disown":
            return await this.#scriptProcessor.disown(this.#parser.parseDisownParams(this.#processTargetParams(command2.params)));
          case "script.evaluate":
            return await this.#scriptProcessor.evaluate(this.#parser.parseEvaluateParams(this.#processTargetParams(command2.params)));
          case "script.getRealms":
            return this.#scriptProcessor.getRealms(this.#parser.parseGetRealmsParams(command2.params));
          case "script.removePreloadScript":
            return await this.#scriptProcessor.removePreloadScript(this.#parser.parseRemovePreloadScriptParams(command2.params));
          // keep-sorted end
          // Session module
          // keep-sorted start block=yes
          case "session.end":
            throw new protocol_js_1.UnsupportedOperationException(`Method ${command2.method} is not implemented.`);
          case "session.new":
            return await this.#sessionProcessor.new(command2.params);
          case "session.status":
            return this.#sessionProcessor.status();
          case "session.subscribe":
            return await this.#sessionProcessor.subscribe(this.#parser.parseSubscribeParams(command2.params), command2["goog:channel"]);
          case "session.unsubscribe":
            return await this.#sessionProcessor.unsubscribe(this.#parser.parseUnsubscribeParams(command2.params), command2["goog:channel"]);
          // keep-sorted end
          // Storage module
          // keep-sorted start block=yes
          case "storage.deleteCookies":
            return await this.#storageProcessor.deleteCookies(this.#parser.parseDeleteCookiesParams(command2.params));
          case "storage.getCookies":
            return await this.#storageProcessor.getCookies(this.#parser.parseGetCookiesParams(command2.params));
          case "storage.setCookie":
            return await this.#storageProcessor.setCookie(this.#parser.parseSetCookieParams(command2.params));
          // keep-sorted end
          // WebExtension module
          // keep-sorted start block=yes
          case "webExtension.install":
            return await this.#webExtensionProcessor.install(this.#parser.parseInstallParams(command2.params));
          case "webExtension.uninstall":
            return await this.#webExtensionProcessor.uninstall(this.#parser.parseUninstallParams(command2.params));
        }
        throw new protocol_js_1.UnknownCommandException(`Unknown command '${command2?.method}'.`);
      }
      // Workaround for as zod.union always take the first schema
      // https://github.com/w3c/webdriver-bidi/issues/635
      #processTargetParams(params) {
        if (typeof params === "object" && params && "target" in params && typeof params.target === "object" && params.target && "context" in params.target) {
          delete params.target["realm"];
        }
        return params;
      }
      async processCommand(command2) {
        try {
          const result = await this.#processCommand(command2);
          const response = {
            type: "success",
            id: command2.id,
            result
          };
          this.emit("response", {
            message: OutgoingMessage_js_1.OutgoingMessage.createResolved(response, command2["goog:channel"]),
            event: command2.method
          });
        } catch (e) {
          if (e instanceof protocol_js_1.Exception) {
            this.emit("response", {
              message: OutgoingMessage_js_1.OutgoingMessage.createResolved(e.toErrorResponse(command2.id), command2["goog:channel"]),
              event: command2.method
            });
          } else {
            const error = e;
            this.#logger?.(log_js_1.LogType.bidi, error);
            const errorException = this.#browserCdpClient.isCloseError(e) ? new protocol_js_1.NoSuchFrameException(`Browsing context is gone`) : new protocol_js_1.UnknownErrorException(error.message, error.stack);
            this.emit("response", {
              message: OutgoingMessage_js_1.OutgoingMessage.createResolved(errorException.toErrorResponse(command2.id), command2["goog:channel"]),
              event: command2.method
            });
          }
        }
      }
    };
    exports2.CommandProcessor = CommandProcessor;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/bluetooth/BluetoothProcessor.js
var require_BluetoothProcessor = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/bluetooth/BluetoothProcessor.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BluetoothProcessor = void 0;
    var protocol_js_1 = require_protocol();
    var BluetoothGattItem = class {
      id;
      uuid;
      constructor(id, uuid) {
        this.id = id;
        this.uuid = uuid;
      }
    };
    var BluetoothDescriptor = class extends BluetoothGattItem {
      characteristic;
      constructor(id, uuid, characteristic) {
        super(id, uuid);
        this.characteristic = characteristic;
      }
    };
    var BluetoothCharacteristic = class extends BluetoothGattItem {
      descriptors = /* @__PURE__ */ new Map();
      service;
      constructor(id, uuid, service) {
        super(id, uuid);
        this.service = service;
      }
    };
    var BluetoothService = class extends BluetoothGattItem {
      characteristics = /* @__PURE__ */ new Map();
      device;
      constructor(id, uuid, device) {
        super(id, uuid);
        this.device = device;
      }
    };
    var BluetoothDevice = class {
      address;
      services = /* @__PURE__ */ new Map();
      constructor(address) {
        this.address = address;
      }
    };
    var BluetoothProcessor = class {
      #eventManager;
      #browsingContextStorage;
      #bluetoothDevices = /* @__PURE__ */ new Map();
      // A map from a characteristic id from CDP to its BluetoothCharacteristic object.
      #bluetoothCharacteristics = /* @__PURE__ */ new Map();
      // A map from a descriptor id from CDP to its BluetoothDescriptor object.
      #bluetoothDescriptors = /* @__PURE__ */ new Map();
      constructor(eventManager, browsingContextStorage) {
        this.#eventManager = eventManager;
        this.#browsingContextStorage = browsingContextStorage;
      }
      #getDevice(address) {
        const device = this.#bluetoothDevices.get(address);
        if (!device) {
          throw new protocol_js_1.InvalidArgumentException(`Bluetooth device with address ${address} does not exist`);
        }
        return device;
      }
      #getService(device, serviceUuid) {
        const service = device.services.get(serviceUuid);
        if (!service) {
          throw new protocol_js_1.InvalidArgumentException(`Service with UUID ${serviceUuid} on device ${device.address} does not exist`);
        }
        return service;
      }
      #getCharacteristic(service, characteristicUuid) {
        const characteristic = service.characteristics.get(characteristicUuid);
        if (!characteristic) {
          throw new protocol_js_1.InvalidArgumentException(`Characteristic with UUID ${characteristicUuid} does not exist for service ${service.uuid} on device ${service.device.address}`);
        }
        return characteristic;
      }
      #getDescriptor(characteristic, descriptorUuid) {
        const descriptor = characteristic.descriptors.get(descriptorUuid);
        if (!descriptor) {
          throw new protocol_js_1.InvalidArgumentException(`Descriptor with UUID ${descriptorUuid} does not exist for characteristic ${characteristic.uuid} on service ${characteristic.service.uuid} on device ${characteristic.service.device.address}`);
        }
        return descriptor;
      }
      async simulateAdapter(params) {
        if (params.state === void 0) {
          throw new protocol_js_1.InvalidArgumentException(`Parameter "state" is required for creating a Bluetooth adapter`);
        }
        const context = this.#browsingContextStorage.getContext(params.context);
        await context.cdpTarget.browserCdpClient.sendCommand("BluetoothEmulation.disable");
        this.#bluetoothDevices.clear();
        this.#bluetoothCharacteristics.clear();
        this.#bluetoothDescriptors.clear();
        await context.cdpTarget.browserCdpClient.sendCommand("BluetoothEmulation.enable", {
          state: params.state,
          leSupported: params.leSupported ?? true
        });
        return {};
      }
      async disableSimulation(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        await context.cdpTarget.browserCdpClient.sendCommand("BluetoothEmulation.disable");
        this.#bluetoothDevices.clear();
        this.#bluetoothCharacteristics.clear();
        this.#bluetoothDescriptors.clear();
        return {};
      }
      async simulatePreconnectedPeripheral(params) {
        if (this.#bluetoothDevices.has(params.address)) {
          throw new protocol_js_1.InvalidArgumentException(`Bluetooth device with address ${params.address} already exists`);
        }
        const context = this.#browsingContextStorage.getContext(params.context);
        await context.cdpTarget.browserCdpClient.sendCommand("BluetoothEmulation.simulatePreconnectedPeripheral", {
          address: params.address,
          name: params.name,
          knownServiceUuids: params.knownServiceUuids,
          manufacturerData: params.manufacturerData
        });
        this.#bluetoothDevices.set(params.address, new BluetoothDevice(params.address));
        return {};
      }
      async simulateAdvertisement(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        await context.cdpTarget.browserCdpClient.sendCommand("BluetoothEmulation.simulateAdvertisement", {
          entry: params.scanEntry
        });
        return {};
      }
      async simulateCharacteristic(params) {
        const device = this.#getDevice(params.address);
        const service = this.#getService(device, params.serviceUuid);
        const context = this.#browsingContextStorage.getContext(params.context);
        switch (params.type) {
          case "add": {
            if (params.characteristicProperties === void 0) {
              throw new protocol_js_1.InvalidArgumentException(`Parameter "characteristicProperties" is required for adding a Bluetooth characteristic`);
            }
            if (service.characteristics.has(params.characteristicUuid)) {
              throw new protocol_js_1.InvalidArgumentException(`Characteristic with UUID ${params.characteristicUuid} already exists`);
            }
            const response = await context.cdpTarget.browserCdpClient.sendCommand("BluetoothEmulation.addCharacteristic", {
              serviceId: service.id,
              characteristicUuid: params.characteristicUuid,
              properties: params.characteristicProperties
            });
            const characteristic = new BluetoothCharacteristic(response.characteristicId, params.characteristicUuid, service);
            service.characteristics.set(params.characteristicUuid, characteristic);
            this.#bluetoothCharacteristics.set(characteristic.id, characteristic);
            return {};
          }
          case "remove": {
            if (params.characteristicProperties !== void 0) {
              throw new protocol_js_1.InvalidArgumentException(`Parameter "characteristicProperties" should not be provided for removing a Bluetooth characteristic`);
            }
            const characteristic = this.#getCharacteristic(service, params.characteristicUuid);
            await context.cdpTarget.browserCdpClient.sendCommand("BluetoothEmulation.removeCharacteristic", {
              characteristicId: characteristic.id
            });
            service.characteristics.delete(params.characteristicUuid);
            this.#bluetoothCharacteristics.delete(characteristic.id);
            return {};
          }
          default:
            throw new protocol_js_1.InvalidArgumentException(`Parameter "type" of ${params.type} is not supported`);
        }
      }
      async simulateCharacteristicResponse(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        const device = this.#getDevice(params.address);
        const service = this.#getService(device, params.serviceUuid);
        const characteristic = this.#getCharacteristic(service, params.characteristicUuid);
        await context.cdpTarget.browserCdpClient.sendCommand("BluetoothEmulation.simulateCharacteristicOperationResponse", {
          characteristicId: characteristic.id,
          type: params.type,
          code: params.code,
          ...params.data && {
            data: btoa(String.fromCharCode(...params.data))
          }
        });
        return {};
      }
      async simulateDescriptor(params) {
        const device = this.#getDevice(params.address);
        const service = this.#getService(device, params.serviceUuid);
        const characteristic = this.#getCharacteristic(service, params.characteristicUuid);
        const context = this.#browsingContextStorage.getContext(params.context);
        switch (params.type) {
          case "add": {
            if (characteristic.descriptors.has(params.descriptorUuid)) {
              throw new protocol_js_1.InvalidArgumentException(`Descriptor with UUID ${params.descriptorUuid} already exists`);
            }
            const response = await context.cdpTarget.browserCdpClient.sendCommand("BluetoothEmulation.addDescriptor", {
              characteristicId: characteristic.id,
              descriptorUuid: params.descriptorUuid
            });
            const descriptor = new BluetoothDescriptor(response.descriptorId, params.descriptorUuid, characteristic);
            characteristic.descriptors.set(params.descriptorUuid, descriptor);
            this.#bluetoothDescriptors.set(descriptor.id, descriptor);
            return {};
          }
          case "remove": {
            const descriptor = this.#getDescriptor(characteristic, params.descriptorUuid);
            await context.cdpTarget.browserCdpClient.sendCommand("BluetoothEmulation.removeDescriptor", {
              descriptorId: descriptor.id
            });
            characteristic.descriptors.delete(params.descriptorUuid);
            this.#bluetoothDescriptors.delete(descriptor.id);
            return {};
          }
          default:
            throw new protocol_js_1.InvalidArgumentException(`Parameter "type" of ${params.type} is not supported`);
        }
      }
      async simulateDescriptorResponse(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        const device = this.#getDevice(params.address);
        const service = this.#getService(device, params.serviceUuid);
        const characteristic = this.#getCharacteristic(service, params.characteristicUuid);
        const descriptor = this.#getDescriptor(characteristic, params.descriptorUuid);
        await context.cdpTarget.browserCdpClient.sendCommand("BluetoothEmulation.simulateDescriptorOperationResponse", {
          descriptorId: descriptor.id,
          type: params.type,
          code: params.code,
          ...params.data && {
            data: btoa(String.fromCharCode(...params.data))
          }
        });
        return {};
      }
      async simulateGattConnectionResponse(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        await context.cdpTarget.browserCdpClient.sendCommand("BluetoothEmulation.simulateGATTOperationResponse", {
          address: params.address,
          type: "connection",
          code: params.code
        });
        return {};
      }
      async simulateGattDisconnection(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        await context.cdpTarget.browserCdpClient.sendCommand("BluetoothEmulation.simulateGATTDisconnection", {
          address: params.address
        });
        return {};
      }
      async simulateService(params) {
        const device = this.#getDevice(params.address);
        const context = this.#browsingContextStorage.getContext(params.context);
        switch (params.type) {
          case "add": {
            if (device.services.has(params.uuid)) {
              throw new protocol_js_1.InvalidArgumentException(`Service with UUID ${params.uuid} already exists`);
            }
            const response = await context.cdpTarget.browserCdpClient.sendCommand("BluetoothEmulation.addService", {
              address: params.address,
              serviceUuid: params.uuid
            });
            device.services.set(params.uuid, new BluetoothService(response.serviceId, params.uuid, device));
            return {};
          }
          case "remove": {
            const service = this.#getService(device, params.uuid);
            await context.cdpTarget.browserCdpClient.sendCommand("BluetoothEmulation.removeService", {
              serviceId: service.id
            });
            device.services.delete(params.uuid);
            return {};
          }
          default:
            throw new protocol_js_1.InvalidArgumentException(`Parameter "type" of ${params.type} is not supported`);
        }
      }
      onCdpTargetCreated(cdpTarget) {
        cdpTarget.cdpClient.on("DeviceAccess.deviceRequestPrompted", (event) => {
          this.#eventManager.registerEvent({
            type: "event",
            method: "bluetooth.requestDevicePromptUpdated",
            params: {
              context: cdpTarget.id,
              prompt: event.id,
              devices: event.devices
            }
          }, cdpTarget.id);
        });
        cdpTarget.browserCdpClient.on("BluetoothEmulation.gattOperationReceived", async (event) => {
          switch (event.type) {
            case "connection":
              this.#eventManager.registerEvent({
                type: "event",
                method: "bluetooth.gattConnectionAttempted",
                params: {
                  context: cdpTarget.id,
                  address: event.address
                }
              }, cdpTarget.id);
              return;
            case "discovery":
              await cdpTarget.browserCdpClient.sendCommand("BluetoothEmulation.simulateGATTOperationResponse", {
                address: event.address,
                type: "discovery",
                code: 0
              });
          }
        });
        cdpTarget.browserCdpClient.on("BluetoothEmulation.characteristicOperationReceived", (event) => {
          if (!this.#bluetoothCharacteristics.has(event.characteristicId)) {
            return;
          }
          let type;
          if (event.type === "write") {
            if (event.writeType === "write-default-deprecated") {
              return;
            }
            type = event.writeType;
          } else {
            type = event.type;
          }
          const characteristic = this.#bluetoothCharacteristics.get(event.characteristicId);
          this.#eventManager.registerEvent({
            type: "event",
            method: "bluetooth.characteristicEventGenerated",
            params: {
              context: cdpTarget.id,
              address: characteristic.service.device.address,
              serviceUuid: characteristic.service.uuid,
              characteristicUuid: characteristic.uuid,
              type,
              ...event.data && {
                data: Array.from(atob(event.data), (c) => c.charCodeAt(0))
              }
            }
          }, cdpTarget.id);
        });
        cdpTarget.browserCdpClient.on("BluetoothEmulation.descriptorOperationReceived", (event) => {
          if (!this.#bluetoothDescriptors.has(event.descriptorId)) {
            return;
          }
          const descriptor = this.#bluetoothDescriptors.get(event.descriptorId);
          this.#eventManager.registerEvent({
            type: "event",
            method: "bluetooth.descriptorEventGenerated",
            params: {
              context: cdpTarget.id,
              address: descriptor.characteristic.service.device.address,
              serviceUuid: descriptor.characteristic.service.uuid,
              characteristicUuid: descriptor.characteristic.uuid,
              descriptorUuid: descriptor.uuid,
              type: event.type,
              ...event.data && {
                data: Array.from(atob(event.data), (c) => c.charCodeAt(0))
              }
            }
          }, cdpTarget.id);
        });
      }
      async handleRequestDevicePrompt(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        if (params.accept) {
          await context.cdpTarget.cdpClient.sendCommand("DeviceAccess.selectPrompt", {
            id: params.prompt,
            deviceId: params.device
          });
        } else {
          await context.cdpTarget.cdpClient.sendCommand("DeviceAccess.cancelPrompt", {
            id: params.prompt
          });
        }
        return {};
      }
    };
    exports2.BluetoothProcessor = BluetoothProcessor;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/browser/ContextConfig.js
var require_ContextConfig = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/browser/ContextConfig.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ContextConfig = void 0;
    var ContextConfig = class _ContextConfig {
      // keep-sorted start block=yes
      acceptInsecureCerts;
      clientHints;
      devicePixelRatio;
      disableNetworkDurableMessages;
      downloadBehavior;
      emulatedNetworkConditions;
      // Extra headers are kept in CDP format.
      extraHeaders;
      geolocation;
      locale;
      maxTouchPoints;
      prerenderingDisabled;
      screenArea;
      screenOrientation;
      scriptingEnabled;
      // Timezone is kept in CDP format with GMT prefix for offset values.
      timezone;
      userAgent;
      userPromptHandler;
      viewport;
      // keep-sorted end
      /**
       * Merges multiple `ContextConfig` objects. The configs are merged in the order they are
       * provided. For each property, the value from the last config that defines it will be
       * used. The final result will not contain any `undefined` or `null` properties.
       * `undefined` values are ignored. `null` values remove the already set value.
       */
      static merge(...configs) {
        const result = new _ContextConfig();
        for (const config2 of configs) {
          if (!config2) {
            continue;
          }
          for (const key in config2) {
            const value = config2[key];
            if (value === null) {
              delete result[key];
            } else if (value !== void 0) {
              result[key] = value;
            }
          }
        }
        return result;
      }
    };
    exports2.ContextConfig = ContextConfig;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/browser/ContextConfigStorage.js
var require_ContextConfigStorage = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/browser/ContextConfigStorage.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ContextConfigStorage = void 0;
    var ContextConfig_js_1 = require_ContextConfig();
    var ContextConfigStorage = class {
      #global = new ContextConfig_js_1.ContextConfig();
      #userContextConfigs = /* @__PURE__ */ new Map();
      #browsingContextConfigs = /* @__PURE__ */ new Map();
      /**
       * Updates the global configuration. Properties with `undefined` values in the
       * provided `config` are ignored.
       */
      updateGlobalConfig(config2) {
        this.#global = ContextConfig_js_1.ContextConfig.merge(this.#global, config2);
      }
      /**
       * Updates the configuration for a specific browsing context. Properties with
       * `undefined` values in the provided `config` are ignored.
       */
      updateBrowsingContextConfig(browsingContextId, config2) {
        this.#browsingContextConfigs.set(browsingContextId, ContextConfig_js_1.ContextConfig.merge(this.#browsingContextConfigs.get(browsingContextId), config2));
      }
      /**
       * Updates the configuration for a specific user context. Properties with
       * `undefined` values in the provided `config` are ignored.
       */
      updateUserContextConfig(userContext, config2) {
        this.#userContextConfigs.set(userContext, ContextConfig_js_1.ContextConfig.merge(this.#userContextConfigs.get(userContext), config2));
      }
      /**
       * Returns the current global configuration.
       */
      getGlobalConfig() {
        return this.#global;
      }
      /**
       * Extra headers is a special case. The headers from the different levels have to be
       * merged instead of being overridden.
       */
      #getExtraHeaders(topLevelBrowsingContextId, userContext) {
        const globalHeaders = this.#global.extraHeaders ?? {};
        const userContextHeaders = this.#userContextConfigs.get(userContext)?.extraHeaders ?? {};
        const browsingContextHeaders = topLevelBrowsingContextId === void 0 ? {} : this.#browsingContextConfigs.get(topLevelBrowsingContextId)?.extraHeaders ?? {};
        return { ...globalHeaders, ...userContextHeaders, ...browsingContextHeaders };
      }
      /**
       * Calculates the active configuration by merging global, user context, and
       * browsing context settings.
       */
      getActiveConfig(topLevelBrowsingContextId, userContext) {
        let result = ContextConfig_js_1.ContextConfig.merge(this.#global, this.#userContextConfigs.get(userContext));
        if (topLevelBrowsingContextId !== void 0) {
          result = ContextConfig_js_1.ContextConfig.merge(result, this.#browsingContextConfigs.get(topLevelBrowsingContextId));
        }
        const extraHeaders = this.#getExtraHeaders(topLevelBrowsingContextId, userContext);
        result.extraHeaders = Object.keys(extraHeaders).length > 0 ? extraHeaders : void 0;
        return result;
      }
    };
    exports2.ContextConfigStorage = ContextConfigStorage;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/browser/UserContextStorage.js
var require_UserContextStorage = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/browser/UserContextStorage.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.UserContextStorage = void 0;
    var protocol_js_1 = require_protocol();
    var UserContextStorage = class {
      #browserClient;
      constructor(browserClient) {
        this.#browserClient = browserClient;
      }
      async getUserContexts() {
        const result = await this.#browserClient.sendCommand("Target.getBrowserContexts");
        return [
          {
            userContext: "default"
          },
          ...result.browserContextIds.map((id) => {
            return {
              userContext: id
            };
          })
        ];
      }
      async verifyUserContextIdList(userContextIds) {
        const foundContexts = /* @__PURE__ */ new Set();
        if (!userContextIds.length) {
          return foundContexts;
        }
        const userContexts = await this.getUserContexts();
        const knownUserContextIds = new Set(userContexts.map((userContext) => userContext.userContext));
        for (const userContextId of userContextIds) {
          if (!knownUserContextIds.has(userContextId)) {
            throw new protocol_js_1.NoSuchUserContextException(`User context ${userContextId} not found`);
          }
          foundContexts.add(userContextId);
        }
        return foundContexts;
      }
    };
    exports2.UserContextStorage = UserContextStorage;
  }
});

// node_modules/chromium-bidi/lib/cjs/utils/Deferred.js
var require_Deferred2 = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/utils/Deferred.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Deferred = void 0;
    var Deferred = class {
      #isFinished = false;
      #promise;
      #result;
      #resolve;
      #reject;
      get isFinished() {
        return this.#isFinished;
      }
      get result() {
        if (!this.#isFinished) {
          throw new Error("Deferred is not finished yet");
        }
        return this.#result;
      }
      constructor() {
        this.#promise = new Promise((resolve5, reject) => {
          this.#resolve = resolve5;
          this.#reject = reject;
        });
        this.#promise.catch((_error) => {
        });
      }
      then(onFulfilled, onRejected) {
        return this.#promise.then(onFulfilled, onRejected);
      }
      catch(onRejected) {
        return this.#promise.catch(onRejected);
      }
      resolve(value) {
        this.#result = value;
        if (!this.#isFinished) {
          this.#isFinished = true;
          this.#resolve(value);
        }
      }
      reject(reason) {
        if (!this.#isFinished) {
          this.#isFinished = true;
          this.#reject(reason);
        }
      }
      finally(onFinally) {
        return this.#promise.finally(onFinally);
      }
      [Symbol.toStringTag] = "Promise";
    };
    exports2.Deferred = Deferred;
  }
});

// node_modules/chromium-bidi/lib/cjs/utils/time.js
var require_time = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/utils/time.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getTimestamp = getTimestamp;
    function getTimestamp() {
      return (/* @__PURE__ */ new Date()).getTime();
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/utils/unitConversions.js
var require_unitConversions = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/utils/unitConversions.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.inchesFromCm = inchesFromCm;
    function inchesFromCm(cm) {
      return cm / 2.54;
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/script/SharedId.js
var require_SharedId = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/script/SharedId.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getSharedId = getSharedId;
    exports2.parseSharedId = parseSharedId;
    var SHARED_ID_DIVIDER = "_element_";
    function getSharedId(frameId, documentId, backendNodeId) {
      return `f.${frameId}.d.${documentId}.e.${backendNodeId}`;
    }
    function parseLegacySharedId(sharedId) {
      const match = sharedId.match(new RegExp(`(.*)${SHARED_ID_DIVIDER}(.*)`));
      if (!match) {
        return null;
      }
      const documentId = match[1];
      const elementId = match[2];
      if (documentId === void 0 || elementId === void 0) {
        return null;
      }
      const backendNodeId = parseInt(elementId ?? "");
      if (isNaN(backendNodeId)) {
        return null;
      }
      return {
        documentId,
        backendNodeId
      };
    }
    function parseSharedId(sharedId) {
      const legacyFormattedSharedId = parseLegacySharedId(sharedId);
      if (legacyFormattedSharedId !== null) {
        return { ...legacyFormattedSharedId, frameId: void 0 };
      }
      const match = sharedId.match(/f\.(.*)\.d\.(.*)\.e\.([0-9]*)/);
      if (!match) {
        return null;
      }
      const frameId = match[1];
      const documentId = match[2];
      const elementId = match[3];
      if (frameId === void 0 || documentId === void 0 || elementId === void 0) {
        return null;
      }
      const backendNodeId = parseInt(elementId ?? "");
      if (isNaN(backendNodeId)) {
        return null;
      }
      return {
        frameId,
        documentId,
        backendNodeId
      };
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/script/Realm.js
var require_Realm2 = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/script/Realm.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Realm = void 0;
    var protocol_js_1 = require_protocol();
    var log_js_1 = require_log();
    var uuid_js_1 = require_uuid();
    var ChannelProxy_js_1 = require_ChannelProxy();
    var Realm = class _Realm {
      #cdpClient;
      #eventManager;
      #executionContextId;
      #logger;
      #origin;
      #realmId;
      realmStorage;
      constructor(cdpClient, eventManager, executionContextId, logger, origin, realmId, realmStorage) {
        this.#cdpClient = cdpClient;
        this.#eventManager = eventManager;
        this.#executionContextId = executionContextId;
        this.#logger = logger;
        this.#origin = origin;
        this.#realmId = realmId;
        this.realmStorage = realmStorage;
        this.realmStorage.addRealm(this);
      }
      cdpToBidiValue(cdpValue, resultOwnership) {
        const bidiValue = this.serializeForBiDi(cdpValue.result.deepSerializedValue, /* @__PURE__ */ new Map());
        if (cdpValue.result.objectId) {
          const objectId = cdpValue.result.objectId;
          if (resultOwnership === "root") {
            bidiValue.handle = objectId;
            this.realmStorage.knownHandlesToRealmMap.set(objectId, this.realmId);
          } else {
            void this.#releaseObject(objectId).catch((error) => this.#logger?.(log_js_1.LogType.debugError, error));
          }
        }
        return bidiValue;
      }
      isHidden() {
        return false;
      }
      /**
       * Relies on the CDP to implement proper BiDi serialization, except:
       * * CDP integer property `backendNodeId` is replaced with `sharedId` of
       * `{documentId}_element_{backendNodeId}`;
       * * CDP integer property `weakLocalObjectReference` is replaced with UUID `internalId`
       * using unique-per serialization `internalIdMap`.
       * * CDP type `platformobject` is replaced with `object`.
       * @param deepSerializedValue - CDP value to be converted to BiDi.
       * @param internalIdMap - Map from CDP integer `weakLocalObjectReference` to BiDi UUID
       * `internalId`.
       */
      serializeForBiDi(deepSerializedValue, internalIdMap) {
        if (Object.hasOwn(deepSerializedValue, "weakLocalObjectReference")) {
          const weakLocalObjectReference = deepSerializedValue.weakLocalObjectReference;
          if (!internalIdMap.has(weakLocalObjectReference)) {
            internalIdMap.set(weakLocalObjectReference, (0, uuid_js_1.uuidv4)());
          }
          deepSerializedValue.internalId = internalIdMap.get(weakLocalObjectReference);
          delete deepSerializedValue["weakLocalObjectReference"];
        }
        if (deepSerializedValue.type === "node" && deepSerializedValue.value && Object.hasOwn(deepSerializedValue.value, "frameId")) {
          delete deepSerializedValue.value["frameId"];
        }
        if (deepSerializedValue.type === "platformobject") {
          return { type: "object" };
        }
        const bidiValue = deepSerializedValue.value;
        if (bidiValue === void 0) {
          return deepSerializedValue;
        }
        if (["array", "set", "htmlcollection", "nodelist"].includes(deepSerializedValue.type)) {
          for (const i in bidiValue) {
            bidiValue[i] = this.serializeForBiDi(bidiValue[i], internalIdMap);
          }
        }
        if (["object", "map"].includes(deepSerializedValue.type)) {
          for (const i in bidiValue) {
            bidiValue[i] = [
              this.serializeForBiDi(bidiValue[i][0], internalIdMap),
              this.serializeForBiDi(bidiValue[i][1], internalIdMap)
            ];
          }
        }
        return deepSerializedValue;
      }
      get realmId() {
        return this.#realmId;
      }
      get executionContextId() {
        return this.#executionContextId;
      }
      get origin() {
        return this.#origin;
      }
      get source() {
        return {
          realm: this.realmId
        };
      }
      get cdpClient() {
        return this.#cdpClient;
      }
      get baseInfo() {
        return {
          realm: this.realmId,
          origin: this.origin
        };
      }
      async evaluate(expression, awaitPromise, resultOwnership = "none", serializationOptions = {}, userActivation = false, includeCommandLineApi = false) {
        const cdpEvaluateResult = await this.cdpClient.sendCommand("Runtime.evaluate", {
          contextId: this.executionContextId,
          expression,
          awaitPromise,
          serializationOptions: _Realm.#getSerializationOptions("deep", serializationOptions),
          userGesture: userActivation,
          includeCommandLineAPI: includeCommandLineApi
        });
        if (cdpEvaluateResult.exceptionDetails) {
          return await this.#getExceptionResult(cdpEvaluateResult.exceptionDetails, 0, resultOwnership);
        }
        return {
          realm: this.realmId,
          result: this.cdpToBidiValue(cdpEvaluateResult, resultOwnership),
          type: "success"
        };
      }
      #registerEvent(event) {
        if (this.associatedBrowsingContexts.length === 0) {
          this.#eventManager.registerGlobalEvent(event);
        } else {
          for (const browsingContext of this.associatedBrowsingContexts) {
            this.#eventManager.registerEvent(event, browsingContext.id);
          }
        }
      }
      initialize() {
        if (!this.isHidden()) {
          this.#registerEvent({
            type: "event",
            method: protocol_js_1.ChromiumBidi.Script.EventNames.RealmCreated,
            params: this.realmInfo
          });
        }
      }
      /**
       * Serializes a given CDP object into BiDi, keeping references in the
       * target's `globalThis`.
       */
      async serializeCdpObject(cdpRemoteObject, resultOwnership) {
        const argument = _Realm.#cdpRemoteObjectToCallArgument(cdpRemoteObject);
        const cdpValue = await this.cdpClient.sendCommand("Runtime.callFunctionOn", {
          functionDeclaration: String((remoteObject) => remoteObject),
          awaitPromise: false,
          arguments: [argument],
          serializationOptions: {
            serialization: "deep"
          },
          executionContextId: this.executionContextId
        });
        return this.cdpToBidiValue(cdpValue, resultOwnership);
      }
      static #cdpRemoteObjectToCallArgument(cdpRemoteObject) {
        if (cdpRemoteObject.objectId !== void 0) {
          return { objectId: cdpRemoteObject.objectId };
        }
        if (cdpRemoteObject.unserializableValue !== void 0) {
          return { unserializableValue: cdpRemoteObject.unserializableValue };
        }
        return { value: cdpRemoteObject.value };
      }
      /**
       * Gets the string representation of an object. This is equivalent to
       * calling `toString()` on the object value.
       */
      async stringifyObject(cdpRemoteObject) {
        const { result } = await this.cdpClient.sendCommand("Runtime.callFunctionOn", {
          functionDeclaration: String((remoteObject) => String(remoteObject)),
          awaitPromise: false,
          arguments: [cdpRemoteObject],
          returnByValue: true,
          executionContextId: this.executionContextId
        });
        return result.value;
      }
      async #flattenKeyValuePairs(mappingLocalValue) {
        const keyValueArray = await Promise.all(mappingLocalValue.map(async ([key, value]) => {
          let keyArg;
          if (typeof key === "string") {
            keyArg = { value: key };
          } else {
            keyArg = await this.deserializeForCdp(key);
          }
          const valueArg = await this.deserializeForCdp(value);
          return [keyArg, valueArg];
        }));
        return keyValueArray.flat();
      }
      async #flattenValueList(listLocalValue) {
        return await Promise.all(listLocalValue.map((localValue) => this.deserializeForCdp(localValue)));
      }
      async #serializeCdpExceptionDetails(cdpExceptionDetails, lineOffset, resultOwnership) {
        const callFrames = cdpExceptionDetails.stackTrace?.callFrames.map((frame) => ({
          url: frame.url,
          functionName: frame.functionName,
          lineNumber: frame.lineNumber - lineOffset,
          columnNumber: frame.columnNumber
        })) ?? [];
        const exception = cdpExceptionDetails.exception;
        return {
          exception: await this.serializeCdpObject(exception, resultOwnership),
          columnNumber: cdpExceptionDetails.columnNumber,
          lineNumber: cdpExceptionDetails.lineNumber - lineOffset,
          stackTrace: {
            callFrames
          },
          text: await this.stringifyObject(exception) || cdpExceptionDetails.text
        };
      }
      async callFunction(functionDeclaration, awaitPromise, thisLocalValue = {
        type: "undefined"
      }, argumentsLocalValues = [], resultOwnership = "none", serializationOptions = {}, userActivation = false) {
        const callFunctionAndSerializeScript = `(...args) => {
      function callFunction(f, args) {
        const deserializedThis = args.shift();
        const deserializedArgs = args;
        return f.apply(deserializedThis, deserializedArgs);
      }
      return callFunction((
        ${functionDeclaration}
      ), args);
    }`;
        const thisAndArgumentsList = [
          await this.deserializeForCdp(thisLocalValue),
          ...await Promise.all(argumentsLocalValues.map(async (argumentLocalValue) => await this.deserializeForCdp(argumentLocalValue)))
        ];
        let cdpCallFunctionResult;
        try {
          cdpCallFunctionResult = await this.cdpClient.sendCommand("Runtime.callFunctionOn", {
            functionDeclaration: callFunctionAndSerializeScript,
            awaitPromise,
            arguments: thisAndArgumentsList,
            serializationOptions: _Realm.#getSerializationOptions("deep", serializationOptions),
            executionContextId: this.executionContextId,
            userGesture: userActivation
          });
        } catch (error) {
          if (error.code === -32e3 && [
            "Could not find object with given id",
            "Argument should belong to the same JavaScript world as target object",
            "Invalid remote object id"
          ].includes(error.message)) {
            throw new protocol_js_1.NoSuchHandleException("Handle was not found.");
          }
          throw error;
        }
        if (cdpCallFunctionResult.exceptionDetails) {
          return await this.#getExceptionResult(cdpCallFunctionResult.exceptionDetails, 1, resultOwnership);
        }
        return {
          type: "success",
          result: this.cdpToBidiValue(cdpCallFunctionResult, resultOwnership),
          realm: this.realmId
        };
      }
      async deserializeForCdp(localValue) {
        if ("handle" in localValue && localValue.handle) {
          return { objectId: localValue.handle };
        } else if ("handle" in localValue || "sharedId" in localValue) {
          throw new protocol_js_1.NoSuchHandleException("Handle was not found.");
        }
        switch (localValue.type) {
          case "undefined":
            return { unserializableValue: "undefined" };
          case "null":
            return { unserializableValue: "null" };
          case "string":
            return { value: localValue.value };
          case "number":
            if (localValue.value === "NaN") {
              return { unserializableValue: "NaN" };
            } else if (localValue.value === "-0") {
              return { unserializableValue: "-0" };
            } else if (localValue.value === "Infinity") {
              return { unserializableValue: "Infinity" };
            } else if (localValue.value === "-Infinity") {
              return { unserializableValue: "-Infinity" };
            }
            return {
              value: localValue.value
            };
          case "boolean":
            return { value: Boolean(localValue.value) };
          case "bigint":
            return {
              unserializableValue: `BigInt(${JSON.stringify(localValue.value)})`
            };
          case "date":
            return {
              unserializableValue: `new Date(Date.parse(${JSON.stringify(localValue.value)}))`
            };
          case "regexp":
            return {
              unserializableValue: `new RegExp(${JSON.stringify(localValue.value.pattern)}, ${JSON.stringify(localValue.value.flags)})`
            };
          case "map": {
            const keyValueArray = await this.#flattenKeyValuePairs(localValue.value);
            const { result } = await this.cdpClient.sendCommand("Runtime.callFunctionOn", {
              functionDeclaration: String((...args2) => {
                const result2 = /* @__PURE__ */ new Map();
                for (let i = 0; i < args2.length; i += 2) {
                  result2.set(args2[i], args2[i + 1]);
                }
                return result2;
              }),
              awaitPromise: false,
              arguments: keyValueArray,
              returnByValue: false,
              executionContextId: this.executionContextId
            });
            return { objectId: result.objectId };
          }
          case "object": {
            const keyValueArray = await this.#flattenKeyValuePairs(localValue.value);
            const { result } = await this.cdpClient.sendCommand("Runtime.callFunctionOn", {
              functionDeclaration: String((...args2) => {
                const result2 = {};
                for (let i = 0; i < args2.length; i += 2) {
                  const key = args2[i];
                  result2[key] = args2[i + 1];
                }
                return result2;
              }),
              awaitPromise: false,
              arguments: keyValueArray,
              returnByValue: false,
              executionContextId: this.executionContextId
            });
            return { objectId: result.objectId };
          }
          case "array": {
            const args2 = await this.#flattenValueList(localValue.value);
            const { result } = await this.cdpClient.sendCommand("Runtime.callFunctionOn", {
              functionDeclaration: String((...args3) => args3),
              awaitPromise: false,
              arguments: args2,
              returnByValue: false,
              executionContextId: this.executionContextId
            });
            return { objectId: result.objectId };
          }
          case "set": {
            const args2 = await this.#flattenValueList(localValue.value);
            const { result } = await this.cdpClient.sendCommand("Runtime.callFunctionOn", {
              functionDeclaration: String((...args3) => new Set(args3)),
              awaitPromise: false,
              arguments: args2,
              returnByValue: false,
              executionContextId: this.executionContextId
            });
            return { objectId: result.objectId };
          }
          case "channel": {
            const channelProxy = new ChannelProxy_js_1.ChannelProxy(localValue.value, this.#logger);
            const channelProxySendMessageHandle = await channelProxy.init(this, this.#eventManager);
            return { objectId: channelProxySendMessageHandle };
          }
        }
        throw new Error(`Value ${JSON.stringify(localValue)} is not deserializable.`);
      }
      async #getExceptionResult(exceptionDetails, lineOffset, resultOwnership) {
        return {
          exceptionDetails: await this.#serializeCdpExceptionDetails(exceptionDetails, lineOffset, resultOwnership),
          realm: this.realmId,
          type: "exception"
        };
      }
      static #getSerializationOptions(serialization, serializationOptions) {
        return {
          serialization,
          additionalParameters: _Realm.#getAdditionalSerializationParameters(serializationOptions),
          ..._Realm.#getMaxObjectDepth(serializationOptions)
        };
      }
      static #getAdditionalSerializationParameters(serializationOptions) {
        const additionalParameters = {};
        if (serializationOptions.maxDomDepth !== void 0) {
          additionalParameters["maxNodeDepth"] = serializationOptions.maxDomDepth === null ? 1e3 : serializationOptions.maxDomDepth;
        }
        if (serializationOptions.includeShadowTree !== void 0) {
          additionalParameters["includeShadowTree"] = serializationOptions.includeShadowTree;
        }
        return additionalParameters;
      }
      static #getMaxObjectDepth(serializationOptions) {
        return serializationOptions.maxObjectDepth === void 0 || serializationOptions.maxObjectDepth === null ? {} : { maxDepth: serializationOptions.maxObjectDepth };
      }
      async #releaseObject(handle) {
        try {
          await this.cdpClient.sendCommand("Runtime.releaseObject", {
            objectId: handle
          });
        } catch (error) {
          if (!(error.code === -32e3 && error.message === "Invalid remote object id")) {
            throw error;
          }
        }
      }
      async disown(handle) {
        if (this.realmStorage.knownHandlesToRealmMap.get(handle) !== this.realmId) {
          return;
        }
        await this.#releaseObject(handle);
        this.realmStorage.knownHandlesToRealmMap.delete(handle);
      }
      dispose() {
        if (!this.isHidden()) {
          this.#registerEvent({
            type: "event",
            method: protocol_js_1.ChromiumBidi.Script.EventNames.RealmDestroyed,
            params: {
              realm: this.realmId
            }
          });
        }
      }
    };
    exports2.Realm = Realm;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/script/WindowRealm.js
var require_WindowRealm = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/script/WindowRealm.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.WindowRealm = void 0;
    var protocol_js_1 = require_protocol();
    var Realm_js_1 = require_Realm2();
    var SharedId_js_1 = require_SharedId();
    var WindowRealm = class extends Realm_js_1.Realm {
      #browsingContextId;
      #browsingContextStorage;
      sandbox;
      constructor(browsingContextId, browsingContextStorage, cdpClient, eventManager, executionContextId, logger, origin, realmId, realmStorage, sandbox) {
        super(cdpClient, eventManager, executionContextId, logger, origin, realmId, realmStorage);
        this.#browsingContextId = browsingContextId;
        this.#browsingContextStorage = browsingContextStorage;
        this.sandbox = sandbox;
        this.initialize();
      }
      #getBrowsingContextId(navigableId) {
        const maybeBrowsingContext = this.#browsingContextStorage.getAllContexts().find((context) => context.navigableId === navigableId);
        return maybeBrowsingContext?.id ?? "UNKNOWN";
      }
      get browsingContext() {
        return this.#browsingContextStorage.getContext(this.#browsingContextId);
      }
      /**
       * Do not expose to user hidden realms.
       */
      isHidden() {
        return this.realmStorage.hiddenSandboxes.has(this.sandbox);
      }
      get associatedBrowsingContexts() {
        return [this.browsingContext];
      }
      get realmType() {
        return "window";
      }
      get realmInfo() {
        return {
          ...this.baseInfo,
          type: this.realmType,
          context: this.#browsingContextId,
          sandbox: this.sandbox
        };
      }
      get source() {
        return {
          realm: this.realmId,
          context: this.browsingContext.id
        };
      }
      serializeForBiDi(deepSerializedValue, internalIdMap) {
        const bidiValue = deepSerializedValue.value;
        if (deepSerializedValue.type === "node" && bidiValue !== void 0) {
          if (Object.hasOwn(bidiValue, "backendNodeId")) {
            let navigableId = this.browsingContext.navigableId ?? "UNKNOWN";
            if (Object.hasOwn(bidiValue, "loaderId")) {
              navigableId = bidiValue.loaderId;
              delete bidiValue["loaderId"];
            }
            deepSerializedValue.sharedId = (0, SharedId_js_1.getSharedId)(this.#getBrowsingContextId(navigableId), navigableId, bidiValue.backendNodeId);
            delete bidiValue["backendNodeId"];
          }
          if (Object.hasOwn(bidiValue, "children")) {
            for (const i in bidiValue.children) {
              bidiValue.children[i] = this.serializeForBiDi(bidiValue.children[i], internalIdMap);
            }
          }
          if (Object.hasOwn(bidiValue, "shadowRoot") && bidiValue.shadowRoot !== null) {
            bidiValue.shadowRoot = this.serializeForBiDi(bidiValue.shadowRoot, internalIdMap);
          }
          if (bidiValue.namespaceURI === "") {
            bidiValue.namespaceURI = null;
          }
        }
        return super.serializeForBiDi(deepSerializedValue, internalIdMap);
      }
      async deserializeForCdp(localValue) {
        if ("sharedId" in localValue && localValue.sharedId) {
          const parsedSharedId = (0, SharedId_js_1.parseSharedId)(localValue.sharedId);
          if (parsedSharedId === null) {
            throw new protocol_js_1.NoSuchNodeException(`SharedId "${localValue.sharedId}" was not found.`);
          }
          const { documentId, backendNodeId } = parsedSharedId;
          if (this.browsingContext.navigableId !== documentId) {
            throw new protocol_js_1.NoSuchNodeException(`SharedId "${localValue.sharedId}" belongs to different document. Current document is ${this.browsingContext.navigableId}.`);
          }
          try {
            const { object } = await this.cdpClient.sendCommand("DOM.resolveNode", {
              backendNodeId,
              executionContextId: this.executionContextId
            });
            return { objectId: object.objectId };
          } catch (error) {
            if (error.code === -32e3 && error.message === "No node with given id found") {
              throw new protocol_js_1.NoSuchNodeException(`SharedId "${localValue.sharedId}" was not found.`);
            }
            throw new protocol_js_1.UnknownErrorException(error.message, error.stack);
          }
        }
        return await super.deserializeForCdp(localValue);
      }
      async evaluate(expression, awaitPromise, resultOwnership, serializationOptions, userActivation, includeCommandLineApi) {
        await this.#browsingContextStorage.getContext(this.#browsingContextId).targetUnblockedOrThrow();
        return await super.evaluate(expression, awaitPromise, resultOwnership, serializationOptions, userActivation, includeCommandLineApi);
      }
      async callFunction(functionDeclaration, awaitPromise, thisLocalValue, argumentsLocalValues, resultOwnership, serializationOptions, userActivation) {
        await this.#browsingContextStorage.getContext(this.#browsingContextId).targetUnblockedOrThrow();
        return await super.callFunction(functionDeclaration, awaitPromise, thisLocalValue, argumentsLocalValues, resultOwnership, serializationOptions, userActivation);
      }
    };
    exports2.WindowRealm = WindowRealm;
  }
});

// node_modules/chromium-bidi/lib/cjs/utils/urlHelpers.js
var require_urlHelpers = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/utils/urlHelpers.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.urlMatchesAboutBlank = urlMatchesAboutBlank;
    function urlMatchesAboutBlank(url) {
      if (url === "") {
        return true;
      }
      try {
        const parsedUrl = new URL(url);
        const schema = parsedUrl.protocol.replace(/:$/, "");
        return schema.toLowerCase() === "about" && parsedUrl.pathname.toLowerCase() === "blank" && parsedUrl.username === "" && parsedUrl.password === "" && parsedUrl.host === "";
      } catch (err) {
        if (err instanceof TypeError) {
          return false;
        }
        throw err;
      }
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/context/NavigationTracker.js
var require_NavigationTracker = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/context/NavigationTracker.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NavigationTracker = exports2.NavigationState = exports2.NavigationResult = void 0;
    var protocol_js_1 = require_protocol();
    var Deferred_js_1 = require_Deferred2();
    var log_js_1 = require_log();
    var time_js_1 = require_time();
    var urlHelpers_js_1 = require_urlHelpers();
    var uuid_js_1 = require_uuid();
    var NavigationResult = class {
      eventName;
      message;
      constructor(eventName, message) {
        this.eventName = eventName;
        this.message = message;
      }
    };
    exports2.NavigationResult = NavigationResult;
    var NavigationState = class {
      navigationId = (0, uuid_js_1.uuidv4)();
      #browsingContextId;
      #started = false;
      #finished = new Deferred_js_1.Deferred();
      url;
      loaderId;
      #isInitial;
      #eventManager;
      committed = new Deferred_js_1.Deferred();
      isFragmentNavigation;
      get finished() {
        return this.#finished;
      }
      constructor(url, browsingContextId, isInitial, eventManager) {
        this.#browsingContextId = browsingContextId;
        this.url = url;
        this.#isInitial = isInitial;
        this.#eventManager = eventManager;
      }
      navigationInfo() {
        return {
          context: this.#browsingContextId,
          navigation: this.navigationId,
          timestamp: (0, time_js_1.getTimestamp)(),
          url: this.url
        };
      }
      start() {
        if (
          // Initial navigation should not be reported.
          !this.#isInitial && // No need in reporting started navigation twice.
          !this.#started && // No need for reporting fragment navigations. Step 13 vs step 16 of the spec:
          // https://html.spec.whatwg.org/#beginning-navigation:webdriver-bidi-navigation-started
          !this.isFragmentNavigation
        ) {
          this.#eventManager.registerEvent({
            type: "event",
            method: protocol_js_1.ChromiumBidi.BrowsingContext.EventNames.NavigationStarted,
            params: this.navigationInfo()
          }, this.#browsingContextId);
        }
        this.#started = true;
      }
      #finish(navigationResult) {
        this.#started = true;
        if (!this.#isInitial && !this.#finished.isFinished && navigationResult.eventName !== "browsingContext.load") {
          this.#eventManager.registerEvent({
            type: "event",
            method: navigationResult.eventName,
            params: this.navigationInfo()
          }, this.#browsingContextId);
        }
        this.#finished.resolve(navigationResult);
      }
      frameNavigated() {
        this.committed.resolve();
        if (!this.#isInitial) {
          this.#eventManager.registerEvent({
            type: "event",
            method: protocol_js_1.ChromiumBidi.BrowsingContext.EventNames.NavigationCommitted,
            params: this.navigationInfo()
          }, this.#browsingContextId);
        }
      }
      fragmentNavigated() {
        this.committed.resolve();
        this.#finish(new NavigationResult(
          "browsingContext.fragmentNavigated"
          /* NavigationEventName.FragmentNavigated */
        ));
      }
      load() {
        this.#finish(new NavigationResult(
          "browsingContext.load"
          /* NavigationEventName.Load */
        ));
      }
      fail(message) {
        this.#finish(new NavigationResult(this.committed.isFinished ? "browsingContext.navigationAborted" : "browsingContext.navigationFailed", message));
      }
    };
    exports2.NavigationState = NavigationState;
    var NavigationTracker = class _NavigationTracker {
      #eventManager;
      #logger;
      #loaderIdToNavigationsMap = /* @__PURE__ */ new Map();
      #browsingContextId;
      /**
       * Last committed navigation is committed, but is not guaranteed to be finished, as it
       * can still wait for `load` or `DOMContentLoaded` events.
       */
      #lastCommittedNavigation;
      /**
       * Pending navigation is a navigation that is started but not yet committed.
       */
      #pendingNavigation;
      // Flags if the initial navigation to `about:blank` is in progress.
      #isInitialNavigation = true;
      constructor(url, browsingContextId, eventManager, logger) {
        this.#browsingContextId = browsingContextId;
        this.#eventManager = eventManager;
        this.#logger = logger;
        this.#isInitialNavigation = true;
        this.#lastCommittedNavigation = new NavigationState(url, browsingContextId, (0, urlHelpers_js_1.urlMatchesAboutBlank)(url), this.#eventManager);
      }
      /**
       * Returns current started ongoing navigation. It can be either a started pending
       * navigation, or one is already navigated.
       */
      get currentNavigationId() {
        if (this.#pendingNavigation?.isFragmentNavigation === false) {
          return this.#pendingNavigation.navigationId;
        }
        return this.#lastCommittedNavigation.navigationId;
      }
      /**
       * Flags if the current navigation relates to the initial to `about:blank` navigation.
       */
      get isInitialNavigation() {
        return this.#isInitialNavigation;
      }
      /**
       * Url of the last navigated navigation.
       */
      get url() {
        return this.#lastCommittedNavigation.url;
      }
      /**
       * Creates a pending navigation e.g. when navigation command is called. Required to
       * provide navigation id before the actual navigation is started. It will be used when
       * navigation started. Can be aborted, failed, fragment navigated, or became a current
       * navigation.
       */
      createPendingNavigation(url, canBeInitialNavigation = false) {
        this.#logger?.(log_js_1.LogType.debug, "createCommandNavigation");
        this.#isInitialNavigation = canBeInitialNavigation && this.#isInitialNavigation && (0, urlHelpers_js_1.urlMatchesAboutBlank)(url);
        this.#pendingNavigation?.fail("navigation canceled by concurrent navigation");
        const navigation = new NavigationState(url, this.#browsingContextId, this.#isInitialNavigation, this.#eventManager);
        this.#pendingNavigation = navigation;
        return navigation;
      }
      dispose() {
        this.#pendingNavigation?.fail("navigation canceled by context disposal");
        this.#lastCommittedNavigation.fail("navigation canceled by context disposal");
      }
      // Update the current url.
      onTargetInfoChanged(url) {
        this.#logger?.(log_js_1.LogType.debug, `onTargetInfoChanged ${url}`);
        this.#lastCommittedNavigation.url = url;
      }
      #getNavigationForFrameNavigated(url, loaderId) {
        if (this.#loaderIdToNavigationsMap.has(loaderId)) {
          return this.#loaderIdToNavigationsMap.get(loaderId);
        }
        if (this.#pendingNavigation !== void 0 && this.#pendingNavigation.loaderId === void 0) {
          return this.#pendingNavigation;
        }
        return this.createPendingNavigation(url, true);
      }
      /**
       * @param {string} unreachableUrl indicated the navigation is actually failed.
       */
      frameNavigated(url, loaderId, unreachableUrl) {
        this.#logger?.(log_js_1.LogType.debug, `frameNavigated ${url}`);
        if (unreachableUrl !== void 0) {
          const navigation2 = this.#loaderIdToNavigationsMap.get(loaderId) ?? this.#pendingNavigation ?? this.createPendingNavigation(unreachableUrl, true);
          navigation2.url = unreachableUrl;
          navigation2.start();
          navigation2.fail("the requested url is unreachable");
          return;
        }
        const navigation = this.#getNavigationForFrameNavigated(url, loaderId);
        if (navigation !== this.#lastCommittedNavigation) {
          this.#lastCommittedNavigation.fail("navigation canceled by concurrent navigation");
        }
        navigation.url = url;
        navigation.loaderId = loaderId;
        this.#loaderIdToNavigationsMap.set(loaderId, navigation);
        navigation.start();
        navigation.frameNavigated();
        this.#lastCommittedNavigation = navigation;
        if (this.#pendingNavigation === navigation) {
          this.#pendingNavigation = void 0;
        }
      }
      navigatedWithinDocument(url, navigationType) {
        this.#logger?.(log_js_1.LogType.debug, `navigatedWithinDocument ${url}, ${navigationType}`);
        this.#lastCommittedNavigation.url = url;
        if (navigationType !== "fragment") {
          return;
        }
        const fragmentNavigation = this.#pendingNavigation?.isFragmentNavigation === true ? this.#pendingNavigation : new NavigationState(url, this.#browsingContextId, false, this.#eventManager);
        fragmentNavigation.fragmentNavigated();
        if (fragmentNavigation === this.#pendingNavigation) {
          this.#pendingNavigation = void 0;
        }
      }
      /**
       * Required to mark navigation as fully complete.
       * TODO: navigation should be complete when it became the current one on
       * `Page.frameNavigated` or on navigating command finished with a new loader Id.
       */
      loadPageEvent(loaderId) {
        this.#logger?.(log_js_1.LogType.debug, "loadPageEvent");
        this.#isInitialNavigation = false;
        this.#loaderIdToNavigationsMap.get(loaderId)?.load();
      }
      /**
       * Fail navigation due to navigation command failed.
       */
      failNavigation(navigation, errorText) {
        this.#logger?.(log_js_1.LogType.debug, "failCommandNavigation");
        navigation.fail(errorText);
      }
      /**
       * Updates the navigation's `loaderId` and sets it as current one, if it is a
       * cross-document navigation.
       */
      navigationCommandFinished(navigation, loaderId) {
        this.#logger?.(log_js_1.LogType.debug, `finishCommandNavigation ${navigation.navigationId}, ${loaderId}`);
        if (loaderId !== void 0) {
          navigation.loaderId = loaderId;
          this.#loaderIdToNavigationsMap.set(loaderId, navigation);
        }
        navigation.isFragmentNavigation = loaderId === void 0;
      }
      frameStartedNavigating(url, loaderId, navigationType) {
        this.#logger?.(log_js_1.LogType.debug, `frameStartedNavigating ${url}, ${loaderId}`);
        if (this.#pendingNavigation && this.#pendingNavigation?.loaderId !== void 0 && this.#pendingNavigation?.loaderId !== loaderId) {
          this.#pendingNavigation?.fail("navigation canceled by concurrent navigation");
          this.#pendingNavigation = void 0;
        }
        if (this.#loaderIdToNavigationsMap.has(loaderId)) {
          const existingNavigation = this.#loaderIdToNavigationsMap.get(loaderId);
          existingNavigation.isFragmentNavigation = _NavigationTracker.#isFragmentNavigation(navigationType);
          this.#pendingNavigation = existingNavigation;
          return;
        }
        const pendingNavigation = this.#pendingNavigation ?? this.createPendingNavigation(url, true);
        this.#loaderIdToNavigationsMap.set(loaderId, pendingNavigation);
        pendingNavigation.isFragmentNavigation = _NavigationTracker.#isFragmentNavigation(navigationType);
        pendingNavigation.url = url;
        pendingNavigation.loaderId = loaderId;
        pendingNavigation.start();
      }
      static #isFragmentNavigation(navigationType) {
        return ["historySameDocument", "sameDocument"].includes(navigationType);
      }
      /**
       * If there is a navigation with the loaderId equals to the network request id, it means
       * that the navigation failed.
       */
      networkLoadingFailed(loaderId, errorText) {
        this.#loaderIdToNavigationsMap.get(loaderId)?.fail(errorText);
      }
    };
    exports2.NavigationTracker = NavigationTracker;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/context/BrowsingContextImpl.js
var require_BrowsingContextImpl = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/context/BrowsingContextImpl.js"(exports2) {
    "use strict";
    init_prefix();
    var _a2;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BrowsingContextImpl = void 0;
    exports2.serializeOrigin = serializeOrigin;
    var protocol_js_1 = require_protocol();
    var assert_js_1 = require_assert2();
    var Deferred_js_1 = require_Deferred2();
    var log_js_1 = require_log();
    var time_js_1 = require_time();
    var unitConversions_js_1 = require_unitConversions();
    var uuid_js_1 = require_uuid();
    var SharedId_js_1 = require_SharedId();
    var WindowRealm_js_1 = require_WindowRealm();
    var NavigationTracker_js_1 = require_NavigationTracker();
    var BrowsingContextImpl = class {
      static LOGGER_PREFIX = `${log_js_1.LogType.debug}:browsingContext`;
      /** Direct children browsing contexts. */
      #children = /* @__PURE__ */ new Set();
      /** The ID of this browsing context. */
      #id;
      userContext;
      // Used for running helper scripts.
      #hiddenSandbox = (0, uuid_js_1.uuidv4)();
      #downloadIdToUrlMap = /* @__PURE__ */ new Map();
      /**
       * The ID of the parent browsing context.
       * If null, this is a top-level context.
       */
      #loaderId;
      #parentId = null;
      #originalOpener;
      #lifecycle = {
        DOMContentLoaded: new Deferred_js_1.Deferred(),
        load: new Deferred_js_1.Deferred()
      };
      #cdpTarget;
      #defaultRealmDeferred = new Deferred_js_1.Deferred();
      #browsingContextStorage;
      #eventManager;
      #logger;
      #navigationTracker;
      #realmStorage;
      #configStorage;
      // Set when the user prompt is opened. Required to provide the type in closing event.
      #lastUserPromptType;
      constructor(id, parentId, userContext, cdpTarget, eventManager, browsingContextStorage, realmStorage, configStorage, url, originalOpener, logger) {
        this.#cdpTarget = cdpTarget;
        this.#id = id;
        this.#parentId = parentId;
        this.userContext = userContext;
        this.#eventManager = eventManager;
        this.#browsingContextStorage = browsingContextStorage;
        this.#realmStorage = realmStorage;
        this.#configStorage = configStorage;
        this.#logger = logger;
        this.#originalOpener = originalOpener;
        this.#realmStorage.hiddenSandboxes.add(this.#hiddenSandbox);
        this.#navigationTracker = new NavigationTracker_js_1.NavigationTracker(url, id, eventManager, logger);
      }
      static create(id, parentId, userContext, cdpTarget, eventManager, browsingContextStorage, realmStorage, configStorage, url, originalOpener, logger) {
        const context = new _a2(id, parentId, userContext, cdpTarget, eventManager, browsingContextStorage, realmStorage, configStorage, url, originalOpener, logger);
        context.#initListeners();
        browsingContextStorage.addContext(context);
        if (!context.isTopLevelContext()) {
          context.parent.addChild(context.id);
        }
        eventManager.registerPromiseEvent(context.targetUnblockedOrThrow().then(() => {
          return {
            kind: "success",
            value: {
              type: "event",
              method: protocol_js_1.ChromiumBidi.BrowsingContext.EventNames.ContextCreated,
              params: {
                ...context.serializeToBidiValue(),
                // Hack to provide the initial URL of the context, as it can be changed
                // between the page target is attached and unblocked, as the page is not
                // fully paused in MPArch session (https://crbug.com/372842894).
                // TODO: remove once https://crbug.com/372842894 is addressed.
                url
              }
            }
          };
        }, (error) => {
          return {
            kind: "error",
            error
          };
        }), context.id, protocol_js_1.ChromiumBidi.BrowsingContext.EventNames.ContextCreated);
        return context;
      }
      /**
       * @see https://html.spec.whatwg.org/multipage/document-sequences.html#navigable
       */
      get navigableId() {
        return this.#loaderId;
      }
      get navigationId() {
        return this.#navigationTracker.currentNavigationId;
      }
      dispose(emitContextDestroyed) {
        this.#navigationTracker.dispose();
        this.#realmStorage.deleteRealms({
          browsingContextId: this.id
        });
        if (!this.isTopLevelContext()) {
          this.parent.#children.delete(this.id);
        }
        this.#failLifecycleIfNotFinished();
        if (emitContextDestroyed) {
          this.#eventManager.registerEvent({
            type: "event",
            method: protocol_js_1.ChromiumBidi.BrowsingContext.EventNames.ContextDestroyed,
            params: this.serializeToBidiValue(null)
          }, this.id);
        }
        this.#deleteAllChildren();
        this.#eventManager.clearBufferedEvents(this.id);
        this.#browsingContextStorage.deleteContextById(this.id);
      }
      /** Returns the ID of this context. */
      get id() {
        return this.#id;
      }
      /** Returns the parent context ID. */
      get parentId() {
        return this.#parentId;
      }
      /** Sets the parent context ID and updates parent's children. */
      set parentId(parentId) {
        if (this.#parentId !== null) {
          this.#logger?.(log_js_1.LogType.debugError, "Parent context already set");
          return;
        }
        this.#parentId = parentId;
        if (!this.isTopLevelContext()) {
          this.parent.addChild(this.id);
        }
      }
      /** Returns the parent context. */
      get parent() {
        if (this.parentId === null) {
          return null;
        }
        return this.#browsingContextStorage.getContext(this.parentId);
      }
      /** Returns all direct children contexts. */
      get directChildren() {
        return [...this.#children].map((id) => this.#browsingContextStorage.getContext(id));
      }
      /** Returns all children contexts, flattened. */
      get allChildren() {
        const children = this.directChildren;
        return children.concat(...children.map((child) => child.allChildren));
      }
      /**
       * Returns true if this is a top-level context.
       * This is the case whenever the parent context ID is null.
       */
      isTopLevelContext() {
        return this.#parentId === null;
      }
      get top() {
        let topContext = this;
        let parent = topContext.parent;
        while (parent) {
          topContext = parent;
          parent = topContext.parent;
        }
        return topContext;
      }
      addChild(childId) {
        this.#children.add(childId);
      }
      #deleteAllChildren(emitContextDestroyed = false) {
        this.directChildren.map((child) => child.dispose(emitContextDestroyed));
      }
      get cdpTarget() {
        return this.#cdpTarget;
      }
      updateCdpTarget(cdpTarget) {
        this.#cdpTarget = cdpTarget;
        this.#initListeners();
      }
      get url() {
        return this.#navigationTracker.url;
      }
      async lifecycleLoaded() {
        await this.#lifecycle.load;
      }
      async targetUnblockedOrThrow() {
        const result = await this.#cdpTarget.unblocked;
        if (result.kind === "error") {
          throw result.error;
        }
      }
      /** Returns a sandbox for internal helper scripts which is not exposed to the user.*/
      async getOrCreateHiddenSandbox() {
        return await this.#getOrCreateSandboxInternal(this.#hiddenSandbox);
      }
      /** Returns a sandbox which is exposed to user. */
      async getOrCreateUserSandbox(sandbox) {
        const realm = await this.#getOrCreateSandboxInternal(sandbox);
        if (realm.isHidden()) {
          throw new protocol_js_1.NoSuchFrameException(`Realm "${sandbox}" not found`);
        }
        return realm;
      }
      async #getOrCreateSandboxInternal(sandbox) {
        if (sandbox === void 0 || sandbox === "") {
          return await this.#defaultRealmDeferred;
        }
        let maybeSandboxes = this.#realmStorage.findRealms({
          browsingContextId: this.id,
          sandbox
        });
        if (maybeSandboxes.length === 0) {
          await this.#cdpTarget.cdpClient.sendCommand("Page.createIsolatedWorld", {
            frameId: this.id,
            worldName: sandbox
          });
          maybeSandboxes = this.#realmStorage.findRealms({
            browsingContextId: this.id,
            sandbox
          });
          (0, assert_js_1.assert)(maybeSandboxes.length !== 0);
        }
        return maybeSandboxes[0];
      }
      /**
       * Implements https://w3c.github.io/webdriver-bidi/#get-the-navigable-info.
       */
      serializeToBidiValue(maxDepth = 0, addParentField = true) {
        return {
          context: this.#id,
          url: this.url,
          userContext: this.userContext,
          originalOpener: this.#originalOpener ?? null,
          clientWindow: `${this.cdpTarget.windowId}`,
          children: maxDepth === null || maxDepth > 0 ? this.directChildren.map((c) => c.serializeToBidiValue(maxDepth === null ? maxDepth : maxDepth - 1, false)) : null,
          ...addParentField ? { parent: this.#parentId } : {}
        };
      }
      onTargetInfoChanged(params) {
        this.#navigationTracker.onTargetInfoChanged(params.targetInfo.url);
      }
      #initListeners() {
        this.#cdpTarget.cdpClient.on("Network.loadingFailed", (params) => {
          this.#navigationTracker.networkLoadingFailed(params.requestId, params.errorText);
        });
        this.#cdpTarget.cdpClient.on("Page.fileChooserOpened", (params) => {
          if (this.id !== params.frameId) {
            return;
          }
          if (this.#loaderId === void 0) {
            this.#logger?.(log_js_1.LogType.debugError, "LoaderId should be defined when file upload is shown", params);
            return;
          }
          const element = params.backendNodeId === void 0 ? void 0 : {
            sharedId: (0, SharedId_js_1.getSharedId)(this.id, this.#loaderId, params.backendNodeId)
          };
          this.#eventManager.registerEvent({
            type: "event",
            method: protocol_js_1.ChromiumBidi.Input.EventNames.FileDialogOpened,
            params: {
              context: this.id,
              multiple: params.mode === "selectMultiple",
              element
            }
          }, this.id);
        });
        this.#cdpTarget.cdpClient.on("Page.frameNavigated", (params) => {
          if (this.id !== params.frame.id) {
            return;
          }
          this.#navigationTracker.frameNavigated(
            params.frame.url + (params.frame.urlFragment ?? ""),
            params.frame.loaderId,
            // `unreachableUrl` indicates if the navigation failed.
            params.frame.unreachableUrl
          );
          this.#deleteAllChildren();
          this.#documentChanged(params.frame.loaderId);
        });
        this.#cdpTarget.cdpClient.on("Page.frameStartedNavigating", (params) => {
          if (this.id !== params.frameId) {
            return;
          }
          this.#navigationTracker.frameStartedNavigating(params.url, params.loaderId, params.navigationType);
        });
        this.#cdpTarget.cdpClient.on("Page.navigatedWithinDocument", (params) => {
          if (this.id !== params.frameId) {
            return;
          }
          this.#navigationTracker.navigatedWithinDocument(params.url, params.navigationType);
          if (params.navigationType === "historyApi") {
            this.#eventManager.registerEvent({
              type: "event",
              method: "browsingContext.historyUpdated",
              params: {
                context: this.id,
                timestamp: (0, time_js_1.getTimestamp)(),
                url: this.#navigationTracker.url
              }
            }, this.id);
            return;
          }
        });
        this.#cdpTarget.cdpClient.on("Page.lifecycleEvent", (params) => {
          if (this.id !== params.frameId) {
            return;
          }
          if (params.name === "init") {
            this.#documentChanged(params.loaderId);
            return;
          }
          if (params.name === "commit") {
            this.#loaderId = params.loaderId;
            return;
          }
          if (!this.#loaderId) {
            this.#loaderId = params.loaderId;
          }
          if (params.loaderId !== this.#loaderId) {
            return;
          }
          switch (params.name) {
            case "DOMContentLoaded":
              if (!this.#navigationTracker.isInitialNavigation) {
                this.#eventManager.registerEvent({
                  type: "event",
                  method: protocol_js_1.ChromiumBidi.BrowsingContext.EventNames.DomContentLoaded,
                  params: {
                    context: this.id,
                    navigation: this.#navigationTracker.currentNavigationId,
                    timestamp: (0, time_js_1.getTimestamp)(),
                    url: this.#navigationTracker.url
                  }
                }, this.id);
              }
              this.#lifecycle.DOMContentLoaded.resolve();
              break;
            case "load":
              if (!this.#navigationTracker.isInitialNavigation) {
                this.#eventManager.registerEvent({
                  type: "event",
                  method: protocol_js_1.ChromiumBidi.BrowsingContext.EventNames.Load,
                  params: {
                    context: this.id,
                    navigation: this.#navigationTracker.currentNavigationId,
                    timestamp: (0, time_js_1.getTimestamp)(),
                    url: this.#navigationTracker.url
                  }
                }, this.id);
              }
              this.#navigationTracker.loadPageEvent(params.loaderId);
              this.#lifecycle.load.resolve();
              break;
          }
        });
        this.#cdpTarget.cdpClient.on("Runtime.executionContextCreated", (params) => {
          const { auxData, name, uniqueId, id } = params.context;
          if (!auxData || auxData.frameId !== this.id) {
            return;
          }
          if (auxData.type === "isolated" && name === "") {
            return;
          }
          let origin;
          let sandbox;
          switch (auxData.type) {
            case "isolated":
              sandbox = name;
              if (!this.#defaultRealmDeferred.isFinished) {
                this.#logger?.(log_js_1.LogType.debugError, "Unexpectedly, isolated realm created before the default one");
              }
              origin = this.#defaultRealmDeferred.isFinished ? this.#defaultRealmDeferred.result.origin : (
                // This fallback is not expected to be ever reached.
                ""
              );
              break;
            case "default":
              origin = serializeOrigin(params.context.origin);
              break;
            default:
              return;
          }
          const realm = new WindowRealm_js_1.WindowRealm(this.id, this.#browsingContextStorage, this.#cdpTarget.cdpClient, this.#eventManager, id, this.#logger, origin, uniqueId, this.#realmStorage, sandbox);
          if (auxData.isDefault) {
            this.#defaultRealmDeferred.resolve(realm);
            void Promise.all(this.#cdpTarget.getChannels().map((channel) => channel.startListenerFromWindow(realm, this.#eventManager)));
          }
        });
        this.#cdpTarget.cdpClient.on("Runtime.executionContextDestroyed", (params) => {
          if (this.#defaultRealmDeferred.isFinished && this.#defaultRealmDeferred.result.executionContextId === params.executionContextId) {
            this.#defaultRealmDeferred = new Deferred_js_1.Deferred();
          }
          this.#realmStorage.deleteRealms({
            cdpSessionId: this.#cdpTarget.cdpSessionId,
            executionContextId: params.executionContextId
          });
        });
        this.#cdpTarget.cdpClient.on("Runtime.executionContextsCleared", () => {
          if (!this.#defaultRealmDeferred.isFinished) {
            this.#defaultRealmDeferred.reject(new protocol_js_1.UnknownErrorException("execution contexts cleared"));
          }
          this.#defaultRealmDeferred = new Deferred_js_1.Deferred();
          this.#realmStorage.deleteRealms({
            cdpSessionId: this.#cdpTarget.cdpSessionId
          });
        });
        this.#cdpTarget.cdpClient.on("Page.javascriptDialogClosed", (params) => {
          if (params.frameId && this.id !== params.frameId) {
            return;
          }
          if (!params.frameId && this.#parentId && this.#cdpTarget.cdpClient !== this.#browsingContextStorage.getContext(this.#parentId)?.cdpTarget.cdpClient) {
            return;
          }
          const accepted = params.result;
          if (this.#lastUserPromptType === void 0) {
            this.#logger?.(log_js_1.LogType.debugError, "Unexpectedly no opening prompt event before closing one");
          }
          this.#eventManager.registerEvent({
            type: "event",
            method: protocol_js_1.ChromiumBidi.BrowsingContext.EventNames.UserPromptClosed,
            params: {
              context: this.id,
              accepted,
              // `lastUserPromptType` should never be undefined here, so fallback to
              // `UNKNOWN`. The fallback is required to prevent tests from hanging while
              // waiting for the closing event. The cast is required, as the `UNKNOWN` value
              // is not standard.
              type: this.#lastUserPromptType ?? "UNKNOWN",
              userText: accepted && params.userInput ? params.userInput : void 0
            }
          }, this.id);
          this.#lastUserPromptType = void 0;
        });
        this.#cdpTarget.cdpClient.on("Page.javascriptDialogOpening", (params) => {
          if (params.frameId && this.id !== params.frameId) {
            return;
          }
          if (!params.frameId && this.#parentId && this.#cdpTarget.cdpClient !== this.#browsingContextStorage.getContext(this.#parentId)?.cdpTarget.cdpClient) {
            return;
          }
          const promptType = _a2.#getPromptType(params.type);
          this.#lastUserPromptType = promptType;
          const promptHandler = this.#getPromptHandler(promptType);
          this.#eventManager.registerEvent({
            type: "event",
            method: protocol_js_1.ChromiumBidi.BrowsingContext.EventNames.UserPromptOpened,
            params: {
              context: this.id,
              handler: promptHandler,
              type: promptType,
              message: params.message,
              ...params.type === "prompt" ? { defaultValue: params.defaultPrompt } : {}
            }
          }, this.id);
          switch (promptHandler) {
            // Based on `unhandledPromptBehavior`, check if the prompt should be handled
            // automatically (`accept`, `dismiss`) or wait for the user to do it.
            case "accept":
              void this.handleUserPrompt(true);
              break;
            case "dismiss":
              void this.handleUserPrompt(false);
              break;
            case "ignore":
              break;
          }
        });
        this.#cdpTarget.browserCdpClient.on("Browser.downloadWillBegin", (params) => {
          if (this.id !== params.frameId) {
            return;
          }
          this.#downloadIdToUrlMap.set(params.guid, params.url);
          this.#eventManager.registerEvent({
            type: "event",
            method: protocol_js_1.ChromiumBidi.BrowsingContext.EventNames.DownloadWillBegin,
            params: {
              context: this.id,
              suggestedFilename: params.suggestedFilename,
              navigation: params.guid,
              timestamp: (0, time_js_1.getTimestamp)(),
              url: params.url
            }
          }, this.id);
        });
        this.#cdpTarget.browserCdpClient.on("Browser.downloadProgress", (params) => {
          if (!this.#downloadIdToUrlMap.has(params.guid)) {
            return;
          }
          if (params.state === "inProgress") {
            return;
          }
          const url = this.#downloadIdToUrlMap.get(params.guid);
          switch (params.state) {
            case "canceled":
              this.#eventManager.registerEvent({
                type: "event",
                method: protocol_js_1.ChromiumBidi.BrowsingContext.EventNames.DownloadEnd,
                params: {
                  status: "canceled",
                  context: this.id,
                  navigation: params.guid,
                  timestamp: (0, time_js_1.getTimestamp)(),
                  url
                }
              }, this.id);
              break;
            case "completed":
              this.#eventManager.registerEvent({
                type: "event",
                method: protocol_js_1.ChromiumBidi.BrowsingContext.EventNames.DownloadEnd,
                params: {
                  filepath: params.filePath ?? null,
                  status: "complete",
                  context: this.id,
                  navigation: params.guid,
                  timestamp: (0, time_js_1.getTimestamp)(),
                  url
                }
              }, this.id);
              break;
            default:
              throw new protocol_js_1.UnknownErrorException(`Unknown download state: ${params.state}`);
          }
        });
      }
      static #getPromptType(cdpType) {
        switch (cdpType) {
          case "alert":
            return "alert";
          case "beforeunload":
            return "beforeunload";
          case "confirm":
            return "confirm";
          case "prompt":
            return "prompt";
        }
      }
      /**
       * Returns either custom UserContext's prompt handler, global or default one.
       */
      #getPromptHandler(promptType) {
        const defaultPromptHandler = "dismiss";
        const contextConfig = this.#configStorage.getActiveConfig(this.top.id, this.userContext);
        switch (promptType) {
          case "alert":
            return contextConfig.userPromptHandler?.alert ?? contextConfig.userPromptHandler?.default ?? defaultPromptHandler;
          case "beforeunload":
            return contextConfig.userPromptHandler?.beforeUnload ?? contextConfig.userPromptHandler?.default ?? "accept";
          case "confirm":
            return contextConfig.userPromptHandler?.confirm ?? contextConfig.userPromptHandler?.default ?? defaultPromptHandler;
          case "prompt":
            return contextConfig.userPromptHandler?.prompt ?? contextConfig.userPromptHandler?.default ?? defaultPromptHandler;
        }
      }
      #documentChanged(loaderId) {
        if (loaderId === void 0 || this.#loaderId === loaderId) {
          return;
        }
        this.#resetLifecycleIfFinished();
        this.#loaderId = loaderId;
        this.#deleteAllChildren(true);
      }
      #resetLifecycleIfFinished() {
        if (this.#lifecycle.DOMContentLoaded.isFinished) {
          this.#lifecycle.DOMContentLoaded = new Deferred_js_1.Deferred();
        } else {
          this.#logger?.(_a2.LOGGER_PREFIX, "Document changed (DOMContentLoaded)");
        }
        if (this.#lifecycle.load.isFinished) {
          this.#lifecycle.load = new Deferred_js_1.Deferred();
        } else {
          this.#logger?.(_a2.LOGGER_PREFIX, "Document changed (load)");
        }
      }
      #failLifecycleIfNotFinished() {
        if (!this.#lifecycle.DOMContentLoaded.isFinished) {
          this.#lifecycle.DOMContentLoaded.reject(new protocol_js_1.UnknownErrorException("navigation canceled"));
        }
        if (!this.#lifecycle.load.isFinished) {
          this.#lifecycle.load.reject(new protocol_js_1.UnknownErrorException("navigation canceled"));
        }
      }
      async navigate(url, wait) {
        try {
          new URL(url);
        } catch {
          throw new protocol_js_1.InvalidArgumentException(`Invalid URL: ${url}`);
        }
        const navigationState = this.#navigationTracker.createPendingNavigation(url);
        const cdpNavigatePromise = (async () => {
          const cdpNavigateResult = await this.#cdpTarget.cdpClient.sendCommand("Page.navigate", {
            url,
            frameId: this.id
          });
          if (cdpNavigateResult.errorText) {
            this.#navigationTracker.failNavigation(navigationState, cdpNavigateResult.errorText);
            throw new protocol_js_1.UnknownErrorException(cdpNavigateResult.errorText);
          }
          this.#navigationTracker.navigationCommandFinished(navigationState, cdpNavigateResult.loaderId);
          this.#documentChanged(cdpNavigateResult.loaderId);
        })();
        const result = await Promise.race([
          // No `loaderId` means same-document navigation.
          this.#waitNavigation(wait, cdpNavigatePromise, navigationState),
          // Throw an error if the navigation is canceled.
          navigationState.finished
        ]);
        if (result instanceof NavigationTracker_js_1.NavigationResult) {
          if (
            // TODO: check after decision on the spec is done:
            //  https://github.com/w3c/webdriver-bidi/issues/799.
            result.eventName === "browsingContext.navigationAborted" || result.eventName === "browsingContext.navigationFailed"
          ) {
            throw new protocol_js_1.UnknownErrorException(result.message ?? "unknown exception");
          }
        }
        return {
          navigation: navigationState.navigationId,
          // Url can change due to redirects. Get the one from commandNavigation.
          url: navigationState.url
        };
      }
      async #waitNavigation(wait, cdpCommandPromise, navigationState) {
        await Promise.all([navigationState.committed, cdpCommandPromise]);
        if (wait === "none") {
          return;
        }
        if (navigationState.isFragmentNavigation === true) {
          await navigationState.finished;
          return;
        }
        if (wait === "interactive") {
          await this.#lifecycle.DOMContentLoaded;
          return;
        }
        if (wait === "complete") {
          await this.#lifecycle.load;
          return;
        }
        throw new protocol_js_1.InvalidArgumentException(`Wait condition ${wait} is not supported`);
      }
      // TODO: support concurrent navigations analogous to `navigate`.
      async reload(ignoreCache, wait) {
        await this.targetUnblockedOrThrow();
        this.#resetLifecycleIfFinished();
        const navigationState = this.#navigationTracker.createPendingNavigation(this.#navigationTracker.url);
        const cdpReloadPromise = this.#cdpTarget.cdpClient.sendCommand("Page.reload", {
          ignoreCache
        });
        const result = await Promise.race([
          // No `loaderId` means same-document navigation.
          this.#waitNavigation(wait, cdpReloadPromise, navigationState),
          // Throw an error if the navigation is canceled.
          navigationState.finished
        ]);
        if (result instanceof NavigationTracker_js_1.NavigationResult) {
          if (result.eventName === "browsingContext.navigationAborted" || result.eventName === "browsingContext.navigationFailed") {
            throw new protocol_js_1.UnknownErrorException(result.message ?? "unknown exception");
          }
        }
        return {
          navigation: navigationState.navigationId,
          // Url can change due to redirects. Get the one from commandNavigation.
          url: navigationState.url
        };
      }
      async setViewport(viewport, devicePixelRatio, screenOrientation) {
        const config2 = this.#configStorage.getActiveConfig(this.id, this.userContext);
        await this.cdpTarget.setDeviceMetricsOverride(viewport, devicePixelRatio, screenOrientation, config2.screenArea ?? null);
      }
      async handleUserPrompt(accept, userText) {
        await this.top.#cdpTarget.cdpClient.sendCommand("Page.handleJavaScriptDialog", {
          accept: accept ?? true,
          promptText: userText
        });
      }
      async activate() {
        await this.#cdpTarget.cdpClient.sendCommand("Page.bringToFront");
      }
      async captureScreenshot(params) {
        if (!this.isTopLevelContext()) {
          throw new protocol_js_1.UnsupportedOperationException(`Non-top-level 'context' (${params.context}) is currently not supported`);
        }
        const formatParameters = getImageFormatParameters(params);
        let captureBeyondViewport = false;
        let script;
        params.origin ??= "viewport";
        switch (params.origin) {
          case "document": {
            script = String(() => {
              const element = document.documentElement;
              return {
                x: 0,
                y: 0,
                width: element.scrollWidth,
                height: element.scrollHeight
              };
            });
            captureBeyondViewport = true;
            break;
          }
          case "viewport": {
            script = String(() => {
              const viewport = window.visualViewport;
              return {
                x: viewport.pageLeft,
                y: viewport.pageTop,
                width: viewport.width,
                height: viewport.height
              };
            });
            break;
          }
        }
        const hiddenSandboxRealm = await this.getOrCreateHiddenSandbox();
        const originResult = await hiddenSandboxRealm.callFunction(script, false);
        (0, assert_js_1.assert)(originResult.type === "success");
        const origin = deserializeDOMRect(originResult.result);
        (0, assert_js_1.assert)(origin);
        let rect = origin;
        if (params.clip) {
          const clip = params.clip;
          if (params.origin === "viewport" && clip.type === "box") {
            clip.x += origin.x;
            clip.y += origin.y;
          }
          rect = getIntersectionRect(await this.#parseRect(clip), origin);
        }
        if (rect.width === 0 || rect.height === 0) {
          throw new protocol_js_1.UnableToCaptureScreenException(`Unable to capture screenshot with zero dimensions: width=${rect.width}, height=${rect.height}`);
        }
        return await this.#cdpTarget.cdpClient.sendCommand("Page.captureScreenshot", {
          clip: { ...rect, scale: 1 },
          ...formatParameters,
          captureBeyondViewport
        });
      }
      async print(params) {
        if (!this.isTopLevelContext()) {
          throw new protocol_js_1.UnsupportedOperationException("Printing of non-top level contexts is not supported");
        }
        const cdpParams = {};
        if (params.background !== void 0) {
          cdpParams.printBackground = params.background;
        }
        if (params.margin?.bottom !== void 0) {
          cdpParams.marginBottom = (0, unitConversions_js_1.inchesFromCm)(params.margin.bottom);
        }
        if (params.margin?.left !== void 0) {
          cdpParams.marginLeft = (0, unitConversions_js_1.inchesFromCm)(params.margin.left);
        }
        if (params.margin?.right !== void 0) {
          cdpParams.marginRight = (0, unitConversions_js_1.inchesFromCm)(params.margin.right);
        }
        if (params.margin?.top !== void 0) {
          cdpParams.marginTop = (0, unitConversions_js_1.inchesFromCm)(params.margin.top);
        }
        if (params.orientation !== void 0) {
          cdpParams.landscape = params.orientation === "landscape";
        }
        if (params.page?.height !== void 0) {
          cdpParams.paperHeight = (0, unitConversions_js_1.inchesFromCm)(params.page.height);
        }
        if (params.page?.width !== void 0) {
          cdpParams.paperWidth = (0, unitConversions_js_1.inchesFromCm)(params.page.width);
        }
        if (params.pageRanges !== void 0) {
          for (const range of params.pageRanges) {
            if (typeof range === "number") {
              continue;
            }
            const rangeParts = range.split("-");
            if (rangeParts.length < 1 || rangeParts.length > 2) {
              throw new protocol_js_1.InvalidArgumentException(`Invalid page range: ${range} is not a valid integer range.`);
            }
            if (rangeParts.length === 1) {
              void parseInteger(rangeParts[0] ?? "");
              continue;
            }
            let lowerBound;
            let upperBound;
            const [rangeLowerPart = "", rangeUpperPart = ""] = rangeParts;
            if (rangeLowerPart === "") {
              lowerBound = 1;
            } else {
              lowerBound = parseInteger(rangeLowerPart);
            }
            if (rangeUpperPart === "") {
              upperBound = Number.MAX_SAFE_INTEGER;
            } else {
              upperBound = parseInteger(rangeUpperPart);
            }
            if (lowerBound > upperBound) {
              throw new protocol_js_1.InvalidArgumentException(`Invalid page range: ${rangeLowerPart} > ${rangeUpperPart}`);
            }
          }
          cdpParams.pageRanges = params.pageRanges.join(",");
        }
        if (params.scale !== void 0) {
          cdpParams.scale = params.scale;
        }
        if (params.shrinkToFit !== void 0) {
          cdpParams.preferCSSPageSize = !params.shrinkToFit;
        }
        try {
          const result = await this.#cdpTarget.cdpClient.sendCommand("Page.printToPDF", cdpParams);
          return {
            data: result.data
          };
        } catch (error) {
          if (error.message === "invalid print parameters: content area is empty") {
            throw new protocol_js_1.UnsupportedOperationException(error.message);
          }
          throw error;
        }
      }
      /**
       * See
       * https://w3c.github.io/webdriver-bidi/#:~:text=If%20command%20parameters%20contains%20%22clip%22%3A
       */
      async #parseRect(clip) {
        switch (clip.type) {
          case "box":
            return { x: clip.x, y: clip.y, width: clip.width, height: clip.height };
          case "element": {
            const hiddenSandboxRealm = await this.getOrCreateHiddenSandbox();
            const result = await hiddenSandboxRealm.callFunction(String((element) => {
              return element instanceof Element;
            }), false, { type: "undefined" }, [clip.element]);
            if (result.type === "exception") {
              throw new protocol_js_1.NoSuchElementException(`Element '${clip.element.sharedId}' was not found`);
            }
            (0, assert_js_1.assert)(result.result.type === "boolean");
            if (!result.result.value) {
              throw new protocol_js_1.NoSuchElementException(`Node '${clip.element.sharedId}' is not an Element`);
            }
            {
              const result2 = await hiddenSandboxRealm.callFunction(String((element) => {
                const rect2 = element.getBoundingClientRect();
                return {
                  x: rect2.x,
                  y: rect2.y,
                  height: rect2.height,
                  width: rect2.width
                };
              }), false, { type: "undefined" }, [clip.element]);
              (0, assert_js_1.assert)(result2.type === "success");
              const rect = deserializeDOMRect(result2.result);
              if (!rect) {
                throw new protocol_js_1.UnableToCaptureScreenException(`Could not get bounding box for Element '${clip.element.sharedId}'`);
              }
              return rect;
            }
          }
        }
      }
      async close() {
        await this.#cdpTarget.cdpClient.sendCommand("Page.close");
      }
      async traverseHistory(delta) {
        if (delta === 0) {
          return;
        }
        const history = await this.#cdpTarget.cdpClient.sendCommand("Page.getNavigationHistory");
        const entry = history.entries[history.currentIndex + delta];
        if (!entry) {
          throw new protocol_js_1.NoSuchHistoryEntryException(`No history entry at delta ${delta}`);
        }
        await this.#cdpTarget.cdpClient.sendCommand("Page.navigateToHistoryEntry", {
          entryId: entry.id
        });
      }
      async toggleModulesIfNeeded() {
        await Promise.all([
          this.#cdpTarget.toggleNetworkIfNeeded(),
          this.#cdpTarget.toggleDeviceAccessIfNeeded(),
          this.#cdpTarget.togglePreloadIfNeeded()
        ]);
      }
      async locateNodes(params) {
        return await this.#locateNodesByLocator(await this.#defaultRealmDeferred, params.locator, params.startNodes ?? [], params.maxNodeCount, params.serializationOptions);
      }
      async #getLocatorDelegate(realm, locator, maxNodeCount, startNodes) {
        switch (locator.type) {
          case "context":
            throw new Error("Unreachable");
          case "css":
            return {
              functionDeclaration: String((cssSelector, maxNodeCount2, ...startNodes2) => {
                const locateNodesUsingCss = (element) => {
                  if (!(element instanceof HTMLElement || element instanceof Document || element instanceof DocumentFragment || element instanceof SVGElement)) {
                    throw new Error("startNodes in css selector should be HTMLElement, SVGElement or Document or DocumentFragment");
                  }
                  return [...element.querySelectorAll(cssSelector)];
                };
                startNodes2 = startNodes2.length > 0 ? startNodes2 : [document];
                const returnedNodes = startNodes2.map((startNode) => (
                  // TODO: stop search early if `maxNodeCount` is reached.
                  locateNodesUsingCss(startNode)
                )).flat(1);
                return maxNodeCount2 === 0 ? returnedNodes : returnedNodes.slice(0, maxNodeCount2);
              }),
              argumentsLocalValues: [
                // `cssSelector`
                { type: "string", value: locator.value },
                // `maxNodeCount` with `0` means no limit.
                { type: "number", value: maxNodeCount ?? 0 },
                // `startNodes`
                ...startNodes
              ]
            };
          case "xpath":
            return {
              functionDeclaration: String((xPathSelector, maxNodeCount2, ...startNodes2) => {
                const evaluator = new XPathEvaluator();
                const expression = evaluator.createExpression(xPathSelector);
                const locateNodesUsingXpath = (element) => {
                  const xPathResult = expression.evaluate(element, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
                  const returnedNodes2 = [];
                  for (let i = 0; i < xPathResult.snapshotLength; i++) {
                    returnedNodes2.push(xPathResult.snapshotItem(i));
                  }
                  return returnedNodes2;
                };
                startNodes2 = startNodes2.length > 0 ? startNodes2 : [document];
                const returnedNodes = startNodes2.map((startNode) => (
                  // TODO: stop search early if `maxNodeCount` is reached.
                  locateNodesUsingXpath(startNode)
                )).flat(1);
                return maxNodeCount2 === 0 ? returnedNodes : returnedNodes.slice(0, maxNodeCount2);
              }),
              argumentsLocalValues: [
                // `xPathSelector`
                { type: "string", value: locator.value },
                // `maxNodeCount` with `0` means no limit.
                { type: "number", value: maxNodeCount ?? 0 },
                // `startNodes`
                ...startNodes
              ]
            };
          case "innerText":
            if (locator.value === "") {
              throw new protocol_js_1.InvalidSelectorException("innerText locator cannot be empty");
            }
            return {
              functionDeclaration: String((innerTextSelector, fullMatch, ignoreCase, maxNodeCount2, maxDepth, ...startNodes2) => {
                const searchText = ignoreCase ? innerTextSelector.toUpperCase() : innerTextSelector;
                const locateNodesUsingInnerText = (node, currentMaxDepth) => {
                  const returnedNodes2 = [];
                  if (node instanceof DocumentFragment || node instanceof Document) {
                    const children = [...node.children];
                    children.forEach((child) => (
                      // `currentMaxDepth` is not decremented intentionally according to
                      // https://github.com/w3c/webdriver-bidi/pull/713.
                      returnedNodes2.push(...locateNodesUsingInnerText(child, currentMaxDepth))
                    ));
                    return returnedNodes2;
                  }
                  if (!(node instanceof HTMLElement)) {
                    return [];
                  }
                  const element = node;
                  const nodeInnerText = ignoreCase ? element.innerText?.toUpperCase() : element.innerText;
                  if (!nodeInnerText.includes(searchText)) {
                    return [];
                  }
                  const childNodes = [];
                  for (const child of element.children) {
                    if (child instanceof HTMLElement) {
                      childNodes.push(child);
                    }
                  }
                  if (childNodes.length === 0) {
                    if (fullMatch && nodeInnerText === searchText) {
                      returnedNodes2.push(element);
                    } else {
                      if (!fullMatch) {
                        returnedNodes2.push(element);
                      }
                    }
                  } else {
                    const childNodeMatches = (
                      // Don't search deeper if `maxDepth` is reached.
                      currentMaxDepth <= 0 ? [] : childNodes.map((child) => locateNodesUsingInnerText(child, currentMaxDepth - 1)).flat(1)
                    );
                    if (childNodeMatches.length === 0) {
                      if (!fullMatch || nodeInnerText === searchText) {
                        returnedNodes2.push(element);
                      }
                    } else {
                      returnedNodes2.push(...childNodeMatches);
                    }
                  }
                  return returnedNodes2;
                };
                startNodes2 = startNodes2.length > 0 ? startNodes2 : [document];
                const returnedNodes = startNodes2.map((startNode) => (
                  // TODO: stop search early if `maxNodeCount` is reached.
                  locateNodesUsingInnerText(startNode, maxDepth)
                )).flat(1);
                return maxNodeCount2 === 0 ? returnedNodes : returnedNodes.slice(0, maxNodeCount2);
              }),
              argumentsLocalValues: [
                // `innerTextSelector`
                { type: "string", value: locator.value },
                // `fullMatch` with default `true`.
                { type: "boolean", value: locator.matchType !== "partial" },
                // `ignoreCase` with default `false`.
                { type: "boolean", value: locator.ignoreCase === true },
                // `maxNodeCount` with `0` means no limit.
                { type: "number", value: maxNodeCount ?? 0 },
                // `maxDepth` with default `1000` (same as default full serialization depth).
                { type: "number", value: locator.maxDepth ?? 1e3 },
                // `startNodes`
                ...startNodes
              ]
            };
          case "accessibility": {
            if (!locator.value.name && !locator.value.role) {
              throw new protocol_js_1.InvalidSelectorException("Either name or role has to be specified");
            }
            await Promise.all([
              this.#cdpTarget.cdpClient.sendCommand("Accessibility.enable"),
              this.#cdpTarget.cdpClient.sendCommand("Accessibility.getRootAXNode")
            ]);
            const bindings = await realm.evaluate(
              /* expression=*/
              "({getAccessibleName, getAccessibleRole})",
              /* awaitPromise=*/
              false,
              "root",
              /* serializationOptions= */
              void 0,
              /* userActivation=*/
              false,
              /* includeCommandLineApi=*/
              true
            );
            if (bindings.type !== "success") {
              throw new Error("Could not get bindings");
            }
            if (bindings.result.type !== "object") {
              throw new Error("Could not get bindings");
            }
            return {
              functionDeclaration: String((name, role, bindings2, maxNodeCount2, ...startNodes2) => {
                const returnedNodes = [];
                let aborted = false;
                function collect(contextNodes, selector) {
                  if (aborted) {
                    return;
                  }
                  for (const contextNode of contextNodes) {
                    let match = true;
                    if (selector.role) {
                      const role2 = bindings2.getAccessibleRole(contextNode);
                      if (selector.role !== role2) {
                        match = false;
                      }
                    }
                    if (selector.name) {
                      const name2 = bindings2.getAccessibleName(contextNode);
                      if (selector.name !== name2) {
                        match = false;
                      }
                    }
                    if (match) {
                      if (maxNodeCount2 !== 0 && returnedNodes.length === maxNodeCount2) {
                        aborted = true;
                        break;
                      }
                      returnedNodes.push(contextNode);
                    }
                    const childNodes = [];
                    for (const child of contextNode.children) {
                      if (child instanceof HTMLElement) {
                        childNodes.push(child);
                      }
                    }
                    collect(childNodes, selector);
                  }
                }
                startNodes2 = startNodes2.length > 0 ? startNodes2 : Array.from(document.documentElement.children).filter((c) => c instanceof HTMLElement);
                collect(startNodes2, {
                  role,
                  name
                });
                return returnedNodes;
              }),
              argumentsLocalValues: [
                // `name`
                { type: "string", value: locator.value.name || "" },
                // `role`
                { type: "string", value: locator.value.role || "" },
                // `bindings`.
                { handle: bindings.result.handle },
                // `maxNodeCount` with `0` means no limit.
                { type: "number", value: maxNodeCount ?? 0 },
                // `startNodes`
                ...startNodes
              ]
            };
          }
        }
      }
      async #locateNodesByLocator(realm, locator, startNodes, maxNodeCount, serializationOptions) {
        if (locator.type === "context") {
          if (startNodes.length !== 0) {
            throw new protocol_js_1.InvalidArgumentException("Start nodes are not supported");
          }
          const contextId = locator.value.context;
          if (!contextId) {
            throw new protocol_js_1.InvalidSelectorException("Invalid context");
          }
          const context = this.#browsingContextStorage.getContext(contextId);
          const parent = context.parent;
          if (!parent) {
            throw new protocol_js_1.InvalidArgumentException("This context has no container");
          }
          try {
            const { backendNodeId } = await parent.#cdpTarget.cdpClient.sendCommand("DOM.getFrameOwner", {
              frameId: contextId
            });
            const { object } = await parent.#cdpTarget.cdpClient.sendCommand("DOM.resolveNode", {
              backendNodeId
            });
            const locatorResult2 = await realm.callFunction(`function () { return this; }`, false, { handle: object.objectId }, [], "none", serializationOptions);
            if (locatorResult2.type === "exception") {
              throw new Error("Unknown exception");
            }
            return { nodes: [locatorResult2.result] };
          } catch {
            throw new protocol_js_1.InvalidArgumentException("Context does not exist");
          }
        }
        const locatorDelegate = await this.#getLocatorDelegate(realm, locator, maxNodeCount, startNodes);
        serializationOptions = {
          ...serializationOptions,
          // The returned object is an array of nodes, so no need in deeper JS serialization.
          maxObjectDepth: 1
        };
        const locatorResult = await realm.callFunction(locatorDelegate.functionDeclaration, false, { type: "undefined" }, locatorDelegate.argumentsLocalValues, "none", serializationOptions);
        if (locatorResult.type !== "success") {
          this.#logger?.(_a2.LOGGER_PREFIX, "Failed locateNodesByLocator", locatorResult);
          if (
            // CSS selector.
            locatorResult.exceptionDetails.text?.endsWith("is not a valid selector.") || // XPath selector.
            locatorResult.exceptionDetails.text?.endsWith("is not a valid XPath expression.")
          ) {
            throw new protocol_js_1.InvalidSelectorException(`Not valid selector ${typeof locator.value === "string" ? locator.value : JSON.stringify(locator.value)}`);
          }
          if (locatorResult.exceptionDetails.text === "Error: startNodes in css selector should be HTMLElement, SVGElement or Document or DocumentFragment") {
            throw new protocol_js_1.InvalidArgumentException("startNodes in css selector should be HTMLElement, SVGElement or Document or DocumentFragment");
          }
          throw new protocol_js_1.UnknownErrorException(`Unexpected error in selector script: ${locatorResult.exceptionDetails.text}`);
        }
        if (locatorResult.result.type !== "array") {
          throw new protocol_js_1.UnknownErrorException(`Unexpected selector script result type: ${locatorResult.result.type}`);
        }
        const nodes = locatorResult.result.value.map((value) => {
          if (value.type !== "node") {
            throw new protocol_js_1.UnknownErrorException(`Unexpected selector script result element: ${value.type}`);
          }
          return value;
        });
        return { nodes };
      }
      #getAllRelatedCdpTargets() {
        const targets = /* @__PURE__ */ new Set();
        targets.add(this.cdpTarget);
        this.allChildren.forEach((c) => targets.add(c.cdpTarget));
        return Array.from(targets);
      }
      async setTimezoneOverride(timezone) {
        await Promise.all(this.#getAllRelatedCdpTargets().map(async (cdpTarget) => await cdpTarget.setTimezoneOverride(timezone)));
      }
      async setLocaleOverride(locale) {
        await Promise.all(this.#getAllRelatedCdpTargets().map(async (cdpTarget) => await cdpTarget.setLocaleOverride(locale)));
      }
      async setGeolocationOverride(geolocation) {
        await Promise.all(this.#getAllRelatedCdpTargets().map(async (cdpTarget) => await cdpTarget.setGeolocationOverride(geolocation)));
      }
      async setScriptingEnabled(scriptingEnabled) {
        await Promise.all(this.#getAllRelatedCdpTargets().map(async (cdpTarget) => await cdpTarget.setScriptingEnabled(scriptingEnabled)));
      }
      async setUserAgentAndAcceptLanguage(userAgent, acceptLanguage, clientHints) {
        await Promise.all(this.#getAllRelatedCdpTargets().map(async (cdpTarget) => await cdpTarget.setUserAgentAndAcceptLanguage(userAgent, acceptLanguage, clientHints)));
      }
      async setEmulatedNetworkConditions(networkConditions) {
        await Promise.all(this.#getAllRelatedCdpTargets().map(async (cdpTarget) => await cdpTarget.setEmulatedNetworkConditions(networkConditions)));
      }
      async setTouchOverride(maxTouchPoints) {
        await Promise.allSettled(this.#getAllRelatedCdpTargets().map(async (cdpTarget) => await cdpTarget.setTouchOverride(maxTouchPoints)));
      }
      async setExtraHeaders(cdpExtraHeaders) {
        await Promise.all(this.#getAllRelatedCdpTargets().map(async (cdpTarget) => await cdpTarget.setExtraHeaders(cdpExtraHeaders)));
      }
    };
    exports2.BrowsingContextImpl = BrowsingContextImpl;
    _a2 = BrowsingContextImpl;
    function serializeOrigin(origin) {
      if (["://", ""].includes(origin)) {
        origin = "null";
      }
      return origin;
    }
    function getImageFormatParameters(params) {
      const { quality, type } = params.format ?? {
        type: "image/png"
      };
      switch (type) {
        case "image/png": {
          return { format: "png" };
        }
        case "image/jpeg": {
          return {
            format: "jpeg",
            ...quality === void 0 ? {} : { quality: Math.round(quality * 100) }
          };
        }
        case "image/webp": {
          return {
            format: "webp",
            ...quality === void 0 ? {} : { quality: Math.round(quality * 100) }
          };
        }
      }
      throw new protocol_js_1.InvalidArgumentException(`Image format '${type}' is not a supported format`);
    }
    function deserializeDOMRect(result) {
      if (result.type !== "object" || result.value === void 0) {
        return;
      }
      const x = result.value.find(([key]) => {
        return key === "x";
      })?.[1];
      const y = result.value.find(([key]) => {
        return key === "y";
      })?.[1];
      const height = result.value.find(([key]) => {
        return key === "height";
      })?.[1];
      const width = result.value.find(([key]) => {
        return key === "width";
      })?.[1];
      if (x?.type !== "number" || y?.type !== "number" || height?.type !== "number" || width?.type !== "number") {
        return;
      }
      return {
        x: x.value,
        y: y.value,
        width: width.value,
        height: height.value
      };
    }
    function normalizeRect(box) {
      return {
        ...box.width < 0 ? {
          x: box.x + box.width,
          width: -box.width
        } : {
          x: box.x,
          width: box.width
        },
        ...box.height < 0 ? {
          y: box.y + box.height,
          height: -box.height
        } : {
          y: box.y,
          height: box.height
        }
      };
    }
    function getIntersectionRect(first, second) {
      first = normalizeRect(first);
      second = normalizeRect(second);
      const x = Math.max(first.x, second.x);
      const y = Math.max(first.y, second.y);
      return {
        x,
        y,
        width: Math.max(Math.min(first.x + first.width, second.x + second.width) - x, 0),
        height: Math.max(Math.min(first.y + first.height, second.y + second.height) - y, 0)
      };
    }
    function parseInteger(value) {
      value = value.trim();
      if (!/^[0-9]+$/.test(value)) {
        throw new protocol_js_1.InvalidArgumentException(`Invalid integer: ${value}`);
      }
      return parseInt(value);
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/script/WorkerRealm.js
var require_WorkerRealm = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/script/WorkerRealm.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.WorkerRealm = void 0;
    var Realm_js_1 = require_Realm2();
    var WorkerRealm = class extends Realm_js_1.Realm {
      #realmType;
      #ownerRealms;
      constructor(cdpClient, eventManager, executionContextId, logger, origin, ownerRealms, realmId, realmStorage, realmType) {
        super(cdpClient, eventManager, executionContextId, logger, origin, realmId, realmStorage);
        this.#ownerRealms = ownerRealms;
        this.#realmType = realmType;
        this.initialize();
      }
      get associatedBrowsingContexts() {
        return this.#ownerRealms.flatMap((realm) => realm.associatedBrowsingContexts);
      }
      get realmType() {
        return this.#realmType;
      }
      get source() {
        return {
          realm: this.realmId,
          // This is a hack to make Puppeteer able to track workers.
          // TODO: remove after Puppeteer tracks workers by owners and use the base version.
          context: this.associatedBrowsingContexts[0]?.id
        };
      }
      get realmInfo() {
        const owners = this.#ownerRealms.map((realm) => realm.realmId);
        const { realmType } = this;
        switch (realmType) {
          case "dedicated-worker": {
            const owner = owners[0];
            if (owner === void 0 || owners.length !== 1) {
              throw new Error("Dedicated worker must have exactly one owner");
            }
            return {
              ...this.baseInfo,
              type: realmType,
              owners: [owner]
            };
          }
          case "service-worker":
          case "shared-worker": {
            return {
              ...this.baseInfo,
              type: realmType
            };
          }
        }
      }
    };
    exports2.WorkerRealm = WorkerRealm;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/log/logHelper.js
var require_logHelper = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/log/logHelper.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.logMessageFormatter = logMessageFormatter;
    exports2.getRemoteValuesText = getRemoteValuesText;
    var assert_js_1 = require_assert2();
    var specifiers = ["%s", "%d", "%i", "%f", "%o", "%O", "%c"];
    function isFormatSpecifier(str) {
      return specifiers.some((spec) => str.includes(spec));
    }
    function logMessageFormatter(args2) {
      let output = "";
      const argFormat = args2[0].value.toString();
      const argValues = args2.slice(1, void 0);
      const tokens = argFormat.split(new RegExp(specifiers.map((spec) => `(${spec})`).join("|"), "g"));
      for (const token of tokens) {
        if (token === void 0 || token === "") {
          continue;
        }
        if (isFormatSpecifier(token)) {
          const arg = argValues.shift();
          (0, assert_js_1.assert)(arg, `Less value is provided: "${getRemoteValuesText(args2, false)}"`);
          if (token === "%s") {
            output += stringFromArg(arg);
          } else if (token === "%d" || token === "%i") {
            if (arg.type === "bigint" || arg.type === "number" || arg.type === "string") {
              output += parseInt(arg.value.toString(), 10);
            } else {
              output += "NaN";
            }
          } else if (token === "%f") {
            if (arg.type === "bigint" || arg.type === "number" || arg.type === "string") {
              output += parseFloat(arg.value.toString());
            } else {
              output += "NaN";
            }
          } else {
            output += toJson(arg);
          }
        } else {
          output += token;
        }
      }
      if (argValues.length > 0) {
        throw new Error(`More value is provided: "${getRemoteValuesText(args2, false)}"`);
      }
      return output;
    }
    function toJson(arg) {
      if (arg.type !== "array" && arg.type !== "bigint" && arg.type !== "date" && arg.type !== "number" && arg.type !== "object" && arg.type !== "string") {
        return stringFromArg(arg);
      }
      if (arg.type === "bigint") {
        return `${arg.value.toString()}n`;
      }
      if (arg.type === "number") {
        return arg.value.toString();
      }
      if (["date", "string"].includes(arg.type)) {
        return JSON.stringify(arg.value);
      }
      if (arg.type === "object") {
        return `{${arg.value.map((pair) => {
          return `${JSON.stringify(pair[0])}:${toJson(pair[1])}`;
        }).join(",")}}`;
      }
      if (arg.type === "array") {
        return `[${arg.value?.map((val) => toJson(val)).join(",") ?? ""}]`;
      }
      throw Error(`Invalid value type: ${arg}`);
    }
    function stringFromArg(arg) {
      if (!Object.hasOwn(arg, "value")) {
        return arg.type;
      }
      switch (arg.type) {
        case "string":
        case "number":
        case "boolean":
        case "bigint":
          return String(arg.value);
        case "regexp":
          return `/${arg.value.pattern}/${arg.value.flags ?? ""}`;
        case "date":
          return new Date(arg.value).toString();
        case "object":
          return `Object(${arg.value?.length ?? ""})`;
        case "array":
          return `Array(${arg.value?.length ?? ""})`;
        case "map":
          return `Map(${arg.value?.length})`;
        case "set":
          return `Set(${arg.value?.length})`;
        default:
          return arg.type;
      }
    }
    function getRemoteValuesText(args2, formatText) {
      const arg = args2[0];
      if (!arg) {
        return "";
      }
      if (arg.type === "string" && isFormatSpecifier(arg.value.toString()) && formatText) {
        return logMessageFormatter(args2);
      }
      return args2.map((arg2) => {
        return stringFromArg(arg2);
      }).join(" ");
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/log/LogManager.js
var require_LogManager = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/log/LogManager.js"(exports2) {
    "use strict";
    init_prefix();
    var _a2;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.LogManager = void 0;
    var protocol_js_1 = require_protocol();
    var log_js_1 = require_log();
    var logHelper_js_1 = require_logHelper();
    function getBidiStackTrace(cdpStackTrace) {
      const stackFrames = cdpStackTrace?.callFrames.map((callFrame) => {
        return {
          columnNumber: callFrame.columnNumber,
          functionName: callFrame.functionName,
          lineNumber: callFrame.lineNumber,
          url: callFrame.url
        };
      });
      return stackFrames ? { callFrames: stackFrames } : void 0;
    }
    function getLogLevel(consoleApiType) {
      if (["error", "assert"].includes(consoleApiType)) {
        return "error";
      }
      if (["debug", "trace"].includes(consoleApiType)) {
        return "debug";
      }
      if (["warn", "warning"].includes(consoleApiType)) {
        return "warn";
      }
      return "info";
    }
    function getLogMethod(consoleApiType) {
      switch (consoleApiType) {
        case "warning":
          return "warn";
        case "startGroup":
          return "group";
        case "startGroupCollapsed":
          return "groupCollapsed";
        case "endGroup":
          return "groupEnd";
      }
      return consoleApiType;
    }
    var LogManager = class {
      #eventManager;
      #realmStorage;
      #cdpTarget;
      #logger;
      constructor(cdpTarget, realmStorage, eventManager, logger) {
        this.#cdpTarget = cdpTarget;
        this.#realmStorage = realmStorage;
        this.#eventManager = eventManager;
        this.#logger = logger;
      }
      static create(cdpTarget, realmStorage, eventManager, logger) {
        const logManager = new _a2(cdpTarget, realmStorage, eventManager, logger);
        logManager.#initializeEntryAddedEventListener();
        return logManager;
      }
      /**
       * Heuristic serialization of CDP remote object. If possible, return the BiDi value
       * without deep serialization.
       */
      async #heuristicSerializeArg(arg, realm) {
        switch (arg.type) {
          // TODO: Implement regexp, array, object, map and set heuristics base on
          //  preview.
          case "undefined":
            return { type: "undefined" };
          case "boolean":
            return { type: "boolean", value: arg.value };
          case "string":
            return { type: "string", value: arg.value };
          case "number":
            return { type: "number", value: arg.unserializableValue ?? arg.value };
          case "bigint":
            if (arg.unserializableValue !== void 0 && arg.unserializableValue[arg.unserializableValue.length - 1] === "n") {
              return {
                type: arg.type,
                value: arg.unserializableValue.slice(0, -1)
              };
            }
            break;
          case "object":
            if (arg.subtype === "null") {
              return { type: "null" };
            }
            break;
          default:
            break;
        }
        return await realm.serializeCdpObject(
          arg,
          "none"
          /* Script.ResultOwnership.None */
        );
      }
      #initializeEntryAddedEventListener() {
        this.#cdpTarget.cdpClient.on("Runtime.consoleAPICalled", (params) => {
          const realm = this.#realmStorage.findRealm({
            cdpSessionId: this.#cdpTarget.cdpSessionId,
            executionContextId: params.executionContextId
          });
          if (realm === void 0) {
            this.#logger?.(log_js_1.LogType.cdp, params);
            return;
          }
          const argsPromise = Promise.all(params.args.map((arg) => this.#heuristicSerializeArg(arg, realm)));
          for (const browsingContext of realm.associatedBrowsingContexts) {
            this.#eventManager.registerPromiseEvent(argsPromise.then((args2) => ({
              kind: "success",
              value: {
                type: "event",
                method: protocol_js_1.ChromiumBidi.Log.EventNames.LogEntryAdded,
                params: {
                  level: getLogLevel(params.type),
                  source: realm.source,
                  text: (0, logHelper_js_1.getRemoteValuesText)(args2, true),
                  timestamp: Math.round(params.timestamp),
                  stackTrace: getBidiStackTrace(params.stackTrace),
                  type: "console",
                  method: getLogMethod(params.type),
                  args: args2
                }
              }
            }), (error) => ({
              kind: "error",
              error
            })), browsingContext.id, protocol_js_1.ChromiumBidi.Log.EventNames.LogEntryAdded);
          }
        });
        this.#cdpTarget.cdpClient.on("Runtime.exceptionThrown", (params) => {
          const realm = this.#realmStorage.findRealm({
            cdpSessionId: this.#cdpTarget.cdpSessionId,
            executionContextId: params.exceptionDetails.executionContextId
          });
          if (realm === void 0) {
            this.#logger?.(log_js_1.LogType.cdp, params);
            return;
          }
          for (const browsingContext of realm.associatedBrowsingContexts) {
            this.#eventManager.registerPromiseEvent(_a2.#getExceptionText(params, realm).then((text) => ({
              kind: "success",
              value: {
                type: "event",
                method: protocol_js_1.ChromiumBidi.Log.EventNames.LogEntryAdded,
                params: {
                  level: "error",
                  source: realm.source,
                  text,
                  timestamp: Math.round(params.timestamp),
                  stackTrace: getBidiStackTrace(params.exceptionDetails.stackTrace),
                  type: "javascript"
                }
              }
            }), (error) => ({
              kind: "error",
              error
            })), browsingContext.id, protocol_js_1.ChromiumBidi.Log.EventNames.LogEntryAdded);
          }
        });
      }
      /**
       * Try the best to get the exception text.
       */
      static async #getExceptionText(params, realm) {
        if (!params.exceptionDetails.exception) {
          return params.exceptionDetails.text;
        }
        if (realm === void 0) {
          return JSON.stringify(params.exceptionDetails.exception);
        }
        return await realm.stringifyObject(params.exceptionDetails.exception);
      }
    };
    exports2.LogManager = LogManager;
    _a2 = LogManager;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/network/CollectorsStorage.js
var require_CollectorsStorage = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/network/CollectorsStorage.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CollectorsStorage = void 0;
    var ErrorResponse_js_1 = require_ErrorResponse();
    var log_js_1 = require_log();
    var uuid_js_1 = require_uuid();
    var CollectorsStorage = class {
      #collectors = /* @__PURE__ */ new Map();
      #responseCollectors = /* @__PURE__ */ new Map();
      #requestBodyCollectors = /* @__PURE__ */ new Map();
      #maxEncodedDataSize;
      #logger;
      constructor(maxEncodedDataSize, logger) {
        this.#maxEncodedDataSize = maxEncodedDataSize;
        this.#logger = logger;
      }
      addDataCollector(params) {
        if (params.maxEncodedDataSize < 1 || params.maxEncodedDataSize > this.#maxEncodedDataSize) {
          throw new ErrorResponse_js_1.InvalidArgumentException(`Max encoded data size should be between 1 and ${this.#maxEncodedDataSize}`);
        }
        const collectorId = (0, uuid_js_1.uuidv4)();
        this.#collectors.set(collectorId, params);
        return collectorId;
      }
      isCollected(requestId, dataType, collectorId) {
        if (collectorId !== void 0 && !this.#collectors.has(collectorId)) {
          throw new ErrorResponse_js_1.NoSuchNetworkCollectorException(`Unknown collector ${collectorId}`);
        }
        if (dataType === void 0) {
          return this.isCollected(requestId, "response", collectorId) || this.isCollected(requestId, "request", collectorId);
        }
        const requestToCollectorsMap = this.#getRequestToCollectorMap(dataType).get(requestId);
        if (requestToCollectorsMap === void 0 || requestToCollectorsMap.size === 0) {
          return false;
        }
        if (collectorId === void 0) {
          return true;
        }
        if (!requestToCollectorsMap.has(collectorId)) {
          return false;
        }
        return true;
      }
      #getRequestToCollectorMap(dataType) {
        switch (dataType) {
          case "response":
            return this.#responseCollectors;
          case "request":
            return this.#requestBodyCollectors;
          default:
            throw new ErrorResponse_js_1.UnsupportedOperationException(`Unsupported data type ${dataType}`);
        }
      }
      disownData(requestId, dataType, collectorId) {
        const requestToCollectorsMap = this.#getRequestToCollectorMap(dataType);
        if (collectorId !== void 0) {
          requestToCollectorsMap.get(requestId)?.delete(collectorId);
        }
        if (collectorId === void 0 || requestToCollectorsMap.get(requestId)?.size === 0) {
          requestToCollectorsMap.delete(requestId);
        }
      }
      #shouldCollectRequest(collectorId, request, dataType, topLevelBrowsingContext, userContext) {
        const collector = this.#collectors.get(collectorId);
        if (collector === void 0) {
          throw new ErrorResponse_js_1.NoSuchNetworkCollectorException(`Unknown collector ${collectorId}`);
        }
        if (collector.userContexts && !collector.userContexts.includes(userContext)) {
          return false;
        }
        if (collector.contexts && !collector.contexts.includes(topLevelBrowsingContext)) {
          return false;
        }
        if (!collector.dataTypes.includes(dataType)) {
          return false;
        }
        if (dataType === "request" && request.bodySize > collector.maxEncodedDataSize) {
          this.#logger?.(log_js_1.LogType.debug, `Request's ${request.id} body size is too big for the collector ${collectorId}`);
          return false;
        }
        if (dataType === "response" && request.encodedResponseBodySize > collector.maxEncodedDataSize) {
          this.#logger?.(log_js_1.LogType.debug, `Request's ${request.id} response is too big for the collector ${collectorId}`);
          return false;
        }
        this.#logger?.(log_js_1.LogType.debug, `Collector ${collectorId} collected ${dataType} of ${request.id}`);
        return true;
      }
      collectIfNeeded(request, dataType, topLevelBrowsingContext, userContext) {
        const collectorIds = [...this.#collectors.keys()].filter((collectorId) => this.#shouldCollectRequest(collectorId, request, dataType, topLevelBrowsingContext, userContext));
        if (collectorIds.length > 0) {
          this.#getRequestToCollectorMap(dataType).set(request.id, new Set(collectorIds));
        }
      }
      removeDataCollector(collectorId) {
        if (!this.#collectors.has(collectorId)) {
          throw new ErrorResponse_js_1.NoSuchNetworkCollectorException(`Collector ${collectorId} does not exist`);
        }
        this.#collectors.delete(collectorId);
        const affectedRequests = [];
        for (const [requestId, collectorIds] of this.#responseCollectors) {
          if (collectorIds.has(collectorId)) {
            collectorIds.delete(collectorId);
            if (collectorIds.size === 0) {
              this.#responseCollectors.delete(requestId);
              affectedRequests.push(requestId);
            }
          }
        }
        for (const [requestId, collectorIds] of this.#requestBodyCollectors) {
          if (collectorIds.has(collectorId)) {
            collectorIds.delete(collectorId);
            if (collectorIds.size === 0) {
              this.#requestBodyCollectors.delete(requestId);
              affectedRequests.push(requestId);
            }
          }
        }
        return affectedRequests;
      }
    };
    exports2.CollectorsStorage = CollectorsStorage;
  }
});

// node_modules/chromium-bidi/lib/cjs/utils/DefaultMap.js
var require_DefaultMap = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/utils/DefaultMap.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DefaultMap = void 0;
    var DefaultMap = class extends Map {
      /** The default value to return whenever a key is not present in the map. */
      #getDefaultValue;
      constructor(getDefaultValue, entries) {
        super(entries);
        this.#getDefaultValue = getDefaultValue;
      }
      get(key) {
        if (!this.has(key)) {
          this.set(key, this.#getDefaultValue(key));
        }
        return super.get(key);
      }
    };
    exports2.DefaultMap = DefaultMap;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/network/NetworkRequest.js
var require_NetworkRequest = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/network/NetworkRequest.js"(exports2) {
    "use strict";
    init_prefix();
    var _a2;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NetworkRequest = void 0;
    var protocol_js_1 = require_protocol();
    var assert_js_1 = require_assert2();
    var DefaultMap_js_1 = require_DefaultMap();
    var Deferred_js_1 = require_Deferred2();
    var log_js_1 = require_log();
    var NetworkUtils_js_1 = require_NetworkUtils();
    var REALM_REGEX = /(?<=realm=").*(?=")/;
    var NetworkRequest = class {
      static unknownParameter = "UNKNOWN";
      /**
       * Each network request has an associated request id, which is a string
       * uniquely identifying that request.
       *
       * The identifier for a request resulting from a redirect matches that of the
       * request that initiated it.
       */
      #id;
      #fetchId;
      /**
       * Indicates the network intercept phase, if the request is currently blocked.
       * Undefined necessarily implies that the request is not blocked.
       */
      #interceptPhase;
      #servedFromCache = false;
      #redirectCount;
      #request = {};
      #requestOverrides;
      #responseOverrides;
      #response = {
        decodedSize: 0,
        encodedSize: 0
      };
      #eventManager;
      #networkStorage;
      #cdpTarget;
      #logger;
      #emittedEvents = {
        [protocol_js_1.ChromiumBidi.Network.EventNames.AuthRequired]: false,
        [protocol_js_1.ChromiumBidi.Network.EventNames.BeforeRequestSent]: false,
        [protocol_js_1.ChromiumBidi.Network.EventNames.FetchError]: false,
        [protocol_js_1.ChromiumBidi.Network.EventNames.ResponseCompleted]: false,
        [protocol_js_1.ChromiumBidi.Network.EventNames.ResponseStarted]: false
      };
      waitNextPhase = new Deferred_js_1.Deferred();
      constructor(id, eventManager, networkStorage, cdpTarget, redirectCount = 0, logger) {
        this.#id = id;
        this.#eventManager = eventManager;
        this.#networkStorage = networkStorage;
        this.#cdpTarget = cdpTarget;
        this.#redirectCount = redirectCount;
        this.#logger = logger;
      }
      get id() {
        return this.#id;
      }
      get fetchId() {
        return this.#fetchId;
      }
      /**
       * When blocked returns the phase for it
       */
      get interceptPhase() {
        return this.#interceptPhase;
      }
      get url() {
        const fragment = this.#request.info?.request.urlFragment ?? this.#request.paused?.request.urlFragment ?? "";
        const url = this.#response.paused?.request.url ?? this.#requestOverrides?.url ?? this.#response.info?.url ?? this.#request.auth?.request.url ?? this.#request.info?.request.url ?? this.#request.paused?.request.url ?? _a2.unknownParameter;
        return `${url}${fragment}`;
      }
      get redirectCount() {
        return this.#redirectCount;
      }
      get cdpTarget() {
        return this.#cdpTarget;
      }
      /** CdpTarget can be changed when frame is moving out of process. */
      updateCdpTarget(cdpTarget) {
        if (cdpTarget !== this.#cdpTarget) {
          this.#logger?.(log_js_1.LogType.debugInfo, `Request ${this.id} was moved from ${this.#cdpTarget.id} to ${cdpTarget.id}`);
          this.#cdpTarget = cdpTarget;
        }
      }
      get cdpClient() {
        return this.#cdpTarget.cdpClient;
      }
      isRedirecting() {
        return Boolean(this.#request.info);
      }
      #isDataUrl() {
        return this.url.startsWith("data:");
      }
      #isNonInterceptable() {
        return (
          // We can't intercept data urls from CDP
          this.#isDataUrl() || // Cached requests never hit the network
          this.#servedFromCache
        );
      }
      get #method() {
        return this.#requestOverrides?.method ?? this.#request.info?.request.method ?? this.#request.paused?.request.method ?? this.#request.auth?.request.method ?? this.#response.paused?.request.method;
      }
      get #navigationId() {
        if (!this.#request.info || !this.#request.info.loaderId || // When we navigate all CDP network events have `loaderId`
        // CDP's `loaderId` and `requestId` match when
        // that request triggered the loading
        this.#request.info.loaderId !== this.#request.info.requestId) {
          return null;
        }
        return this.#networkStorage.getNavigationId(this.#context ?? void 0);
      }
      get #cookies() {
        let cookies = [];
        if (this.#request.extraInfo) {
          cookies = this.#request.extraInfo.associatedCookies.filter(({ blockedReasons }) => {
            return !Array.isArray(blockedReasons) || blockedReasons.length === 0;
          }).map(({ cookie }) => (0, NetworkUtils_js_1.cdpToBiDiCookie)(cookie));
        }
        return cookies;
      }
      #getBodySizeFromHeaders(headers) {
        if (headers === void 0) {
          return void 0;
        }
        if (headers["Content-Length"] !== void 0) {
          const bodySize = Number.parseInt(headers["Content-Length"]);
          if (Number.isInteger(bodySize)) {
            return bodySize;
          }
          this.#logger?.(log_js_1.LogType.debugError, "Unexpected non-integer 'Content-Length' header");
        }
        return void 0;
      }
      get bodySize() {
        if (typeof this.#requestOverrides?.bodySize === "number") {
          return this.#requestOverrides.bodySize;
        }
        if (this.#request.info?.request.postDataEntries !== void 0) {
          return (0, NetworkUtils_js_1.bidiBodySizeFromCdpPostDataEntries)(this.#request.info?.request.postDataEntries);
        }
        return this.#getBodySizeFromHeaders(this.#request.info?.request.headers) ?? this.#getBodySizeFromHeaders(this.#request.extraInfo?.headers) ?? 0;
      }
      get #context() {
        const result = this.#response.paused?.frameId ?? this.#request.info?.frameId ?? this.#request.paused?.frameId ?? this.#request.auth?.frameId;
        if (result !== void 0) {
          return result;
        }
        if (this.#request?.info?.initiator.type === "preflight" && this.#request?.info?.initiator.requestId !== void 0) {
          const maybeInitiator = this.#networkStorage.getRequestById(this.#request?.info?.initiator.requestId);
          if (maybeInitiator !== void 0) {
            return maybeInitiator.#request.info?.frameId ?? null;
          }
        }
        return null;
      }
      /** Returns the HTTP status code associated with this request if any. */
      get #statusCode() {
        return this.#responseOverrides?.statusCode ?? this.#response.paused?.responseStatusCode ?? this.#response.extraInfo?.statusCode ?? this.#response.info?.status;
      }
      get #requestHeaders() {
        let headers = [];
        if (this.#requestOverrides?.headers) {
          const headerMap = new DefaultMap_js_1.DefaultMap(() => []);
          for (const header of this.#requestOverrides.headers) {
            headerMap.get(header.name).push(header.value.value);
          }
          for (const [name, value] of headerMap.entries()) {
            headers.push({
              name,
              value: {
                type: "string",
                value: value.join("\n").trimEnd()
              }
            });
          }
        } else {
          headers = [
            ...(0, NetworkUtils_js_1.bidiNetworkHeadersFromCdpNetworkHeaders)(this.#request.info?.request.headers),
            ...(0, NetworkUtils_js_1.bidiNetworkHeadersFromCdpNetworkHeaders)(this.#request.extraInfo?.headers)
          ];
        }
        return headers;
      }
      get #authChallenges() {
        if (!this.#response.info) {
          return;
        }
        if (!(this.#statusCode === 401 || this.#statusCode === 407)) {
          return void 0;
        }
        const headerName = this.#statusCode === 401 ? "WWW-Authenticate" : "Proxy-Authenticate";
        const authChallenges = [];
        for (const [header, value] of Object.entries(this.#response.info.headers)) {
          if (header.localeCompare(headerName, void 0, { sensitivity: "base" }) === 0) {
            authChallenges.push({
              scheme: value.split(" ").at(0) ?? "",
              realm: value.match(REALM_REGEX)?.at(0) ?? ""
            });
          }
        }
        return authChallenges;
      }
      get #timings() {
        const responseTimeOffset = (0, NetworkUtils_js_1.getTiming)((0, NetworkUtils_js_1.getTiming)(this.#response.info?.timing?.requestTime) - (0, NetworkUtils_js_1.getTiming)(this.#request.info?.timestamp));
        return {
          // TODO: Verify this is correct
          timeOrigin: Math.round((0, NetworkUtils_js_1.getTiming)(this.#request.info?.wallTime) * 1e3),
          // Timing baseline.
          // TODO: Verify this is correct.
          requestTime: 0,
          // TODO: set if redirect detected.
          redirectStart: 0,
          // TODO: set if redirect detected.
          redirectEnd: 0,
          // TODO: Verify this is correct
          // https://source.chromium.org/chromium/chromium/src/+/main:net/base/load_timing_info.h;l=145
          fetchStart: (0, NetworkUtils_js_1.getTiming)(this.#response.info?.timing?.workerFetchStart, responseTimeOffset),
          // fetchStart: 0,
          dnsStart: (0, NetworkUtils_js_1.getTiming)(this.#response.info?.timing?.dnsStart, responseTimeOffset),
          dnsEnd: (0, NetworkUtils_js_1.getTiming)(this.#response.info?.timing?.dnsEnd, responseTimeOffset),
          connectStart: (0, NetworkUtils_js_1.getTiming)(this.#response.info?.timing?.connectStart, responseTimeOffset),
          connectEnd: (0, NetworkUtils_js_1.getTiming)(this.#response.info?.timing?.connectEnd, responseTimeOffset),
          tlsStart: (0, NetworkUtils_js_1.getTiming)(this.#response.info?.timing?.sslStart, responseTimeOffset),
          requestStart: (0, NetworkUtils_js_1.getTiming)(this.#response.info?.timing?.sendStart, responseTimeOffset),
          // https://source.chromium.org/chromium/chromium/src/+/main:net/base/load_timing_info.h;l=196
          responseStart: (0, NetworkUtils_js_1.getTiming)(this.#response.info?.timing?.receiveHeadersStart, responseTimeOffset),
          responseEnd: (0, NetworkUtils_js_1.getTiming)(this.#response.info?.timing?.receiveHeadersEnd, responseTimeOffset)
        };
      }
      #phaseChanged() {
        this.waitNextPhase.resolve();
        this.waitNextPhase = new Deferred_js_1.Deferred();
      }
      #interceptsInPhase(phase) {
        if (this.#isNonInterceptable() || !this.#cdpTarget.isSubscribedTo(`network.${phase}`)) {
          return /* @__PURE__ */ new Set();
        }
        return this.#networkStorage.getInterceptsForPhase(this, phase);
      }
      #isBlockedInPhase(phase) {
        return this.#interceptsInPhase(phase).size > 0;
      }
      handleRedirect(event) {
        this.#response.hasExtraInfo = false;
        this.#response.decodedSize = 0;
        this.#response.encodedSize = 0;
        this.#response.info = event.redirectResponse;
        this.#emitEventsIfReady({
          wasRedirected: true
        });
      }
      #emitEventsIfReady(options = {}) {
        const requestExtraInfoCompleted = (
          // Flush redirects
          options.wasRedirected || Boolean(this.#response.loadingFailed) || this.#isDataUrl() || Boolean(this.#request.extraInfo) || // If the request is intercepted during the `authRequired` phase, there
          // will be no `Network.requestWillBeSentExtraInfo` CDP events.
          this.#isBlockedInPhase(
            "authRequired"
            /* Network.InterceptPhase.AuthRequired */
          ) || // Requests from cache don't have extra info
          this.#servedFromCache || // Sometimes there is no extra info and the response
          // is the only place we can find out
          Boolean(this.#response.info && !this.#response.hasExtraInfo)
        );
        const noInterceptionExpected = this.#isNonInterceptable();
        const requestInterceptionExpected = !noInterceptionExpected && this.#isBlockedInPhase(
          "beforeRequestSent"
          /* Network.InterceptPhase.BeforeRequestSent */
        );
        const requestInterceptionCompleted = !requestInterceptionExpected || requestInterceptionExpected && Boolean(this.#request.paused);
        if (Boolean(this.#request.info) && (requestInterceptionExpected ? requestInterceptionCompleted : requestExtraInfoCompleted)) {
          this.#emitEvent(this.#getBeforeRequestEvent.bind(this));
        }
        const responseExtraInfoCompleted = Boolean(this.#response.extraInfo) || // Response from cache don't have extra info
        this.#servedFromCache || // Don't expect extra info if the flag is false
        Boolean(this.#response.info && !this.#response.hasExtraInfo);
        const responseInterceptionExpected = !noInterceptionExpected && this.#isBlockedInPhase(
          "responseStarted"
          /* Network.InterceptPhase.ResponseStarted */
        );
        if (this.#response.info || responseInterceptionExpected && Boolean(this.#response.paused)) {
          this.#emitEvent(this.#getResponseStartedEvent.bind(this));
        }
        const responseInterceptionCompleted = !responseInterceptionExpected || responseInterceptionExpected && Boolean(this.#response.paused);
        const loadingFinished = Boolean(this.#response.loadingFailed) || Boolean(this.#response.loadingFinished);
        if (Boolean(this.#response.info) && responseExtraInfoCompleted && responseInterceptionCompleted && (loadingFinished || options.wasRedirected)) {
          this.#emitEvent(this.#getResponseReceivedEvent.bind(this));
          this.#networkStorage.disposeRequest(this.id);
        }
      }
      onRequestWillBeSentEvent(event) {
        this.#request.info = event;
        this.#networkStorage.collectIfNeeded(
          this,
          "request"
          /* Network.DataType.Request */
        );
        this.#emitEventsIfReady();
      }
      onRequestWillBeSentExtraInfoEvent(event) {
        this.#request.extraInfo = event;
        this.#emitEventsIfReady();
      }
      onResponseReceivedExtraInfoEvent(event) {
        if (event.statusCode >= 300 && event.statusCode <= 399 && this.#request.info && event.headers["location"] === this.#request.info.request.url) {
          return;
        }
        this.#response.extraInfo = event;
        this.#emitEventsIfReady();
      }
      onResponseReceivedEvent(event) {
        this.#response.hasExtraInfo = event.hasExtraInfo;
        this.#response.info = event.response;
        this.#networkStorage.collectIfNeeded(
          this,
          "response"
          /* Network.DataType.Response */
        );
        this.#emitEventsIfReady();
      }
      onServedFromCache() {
        this.#servedFromCache = true;
        this.#emitEventsIfReady();
      }
      onLoadingFinishedEvent(event) {
        this.#response.loadingFinished = event;
        this.#emitEventsIfReady();
      }
      onDataReceivedEvent(event) {
        this.#response.decodedSize += event.dataLength;
        this.#response.encodedSize += event.encodedDataLength;
      }
      onLoadingFailedEvent(event) {
        this.#response.loadingFailed = event;
        this.#emitEventsIfReady();
        this.#emitEvent(() => {
          return {
            method: protocol_js_1.ChromiumBidi.Network.EventNames.FetchError,
            params: {
              ...this.#getBaseEventParams(),
              errorText: event.errorText
            }
          };
        });
      }
      /** @see https://chromedevtools.github.io/devtools-protocol/tot/Fetch/#method-failRequest */
      async failRequest(errorReason) {
        (0, assert_js_1.assert)(this.#fetchId, "Network Interception not set-up.");
        await this.cdpClient.sendCommand("Fetch.failRequest", {
          requestId: this.#fetchId,
          errorReason
        });
        this.#interceptPhase = void 0;
      }
      onRequestPaused(event) {
        this.#fetchId = event.requestId;
        if (event.responseStatusCode || event.responseErrorReason) {
          this.#response.paused = event;
          if (this.#isBlockedInPhase(
            "responseStarted"
            /* Network.InterceptPhase.ResponseStarted */
          ) && // CDP may emit multiple events for a single request
          !this.#emittedEvents[protocol_js_1.ChromiumBidi.Network.EventNames.ResponseStarted] && // Continue all response that have not enabled Network domain
          this.#fetchId !== this.id) {
            this.#interceptPhase = "responseStarted";
          } else {
            void this.#continueResponse();
          }
        } else {
          this.#request.paused = event;
          if (this.#isBlockedInPhase(
            "beforeRequestSent"
            /* Network.InterceptPhase.BeforeRequestSent */
          ) && // CDP may emit multiple events for a single request
          !this.#emittedEvents[protocol_js_1.ChromiumBidi.Network.EventNames.BeforeRequestSent] && // Continue all requests that have not enabled Network domain
          this.#fetchId !== this.id) {
            this.#interceptPhase = "beforeRequestSent";
          } else {
            void this.#continueRequest();
          }
        }
        this.#emitEventsIfReady();
      }
      onAuthRequired(event) {
        this.#fetchId = event.requestId;
        this.#request.auth = event;
        if (this.#isBlockedInPhase(
          "authRequired"
          /* Network.InterceptPhase.AuthRequired */
        ) && // Continue all auth requests that have not enabled Network domain
        this.#fetchId !== this.id) {
          this.#interceptPhase = "authRequired";
          this.#emitEventsIfReady();
        } else {
          void this.#continueWithAuth({
            response: "Default"
          });
        }
        this.#emitEvent(() => {
          return {
            method: protocol_js_1.ChromiumBidi.Network.EventNames.AuthRequired,
            params: {
              ...this.#getBaseEventParams(
                "authRequired"
                /* Network.InterceptPhase.AuthRequired */
              ),
              response: this.#getResponseEventParams()
            }
          };
        });
      }
      /** @see https://chromedevtools.github.io/devtools-protocol/tot/Fetch/#method-continueRequest */
      async continueRequest(overrides = {}) {
        const overrideHeaders = this.#getOverrideHeader(overrides.headers, overrides.cookies);
        const headers = (0, NetworkUtils_js_1.cdpFetchHeadersFromBidiNetworkHeaders)(overrideHeaders);
        const postData = getCdpBodyFromBiDiBytesValue(overrides.body);
        await this.#continueRequest({
          url: overrides.url,
          method: overrides.method,
          headers,
          postData
        });
        this.#requestOverrides = {
          url: overrides.url,
          method: overrides.method,
          headers: overrides.headers,
          cookies: overrides.cookies,
          bodySize: getSizeFromBiDiBytesValue(overrides.body)
        };
      }
      async #continueRequest(overrides = {}) {
        (0, assert_js_1.assert)(this.#fetchId, "Network Interception not set-up.");
        await this.cdpClient.sendCommand("Fetch.continueRequest", {
          requestId: this.#fetchId,
          url: overrides.url,
          method: overrides.method,
          headers: overrides.headers,
          postData: overrides.postData
        });
        this.#interceptPhase = void 0;
      }
      /** @see https://chromedevtools.github.io/devtools-protocol/tot/Fetch/#method-continueResponse */
      async continueResponse(overrides = {}) {
        if (this.interceptPhase === "authRequired") {
          if (overrides.credentials) {
            await Promise.all([
              this.waitNextPhase,
              await this.#continueWithAuth({
                response: "ProvideCredentials",
                username: overrides.credentials.username,
                password: overrides.credentials.password
              })
            ]);
          } else {
            return await this.#continueWithAuth({
              response: "ProvideCredentials"
            });
          }
        }
        if (this.#interceptPhase === "responseStarted") {
          const overrideHeaders = this.#getOverrideHeader(overrides.headers, overrides.cookies);
          const responseHeaders = (0, NetworkUtils_js_1.cdpFetchHeadersFromBidiNetworkHeaders)(overrideHeaders);
          await this.#continueResponse({
            responseCode: overrides.statusCode ?? this.#response.paused?.responseStatusCode,
            responsePhrase: overrides.reasonPhrase ?? this.#response.paused?.responseStatusText,
            responseHeaders: responseHeaders ?? this.#response.paused?.responseHeaders
          });
          this.#responseOverrides = {
            statusCode: overrides.statusCode,
            headers: overrideHeaders
          };
        }
      }
      async #continueResponse({ responseCode, responsePhrase, responseHeaders } = {}) {
        (0, assert_js_1.assert)(this.#fetchId, "Network Interception not set-up.");
        await this.cdpClient.sendCommand("Fetch.continueResponse", {
          requestId: this.#fetchId,
          responseCode,
          responsePhrase,
          responseHeaders
        });
        this.#interceptPhase = void 0;
      }
      /** @see https://chromedevtools.github.io/devtools-protocol/tot/Fetch/#method-continueWithAuth */
      async continueWithAuth(authChallenge) {
        let username;
        let password;
        if (authChallenge.action === "provideCredentials") {
          const { credentials } = authChallenge;
          username = credentials.username;
          password = credentials.password;
        }
        const response = (0, NetworkUtils_js_1.cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction)(authChallenge.action);
        await this.#continueWithAuth({
          response,
          username,
          password
        });
      }
      /** @see https://chromedevtools.github.io/devtools-protocol/tot/Fetch/#method-provideResponse */
      async provideResponse(overrides) {
        (0, assert_js_1.assert)(this.#fetchId, "Network Interception not set-up.");
        if (this.interceptPhase === "authRequired") {
          return await this.#continueWithAuth({
            response: "ProvideCredentials"
          });
        }
        if (!overrides.body && !overrides.headers) {
          return await this.#continueRequest();
        }
        const overrideHeaders = this.#getOverrideHeader(overrides.headers, overrides.cookies);
        const responseHeaders = (0, NetworkUtils_js_1.cdpFetchHeadersFromBidiNetworkHeaders)(overrideHeaders);
        const responseCode = overrides.statusCode ?? this.#statusCode ?? 200;
        await this.cdpClient.sendCommand("Fetch.fulfillRequest", {
          requestId: this.#fetchId,
          responseCode,
          responsePhrase: overrides.reasonPhrase,
          responseHeaders,
          body: getCdpBodyFromBiDiBytesValue(overrides.body)
        });
        this.#interceptPhase = void 0;
      }
      dispose() {
        this.waitNextPhase.reject(new Error("waitNextPhase disposed"));
      }
      async #continueWithAuth(authChallengeResponse) {
        (0, assert_js_1.assert)(this.#fetchId, "Network Interception not set-up.");
        await this.cdpClient.sendCommand("Fetch.continueWithAuth", {
          requestId: this.#fetchId,
          authChallengeResponse
        });
        this.#interceptPhase = void 0;
      }
      #emitEvent(getEvent) {
        let event;
        try {
          event = getEvent();
        } catch (error) {
          this.#logger?.(log_js_1.LogType.debugError, error);
          return;
        }
        if (this.#isIgnoredEvent() || this.#emittedEvents[event.method] && // Special case this event can be emitted multiple times
        event.method !== protocol_js_1.ChromiumBidi.Network.EventNames.AuthRequired) {
          return;
        }
        this.#phaseChanged();
        this.#emittedEvents[event.method] = true;
        if (this.#context) {
          this.#eventManager.registerEvent(Object.assign(event, {
            type: "event"
          }), this.#context);
        } else {
          this.#eventManager.registerGlobalEvent(Object.assign(event, {
            type: "event"
          }));
        }
      }
      #getBaseEventParams(phase) {
        const interceptProps = {
          isBlocked: false
        };
        if (phase) {
          const blockedBy = this.#interceptsInPhase(phase);
          interceptProps.isBlocked = blockedBy.size > 0;
          if (interceptProps.isBlocked) {
            interceptProps.intercepts = [...blockedBy];
          }
        }
        return {
          context: this.#context,
          navigation: this.#navigationId,
          redirectCount: this.#redirectCount,
          request: this.#getRequestData(),
          // Timestamp should be in milliseconds, while CDP provides it in seconds.
          timestamp: Math.round((0, NetworkUtils_js_1.getTiming)(this.#request.info?.wallTime) * 1e3),
          // Contains isBlocked and intercepts
          ...interceptProps
        };
      }
      #getResponseEventParams() {
        if (this.#response.info?.fromDiskCache) {
          this.#response.extraInfo = void 0;
        }
        const cdpHeaders = this.#response.info?.headers ?? {};
        const cdpRawHeaders = this.#response.extraInfo?.headers ?? {};
        for (const [key, value] of Object.entries(cdpRawHeaders)) {
          cdpHeaders[key] = value;
        }
        const headers = (0, NetworkUtils_js_1.bidiNetworkHeadersFromCdpNetworkHeaders)(cdpHeaders);
        const authChallenges = this.#authChallenges;
        const response = {
          url: this.url,
          protocol: this.#response.info?.protocol ?? "",
          status: this.#statusCode ?? -1,
          // TODO: Throw an exception or use some other status code?
          statusText: this.#response.info?.statusText || this.#response.paused?.responseStatusText || "",
          fromCache: this.#response.info?.fromDiskCache || this.#response.info?.fromPrefetchCache || this.#servedFromCache,
          headers: this.#responseOverrides?.headers ?? headers,
          mimeType: this.#response.info?.mimeType || "",
          // TODO: this should be the size for the entire HTTP response.
          bytesReceived: this.encodedResponseBodySize,
          headersSize: (0, NetworkUtils_js_1.computeHeadersSize)(headers),
          bodySize: this.encodedResponseBodySize,
          content: {
            size: this.#response.decodedSize ?? 0
          },
          ...authChallenges ? { authChallenges } : {}
        };
        return {
          ...response,
          "goog:securityDetails": this.#response.info?.securityDetails
        };
      }
      get encodedResponseBodySize() {
        return this.#response.loadingFinished?.encodedDataLength ?? this.#response.info?.encodedDataLength ?? this.#response.encodedSize ?? 0;
      }
      #getRequestData() {
        const headers = this.#requestHeaders;
        const request = {
          request: this.#id,
          url: this.url,
          method: this.#method ?? _a2.unknownParameter,
          headers,
          cookies: this.#cookies,
          headersSize: (0, NetworkUtils_js_1.computeHeadersSize)(headers),
          bodySize: this.bodySize,
          // TODO: populate
          destination: this.#getDestination(),
          // TODO: populate
          initiatorType: this.#getInitiatorType(),
          timings: this.#timings
        };
        return {
          ...request,
          "goog:postData": this.#request.info?.request?.postData,
          "goog:hasPostData": this.#request.info?.request?.hasPostData,
          "goog:resourceType": this.#request.info?.type,
          "goog:resourceInitiator": this.#request.info?.initiator
        };
      }
      /**
       * Heuristic trying to guess the destination.
       * Specification: https://fetch.spec.whatwg.org/#concept-request-destination.
       * Specified values: "audio", "audioworklet", "document", "embed", "font", "frame",
       * "iframe", "image", "json", "manifest", "object", "paintworklet", "report", "script",
       * "serviceworker", "sharedworker", "style", "track", "video", "webidentity", "worker",
       * "xslt".
       */
      #getDestination() {
        switch (this.#request.info?.type) {
          case "Script":
            return "script";
          case "Stylesheet":
            return "style";
          case "Image":
            return "image";
          case "Document":
            return this.#request.info?.initiator.type === "parser" ? "iframe" : "document";
          default:
            return "";
        }
      }
      /**
       * Heuristic trying to guess the initiator type.
       * Specification: https://fetch.spec.whatwg.org/#request-initiator-type.
       * Specified values: "audio", "beacon", "body", "css", "early-hints", "embed", "fetch",
       * "font", "frame", "iframe", "image", "img", "input", "link", "object", "ping",
       * "script", "track", "video", "xmlhttprequest", "other".
       */
      #getInitiatorType() {
        if (this.#request.info?.initiator.type === "parser") {
          switch (this.#request.info?.type) {
            case "Document":
              return "iframe";
            case "Font":
              return this.#request.info?.initiator?.url === this.#request.info?.documentURL ? "font" : "css";
            case "Image":
              return this.#request.info?.initiator?.url === this.#request.info?.documentURL ? "img" : "css";
            case "Script":
              return "script";
            case "Stylesheet":
              return "link";
            default:
              return null;
          }
        }
        if (this.#request?.info?.type === "Fetch") {
          return "fetch";
        }
        return null;
      }
      #getBeforeRequestEvent() {
        (0, assert_js_1.assert)(this.#request.info, "RequestWillBeSentEvent is not set");
        return {
          method: protocol_js_1.ChromiumBidi.Network.EventNames.BeforeRequestSent,
          params: {
            ...this.#getBaseEventParams(
              "beforeRequestSent"
              /* Network.InterceptPhase.BeforeRequestSent */
            ),
            initiator: {
              type: _a2.#getInitiator(this.#request.info.initiator.type),
              columnNumber: this.#request.info.initiator.columnNumber,
              lineNumber: this.#request.info.initiator.lineNumber,
              stackTrace: this.#request.info.initiator.stack,
              request: this.#request.info.initiator.requestId
            }
          }
        };
      }
      #getResponseStartedEvent() {
        return {
          method: protocol_js_1.ChromiumBidi.Network.EventNames.ResponseStarted,
          params: {
            ...this.#getBaseEventParams(
              "responseStarted"
              /* Network.InterceptPhase.ResponseStarted */
            ),
            response: this.#getResponseEventParams()
          }
        };
      }
      #getResponseReceivedEvent() {
        return {
          method: protocol_js_1.ChromiumBidi.Network.EventNames.ResponseCompleted,
          params: {
            ...this.#getBaseEventParams(),
            response: this.#getResponseEventParams()
          }
        };
      }
      #isIgnoredEvent() {
        const faviconUrl = "/favicon.ico";
        return this.#request.paused?.request.url.endsWith(faviconUrl) ?? this.#request.info?.request.url.endsWith(faviconUrl) ?? false;
      }
      #getOverrideHeader(headers, cookies) {
        if (!headers && !cookies) {
          return void 0;
        }
        let overrideHeaders = headers;
        const cookieHeader = (0, NetworkUtils_js_1.networkHeaderFromCookieHeaders)(cookies);
        if (cookieHeader && !overrideHeaders) {
          overrideHeaders = this.#requestHeaders;
        }
        if (cookieHeader && overrideHeaders) {
          overrideHeaders.filter((header) => header.name.localeCompare("cookie", void 0, {
            sensitivity: "base"
          }) !== 0);
          overrideHeaders.push(cookieHeader);
        }
        return overrideHeaders;
      }
      static #getInitiator(initiatorType) {
        switch (initiatorType) {
          case "parser":
          case "script":
          case "preflight":
            return initiatorType;
          default:
            return "other";
        }
      }
    };
    exports2.NetworkRequest = NetworkRequest;
    _a2 = NetworkRequest;
    function getCdpBodyFromBiDiBytesValue(body) {
      let parsedBody;
      if (body?.type === "string") {
        parsedBody = (0, NetworkUtils_js_1.stringToBase64)(body.value);
      } else if (body?.type === "base64") {
        parsedBody = body.value;
      }
      return parsedBody;
    }
    function getSizeFromBiDiBytesValue(body) {
      if (body?.type === "string") {
        return body.value.length;
      } else if (body?.type === "base64") {
        return atob(body.value).length;
      }
      return 0;
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/network/NetworkStorage.js
var require_NetworkStorage = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/network/NetworkStorage.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NetworkStorage = exports2.MAX_TOTAL_COLLECTED_SIZE = void 0;
    var protocol_js_1 = require_protocol();
    var uuid_js_1 = require_uuid();
    var CollectorsStorage_js_1 = require_CollectorsStorage();
    var NetworkRequest_js_1 = require_NetworkRequest();
    var NetworkUtils_js_1 = require_NetworkUtils();
    exports2.MAX_TOTAL_COLLECTED_SIZE = 2e8;
    var NetworkStorage = class {
      #browsingContextStorage;
      #eventManager;
      #collectorsStorage;
      #logger;
      /**
       * A map from network request ID to Network Request objects.
       * Needed as long as information about requests comes from different events.
       */
      #requests = /* @__PURE__ */ new Map();
      /** A map from intercept ID to track active network intercepts. */
      #intercepts = /* @__PURE__ */ new Map();
      #defaultCacheBehavior = "default";
      constructor(eventManager, browsingContextStorage, browserClient, logger) {
        this.#browsingContextStorage = browsingContextStorage;
        this.#eventManager = eventManager;
        this.#collectorsStorage = new CollectorsStorage_js_1.CollectorsStorage(exports2.MAX_TOTAL_COLLECTED_SIZE, logger);
        browserClient.on("Target.detachedFromTarget", ({ sessionId }) => {
          this.disposeRequestMap(sessionId);
        });
        this.#logger = logger;
      }
      /**
       * Gets the network request with the given ID, if any.
       * Otherwise, creates a new network request with the given ID and cdp target.
       */
      #getOrCreateNetworkRequest(id, cdpTarget, redirectCount) {
        let request = this.getRequestById(id);
        if (redirectCount === void 0 && request) {
          return request;
        }
        request = new NetworkRequest_js_1.NetworkRequest(id, this.#eventManager, this, cdpTarget, redirectCount, this.#logger);
        this.addRequest(request);
        return request;
      }
      onCdpTargetCreated(cdpTarget) {
        const cdpClient = cdpTarget.cdpClient;
        const listeners = [
          [
            "Network.requestWillBeSent",
            (params) => {
              const request = this.getRequestById(params.requestId);
              request?.updateCdpTarget(cdpTarget);
              if (request && request.isRedirecting()) {
                request.handleRedirect(params);
                this.disposeRequest(params.requestId);
                this.#getOrCreateNetworkRequest(params.requestId, cdpTarget, request.redirectCount + 1).onRequestWillBeSentEvent(params);
              } else {
                this.#getOrCreateNetworkRequest(params.requestId, cdpTarget).onRequestWillBeSentEvent(params);
              }
            }
          ],
          [
            "Network.requestWillBeSentExtraInfo",
            (params) => {
              const request = this.#getOrCreateNetworkRequest(params.requestId, cdpTarget);
              request.updateCdpTarget(cdpTarget);
              request.onRequestWillBeSentExtraInfoEvent(params);
            }
          ],
          [
            "Network.responseReceived",
            (params) => {
              const request = this.#getOrCreateNetworkRequest(params.requestId, cdpTarget);
              request.updateCdpTarget(cdpTarget);
              request.onResponseReceivedEvent(params);
            }
          ],
          [
            "Network.responseReceivedExtraInfo",
            (params) => {
              const request = this.#getOrCreateNetworkRequest(params.requestId, cdpTarget);
              request.updateCdpTarget(cdpTarget);
              request.onResponseReceivedExtraInfoEvent(params);
            }
          ],
          [
            "Network.requestServedFromCache",
            (params) => {
              const request = this.#getOrCreateNetworkRequest(params.requestId, cdpTarget);
              request.updateCdpTarget(cdpTarget);
              request.onServedFromCache();
            }
          ],
          [
            "Fetch.requestPaused",
            (event) => {
              const request = this.#getOrCreateNetworkRequest(
                // CDP quirk if the Network domain is not present this is undefined
                event.networkId ?? event.requestId,
                cdpTarget
              );
              request.updateCdpTarget(cdpTarget);
              request.onRequestPaused(event);
            }
          ],
          [
            "Fetch.authRequired",
            (event) => {
              let request = this.getRequestByFetchId(event.requestId);
              if (!request) {
                request = this.#getOrCreateNetworkRequest(event.requestId, cdpTarget);
              }
              request.updateCdpTarget(cdpTarget);
              request.onAuthRequired(event);
            }
          ],
          [
            "Network.dataReceived",
            (params) => {
              const request = this.getRequestById(params.requestId);
              request?.updateCdpTarget(cdpTarget);
              request?.onDataReceivedEvent(params);
            }
          ],
          [
            "Network.loadingFailed",
            (params) => {
              const request = this.#getOrCreateNetworkRequest(params.requestId, cdpTarget);
              request.updateCdpTarget(cdpTarget);
              request.onLoadingFailedEvent(params);
            }
          ],
          [
            "Network.loadingFinished",
            (params) => {
              const request = this.getRequestById(params.requestId);
              request?.updateCdpTarget(cdpTarget);
              request?.onLoadingFinishedEvent(params);
            }
          ]
        ];
        for (const [event, listener] of listeners) {
          cdpClient.on(event, listener);
        }
      }
      async getCollectedData(params) {
        if (!this.#collectorsStorage.isCollected(params.request, params.dataType, params.collector)) {
          throw new protocol_js_1.NoSuchNetworkDataException(params.collector === void 0 ? `No collected ${params.dataType} data` : `Collector ${params.collector} didn't collect ${params.dataType} data`);
        }
        if (params.disown && params.collector === void 0) {
          throw new protocol_js_1.InvalidArgumentException("Cannot disown collected data without collector ID");
        }
        const request = this.getRequestById(params.request);
        if (request === void 0) {
          throw new protocol_js_1.NoSuchNetworkDataException(`No data for ${params.request}`);
        }
        let result = void 0;
        switch (params.dataType) {
          case "response":
            result = await this.#getCollectedResponseData(request);
            break;
          case "request":
            result = await this.#getCollectedRequestData(request);
            break;
          default:
            throw new protocol_js_1.UnsupportedOperationException(`Unsupported data type ${params.dataType}`);
        }
        if (params.disown && params.collector !== void 0) {
          this.#collectorsStorage.disownData(request.id, params.dataType, params.collector);
          this.disposeRequest(request.id);
        }
        return result;
      }
      async #getCollectedResponseData(request) {
        try {
          const responseBody = await request.cdpClient.sendCommand("Network.getResponseBody", { requestId: request.id });
          return {
            bytes: {
              type: responseBody.base64Encoded ? "base64" : "string",
              value: responseBody.body
            }
          };
        } catch (error) {
          if (error.code === -32e3 && error.message === "No resource with given identifier found") {
            throw new protocol_js_1.NoSuchNetworkDataException(`Response data was disposed`);
          }
          if (error.code === -32001) {
            throw new protocol_js_1.NoSuchNetworkDataException(`Response data is disposed after the related page`);
          }
          throw error;
        }
      }
      async #getCollectedRequestData(request) {
        const requestPostData = await request.cdpClient.sendCommand("Network.getRequestPostData", { requestId: request.id });
        return {
          bytes: {
            type: "string",
            value: requestPostData.postData
          }
        };
      }
      collectIfNeeded(request, dataType) {
        this.#collectorsStorage.collectIfNeeded(request, dataType, request.cdpTarget.topLevelId, request.cdpTarget.userContext);
      }
      getInterceptionStages(browsingContextId) {
        const stages = {
          request: false,
          response: false,
          auth: false
        };
        for (const intercept of this.#intercepts.values()) {
          if (intercept.contexts && !intercept.contexts.includes(browsingContextId)) {
            continue;
          }
          stages.request ||= intercept.phases.includes(
            "beforeRequestSent"
            /* Network.InterceptPhase.BeforeRequestSent */
          );
          stages.response ||= intercept.phases.includes(
            "responseStarted"
            /* Network.InterceptPhase.ResponseStarted */
          );
          stages.auth ||= intercept.phases.includes(
            "authRequired"
            /* Network.InterceptPhase.AuthRequired */
          );
        }
        return stages;
      }
      getInterceptsForPhase(request, phase) {
        if (request.url === NetworkRequest_js_1.NetworkRequest.unknownParameter) {
          return /* @__PURE__ */ new Set();
        }
        const intercepts = /* @__PURE__ */ new Set();
        for (const [interceptId, intercept] of this.#intercepts.entries()) {
          if (!intercept.phases.includes(phase) || intercept.contexts && !intercept.contexts.includes(request.cdpTarget.topLevelId)) {
            continue;
          }
          if (intercept.urlPatterns.length === 0) {
            intercepts.add(interceptId);
            continue;
          }
          for (const pattern of intercept.urlPatterns) {
            if ((0, NetworkUtils_js_1.matchUrlPattern)(pattern, request.url)) {
              intercepts.add(interceptId);
              break;
            }
          }
        }
        return intercepts;
      }
      disposeRequestMap(sessionId) {
        for (const request of this.#requests.values()) {
          if (request.cdpClient.sessionId === sessionId) {
            this.#requests.delete(request.id);
            request.dispose();
          }
        }
      }
      /**
       * Adds the given entry to the intercept map.
       * URL patterns are assumed to be parsed.
       *
       * @return The intercept ID.
       */
      addIntercept(value) {
        const interceptId = (0, uuid_js_1.uuidv4)();
        this.#intercepts.set(interceptId, value);
        return interceptId;
      }
      /**
       * Removes the given intercept from the intercept map.
       * Throws NoSuchInterceptException if the intercept does not exist.
       */
      removeIntercept(intercept) {
        if (!this.#intercepts.has(intercept)) {
          throw new protocol_js_1.NoSuchInterceptException(`Intercept '${intercept}' does not exist.`);
        }
        this.#intercepts.delete(intercept);
      }
      getRequestsByTarget(target) {
        const requests = [];
        for (const request of this.#requests.values()) {
          if (request.cdpTarget === target) {
            requests.push(request);
          }
        }
        return requests;
      }
      getRequestById(id) {
        return this.#requests.get(id);
      }
      getRequestByFetchId(fetchId) {
        for (const request of this.#requests.values()) {
          if (request.fetchId === fetchId) {
            return request;
          }
        }
        return;
      }
      addRequest(request) {
        this.#requests.set(request.id, request);
      }
      /**
       * Disposes the given request, if no collectors targeting it are left.
       */
      disposeRequest(id) {
        if (this.#collectorsStorage.isCollected(id)) {
          return;
        }
        this.#requests.delete(id);
      }
      /**
       * Gets the virtual navigation ID for the given navigable ID.
       */
      getNavigationId(contextId) {
        if (contextId === void 0) {
          return null;
        }
        return this.#browsingContextStorage.findContext(contextId)?.navigationId ?? null;
      }
      set defaultCacheBehavior(behavior) {
        this.#defaultCacheBehavior = behavior;
      }
      get defaultCacheBehavior() {
        return this.#defaultCacheBehavior;
      }
      addDataCollector(params) {
        return this.#collectorsStorage.addDataCollector(params);
      }
      removeDataCollector(params) {
        const releasedRequests = this.#collectorsStorage.removeDataCollector(params.collector);
        releasedRequests.map((request) => this.disposeRequest(request));
      }
      disownData(params) {
        if (!this.#collectorsStorage.isCollected(params.request, params.dataType, params.collector)) {
          throw new protocol_js_1.NoSuchNetworkDataException(`Collector ${params.collector} didn't collect ${params.dataType} data`);
        }
        this.#collectorsStorage.disownData(params.request, params.dataType, params.collector);
        this.disposeRequest(params.request);
      }
    };
    exports2.NetworkStorage = NetworkStorage;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/cdp/CdpTarget.js
var require_CdpTarget = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/cdp/CdpTarget.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CdpTarget = void 0;
    var chromium_bidi_js_1 = require_chromium_bidi();
    var protocol_js_1 = require_protocol();
    var Deferred_js_1 = require_Deferred2();
    var log_js_1 = require_log();
    var BrowsingContextImpl_js_1 = require_BrowsingContextImpl();
    var LogManager_js_1 = require_LogManager();
    var NetworkStorage_js_1 = require_NetworkStorage();
    var CdpTarget = class _CdpTarget {
      #id;
      userContext;
      #cdpClient;
      #browserCdpClient;
      #parentCdpClient;
      #realmStorage;
      #eventManager;
      #preloadScriptStorage;
      #browsingContextStorage;
      #networkStorage;
      contextConfigStorage;
      #unblocked = new Deferred_js_1.Deferred();
      // Default user agent for the target. Required, as emulating client hints without user
      // agent is not possible. Cache it to avoid round trips to the browser for every target override.
      #defaultUserAgent;
      #logger;
      /**
       * Target's window id. Is filled when the CDP target is created and do not reflect
       * moving targets from one window to another. The actual values
       * will be set during `#unblock`.
       * */
      #windowId;
      #deviceAccessEnabled = false;
      #cacheDisableState = false;
      #preloadEnabled = false;
      #fetchDomainStages = {
        request: false,
        response: false,
        auth: false
      };
      static create(targetId, cdpClient, browserCdpClient, parentCdpClient, realmStorage, eventManager, preloadScriptStorage, browsingContextStorage, networkStorage, configStorage, userContext, defaultUserAgent, logger) {
        const cdpTarget = new _CdpTarget(targetId, cdpClient, browserCdpClient, parentCdpClient, eventManager, realmStorage, preloadScriptStorage, browsingContextStorage, configStorage, networkStorage, userContext, defaultUserAgent, logger);
        LogManager_js_1.LogManager.create(cdpTarget, realmStorage, eventManager, logger);
        cdpTarget.#setEventListeners();
        void cdpTarget.#unblock();
        return cdpTarget;
      }
      constructor(targetId, cdpClient, browserCdpClient, parentCdpClient, eventManager, realmStorage, preloadScriptStorage, browsingContextStorage, configStorage, networkStorage, userContext, defaultUserAgent, logger) {
        this.#defaultUserAgent = defaultUserAgent;
        this.userContext = userContext;
        this.#id = targetId;
        this.#cdpClient = cdpClient;
        this.#browserCdpClient = browserCdpClient;
        this.#parentCdpClient = parentCdpClient;
        this.#eventManager = eventManager;
        this.#realmStorage = realmStorage;
        this.#preloadScriptStorage = preloadScriptStorage;
        this.#networkStorage = networkStorage;
        this.#browsingContextStorage = browsingContextStorage;
        this.contextConfigStorage = configStorage;
        this.#logger = logger;
      }
      /** Returns a deferred that resolves when the target is unblocked. */
      get unblocked() {
        return this.#unblocked;
      }
      get id() {
        return this.#id;
      }
      get cdpClient() {
        return this.#cdpClient;
      }
      get parentCdpClient() {
        return this.#parentCdpClient;
      }
      get browserCdpClient() {
        return this.#browserCdpClient;
      }
      /** Needed for CDP escape path. */
      get cdpSessionId() {
        return this.#cdpClient.sessionId;
      }
      /**
       * Window id the target belongs to. If not known, returns 0.
       */
      get windowId() {
        if (this.#windowId === void 0) {
          this.#logger?.(log_js_1.LogType.debugError, "Getting windowId before it was set, returning 0");
        }
        return this.#windowId ?? 0;
      }
      /**
       * Enables all the required CDP domains and unblocks the target.
       */
      async #unblock() {
        const config2 = this.contextConfigStorage.getActiveConfig(this.topLevelId, this.userContext);
        const results = await Promise.allSettled([
          this.#cdpClient.sendCommand("Page.enable", {
            enableFileChooserOpenedEvent: true
          }),
          ...this.#ignoreFileDialog() ? [] : [
            this.#cdpClient.sendCommand("Page.setInterceptFileChooserDialog", {
              enabled: true,
              // The intercepted dialog should be canceled.
              cancel: true
            })
          ],
          // There can be some existing frames in the target, if reconnecting to an
          // existing browser instance, e.g. via Puppeteer. Need to restore the browsing
          // contexts for the frames to correctly handle further events, like
          // `Runtime.executionContextCreated`.
          // It's important to schedule this task together with enabling domains commands to
          // prepare the tree before the events (e.g. Runtime.executionContextCreated) start
          // coming.
          // https://github.com/GoogleChromeLabs/chromium-bidi/issues/2282
          this.#cdpClient.sendCommand("Page.getFrameTree").then((frameTree) => this.#restoreFrameTreeState(frameTree.frameTree)),
          this.#cdpClient.sendCommand("Runtime.enable"),
          this.#cdpClient.sendCommand("Page.setLifecycleEventsEnabled", {
            enabled: true
          }),
          // Enabling CDP Network domain is required for navigation detection:
          // https://github.com/GoogleChromeLabs/chromium-bidi/issues/2856.
          this.#cdpClient.sendCommand("Network.enable", {
            // If `googDisableNetworkDurableMessages` flag is set, do not enable durable
            // messages.
            enableDurableMessages: config2.disableNetworkDurableMessages !== true,
            maxTotalBufferSize: NetworkStorage_js_1.MAX_TOTAL_COLLECTED_SIZE
          }).then(() => this.toggleNetworkIfNeeded()),
          this.#cdpClient.sendCommand("Target.setAutoAttach", {
            autoAttach: true,
            waitForDebuggerOnStart: true,
            flatten: true
          }),
          this.#updateWindowId(),
          this.#setUserContextConfig(config2),
          this.#initAndEvaluatePreloadScripts(),
          this.#cdpClient.sendCommand("Runtime.runIfWaitingForDebugger"),
          // Resume tab execution as well if it was paused by the debugger.
          this.#parentCdpClient.sendCommand("Runtime.runIfWaitingForDebugger"),
          this.toggleDeviceAccessIfNeeded(),
          this.togglePreloadIfNeeded()
        ]);
        for (const result of results) {
          if (result instanceof Error) {
            this.#logger?.(log_js_1.LogType.debugError, "Error happened when configuring a new target", result);
          }
        }
        this.#unblocked.resolve({
          kind: "success",
          value: void 0
        });
      }
      #restoreFrameTreeState(frameTree) {
        const frame = frameTree.frame;
        const maybeContext = this.#browsingContextStorage.findContext(frame.id);
        if (maybeContext !== void 0) {
          if (maybeContext.parentId === null && frame.parentId !== null && frame.parentId !== void 0) {
            maybeContext.parentId = frame.parentId;
          }
        }
        if (maybeContext === void 0 && frame.parentId !== void 0) {
          const parentBrowsingContext = this.#browsingContextStorage.getContext(frame.parentId);
          BrowsingContextImpl_js_1.BrowsingContextImpl.create(frame.id, frame.parentId, this.userContext, parentBrowsingContext.cdpTarget, this.#eventManager, this.#browsingContextStorage, this.#realmStorage, this.contextConfigStorage, frame.url, void 0, this.#logger);
        }
        frameTree.childFrames?.map((frameTree2) => this.#restoreFrameTreeState(frameTree2));
      }
      async toggleFetchIfNeeded() {
        const stages = this.#networkStorage.getInterceptionStages(this.topLevelId);
        if (this.#fetchDomainStages.request === stages.request && this.#fetchDomainStages.response === stages.response && this.#fetchDomainStages.auth === stages.auth) {
          return;
        }
        const patterns = [];
        this.#fetchDomainStages = stages;
        if (stages.request || stages.auth) {
          patterns.push({
            urlPattern: "*",
            requestStage: "Request"
          });
        }
        if (stages.response) {
          patterns.push({
            urlPattern: "*",
            requestStage: "Response"
          });
        }
        if (patterns.length) {
          await this.#cdpClient.sendCommand("Fetch.enable", {
            patterns,
            handleAuthRequests: stages.auth
          });
        } else {
          const blockedRequest = this.#networkStorage.getRequestsByTarget(this).filter((request) => request.interceptPhase);
          void Promise.allSettled(blockedRequest.map((request) => request.waitNextPhase)).then(async () => {
            const blockedRequest2 = this.#networkStorage.getRequestsByTarget(this).filter((request) => request.interceptPhase);
            if (blockedRequest2.length) {
              return await this.toggleFetchIfNeeded();
            }
            return await this.#cdpClient.sendCommand("Fetch.disable");
          }).catch((error) => {
            this.#logger?.(log_js_1.LogType.bidi, "Disable failed", error);
          });
        }
      }
      /**
       * Toggles CDP "Fetch" domain and enable/disable network cache.
       */
      async toggleNetworkIfNeeded() {
        try {
          await Promise.all([
            this.toggleSetCacheDisabled(),
            this.toggleFetchIfNeeded()
          ]);
        } catch (err) {
          this.#logger?.(log_js_1.LogType.debugError, err);
          if (!this.#isExpectedError(err)) {
            throw err;
          }
        }
      }
      async toggleSetCacheDisabled(disable) {
        const defaultCacheDisabled = this.#networkStorage.defaultCacheBehavior === "bypass";
        const cacheDisabled = disable ?? defaultCacheDisabled;
        if (this.#cacheDisableState === cacheDisabled) {
          return;
        }
        this.#cacheDisableState = cacheDisabled;
        try {
          await this.#cdpClient.sendCommand("Network.setCacheDisabled", {
            cacheDisabled
          });
        } catch (err) {
          this.#logger?.(log_js_1.LogType.debugError, err);
          this.#cacheDisableState = !cacheDisabled;
          if (!this.#isExpectedError(err)) {
            throw err;
          }
        }
      }
      async toggleDeviceAccessIfNeeded() {
        const enabled = this.isSubscribedTo(chromium_bidi_js_1.Bluetooth.EventNames.RequestDevicePromptUpdated);
        if (this.#deviceAccessEnabled === enabled) {
          return;
        }
        this.#deviceAccessEnabled = enabled;
        try {
          await this.#cdpClient.sendCommand(enabled ? "DeviceAccess.enable" : "DeviceAccess.disable");
        } catch (err) {
          this.#logger?.(log_js_1.LogType.debugError, err);
          this.#deviceAccessEnabled = !enabled;
          if (!this.#isExpectedError(err)) {
            throw err;
          }
        }
      }
      async togglePreloadIfNeeded() {
        const enabled = this.isSubscribedTo(chromium_bidi_js_1.Speculation.EventNames.PrefetchStatusUpdated);
        if (this.#preloadEnabled === enabled) {
          return;
        }
        this.#preloadEnabled = enabled;
        try {
          await this.#cdpClient.sendCommand(enabled ? "Preload.enable" : "Preload.disable");
        } catch (err) {
          this.#logger?.(log_js_1.LogType.debugError, err);
          this.#preloadEnabled = !enabled;
          if (!this.#isExpectedError(err)) {
            throw err;
          }
        }
      }
      /**
       * Heuristic checking if the error is due to the session being closed. If so, ignore the
       * error.
       */
      #isExpectedError(err) {
        const error = err;
        return error.code === -32001 && error.message === "Session with given id not found." || this.#cdpClient.isCloseError(err);
      }
      #setEventListeners() {
        this.#cdpClient.on("*", (event, params) => {
          if (typeof event !== "string") {
            return;
          }
          this.#eventManager.registerEvent({
            type: "event",
            method: `goog:cdp.${event}`,
            params: {
              event,
              params,
              session: this.cdpSessionId
            }
          }, this.id);
        });
      }
      async #enableFetch(stages) {
        const patterns = [];
        if (stages.request || stages.auth) {
          patterns.push({
            urlPattern: "*",
            requestStage: "Request"
          });
        }
        if (stages.response) {
          patterns.push({
            urlPattern: "*",
            requestStage: "Response"
          });
        }
        if (patterns.length) {
          const oldStages = this.#fetchDomainStages;
          this.#fetchDomainStages = stages;
          try {
            await this.#cdpClient.sendCommand("Fetch.enable", {
              patterns,
              handleAuthRequests: stages.auth
            });
          } catch {
            this.#fetchDomainStages = oldStages;
          }
        }
      }
      async #disableFetch() {
        const blockedRequest = this.#networkStorage.getRequestsByTarget(this).filter((request) => request.interceptPhase);
        if (blockedRequest.length === 0) {
          this.#fetchDomainStages = {
            request: false,
            response: false,
            auth: false
          };
          await this.#cdpClient.sendCommand("Fetch.disable");
        }
      }
      async toggleNetwork() {
        const stages = this.#networkStorage.getInterceptionStages(this.topLevelId);
        const fetchEnable = Object.values(stages).some((value) => value);
        const fetchChanged = this.#fetchDomainStages.request !== stages.request || this.#fetchDomainStages.response !== stages.response || this.#fetchDomainStages.auth !== stages.auth;
        this.#logger?.(log_js_1.LogType.debugInfo, "Toggle Network", `Fetch (${fetchEnable}) ${fetchChanged}`);
        if (fetchEnable && fetchChanged) {
          await this.#enableFetch(stages);
        }
        if (!fetchEnable && fetchChanged) {
          await this.#disableFetch();
        }
      }
      /**
       * All the ProxyChannels from all the preload scripts of the given
       * BrowsingContext.
       */
      getChannels() {
        return this.#preloadScriptStorage.find().flatMap((script) => script.channels);
      }
      async #updateWindowId() {
        const { windowId } = await this.#browserCdpClient.sendCommand("Browser.getWindowForTarget", { targetId: this.id });
        this.#windowId = windowId;
      }
      /** Loads all top-level preload scripts. */
      async #initAndEvaluatePreloadScripts() {
        await Promise.all(this.#preloadScriptStorage.find({
          // Needed for OOPIF
          targetId: this.topLevelId
        }).map((script) => {
          return script.initInTarget(this, true);
        }));
      }
      async setDeviceMetricsOverride(viewport, devicePixelRatio, screenOrientation, screenArea) {
        if (viewport === null && devicePixelRatio === null && screenOrientation === null && screenArea === null) {
          await this.cdpClient.sendCommand("Emulation.clearDeviceMetricsOverride");
          return;
        }
        const metricsOverride = {
          width: viewport?.width ?? 0,
          height: viewport?.height ?? 0,
          deviceScaleFactor: devicePixelRatio ?? 0,
          screenOrientation: this.#toCdpScreenOrientationAngle(screenOrientation) ?? void 0,
          mobile: false,
          screenWidth: screenArea?.width,
          screenHeight: screenArea?.height
        };
        await this.cdpClient.sendCommand("Emulation.setDeviceMetricsOverride", metricsOverride);
      }
      /**
       * Immediately schedules all the required commands to configure user context
       * configuration and waits for them to finish. It's important to schedule them
       * in parallel, so that they are enqueued before any page's scripts.
       */
      async #setUserContextConfig(config2) {
        const promises = [];
        promises.push(this.#cdpClient.sendCommand("Page.setPrerenderingAllowed", {
          isAllowed: !config2.prerenderingDisabled
        }).catch(() => {
        }));
        if (config2.viewport !== void 0 || config2.devicePixelRatio !== void 0 || config2.screenOrientation !== void 0 || config2.screenArea !== void 0) {
          promises.push(this.setDeviceMetricsOverride(config2.viewport ?? null, config2.devicePixelRatio ?? null, config2.screenOrientation ?? null, config2.screenArea ?? null).catch(() => {
          }));
        }
        if (config2.geolocation !== void 0 && config2.geolocation !== null) {
          promises.push(this.setGeolocationOverride(config2.geolocation));
        }
        if (config2.locale !== void 0) {
          promises.push(this.setLocaleOverride(config2.locale));
        }
        if (config2.timezone !== void 0) {
          promises.push(this.setTimezoneOverride(config2.timezone));
        }
        if (config2.extraHeaders !== void 0) {
          promises.push(this.setExtraHeaders(config2.extraHeaders));
        }
        if (config2.userAgent !== void 0 || config2.locale !== void 0 || config2.clientHints !== void 0) {
          promises.push(this.setUserAgentAndAcceptLanguage(config2.userAgent, config2.locale, config2.clientHints));
        }
        if (config2.scriptingEnabled !== void 0) {
          promises.push(this.setScriptingEnabled(config2.scriptingEnabled));
        }
        if (config2.acceptInsecureCerts !== void 0) {
          promises.push(this.cdpClient.sendCommand("Security.setIgnoreCertificateErrors", {
            ignore: config2.acceptInsecureCerts
          }));
        }
        if (config2.emulatedNetworkConditions !== void 0) {
          promises.push(this.setEmulatedNetworkConditions(config2.emulatedNetworkConditions));
        }
        if (config2.maxTouchPoints !== void 0) {
          promises.push(this.setTouchOverride(config2.maxTouchPoints));
        }
        await Promise.all(promises);
      }
      get topLevelId() {
        return this.#browsingContextStorage.findTopLevelContextId(this.id) ?? this.id;
      }
      isSubscribedTo(moduleOrEvent) {
        return this.#eventManager.subscriptionManager.isSubscribedTo(moduleOrEvent, this.topLevelId);
      }
      #ignoreFileDialog() {
        const config2 = this.contextConfigStorage.getActiveConfig(this.topLevelId, this.userContext);
        return (config2.userPromptHandler?.file ?? config2.userPromptHandler?.default ?? "ignore") === "ignore";
      }
      async setGeolocationOverride(geolocation) {
        if (geolocation === null) {
          await this.cdpClient.sendCommand("Emulation.clearGeolocationOverride");
        } else if ("type" in geolocation) {
          if (geolocation.type !== "positionUnavailable") {
            throw new protocol_js_1.UnknownErrorException(`Unknown geolocation error ${geolocation.type}`);
          }
          await this.cdpClient.sendCommand("Emulation.setGeolocationOverride", {});
        } else if ("latitude" in geolocation) {
          await this.cdpClient.sendCommand("Emulation.setGeolocationOverride", {
            latitude: geolocation.latitude,
            longitude: geolocation.longitude,
            accuracy: geolocation.accuracy ?? 1,
            // `null` value is treated as "missing".
            altitude: geolocation.altitude ?? void 0,
            altitudeAccuracy: geolocation.altitudeAccuracy ?? void 0,
            heading: geolocation.heading ?? void 0,
            speed: geolocation.speed ?? void 0
          });
        } else {
          throw new protocol_js_1.UnknownErrorException("Unexpected geolocation coordinates value");
        }
      }
      async setTouchOverride(maxTouchPoints) {
        const touchEmulationParams = {
          enabled: maxTouchPoints !== null
        };
        if (maxTouchPoints !== null) {
          touchEmulationParams.maxTouchPoints = maxTouchPoints;
        }
        await this.cdpClient.sendCommand("Emulation.setTouchEmulationEnabled", touchEmulationParams);
      }
      #toCdpScreenOrientationAngle(orientation) {
        if (orientation === null) {
          return null;
        }
        if (orientation.natural === "portrait") {
          switch (orientation.type) {
            case "portrait-primary":
              return {
                angle: 0,
                type: "portraitPrimary"
              };
            case "landscape-primary":
              return {
                angle: 90,
                type: "landscapePrimary"
              };
            case "portrait-secondary":
              return {
                angle: 180,
                type: "portraitSecondary"
              };
            case "landscape-secondary":
              return {
                angle: 270,
                type: "landscapeSecondary"
              };
            default:
              throw new protocol_js_1.UnknownErrorException(`Unexpected screen orientation type ${orientation.type}`);
          }
        }
        if (orientation.natural === "landscape") {
          switch (orientation.type) {
            case "landscape-primary":
              return {
                angle: 0,
                type: "landscapePrimary"
              };
            case "portrait-primary":
              return {
                angle: 90,
                type: "portraitPrimary"
              };
            case "landscape-secondary":
              return {
                angle: 180,
                type: "landscapeSecondary"
              };
            case "portrait-secondary":
              return {
                angle: 270,
                type: "portraitSecondary"
              };
            default:
              throw new protocol_js_1.UnknownErrorException(`Unexpected screen orientation type ${orientation.type}`);
          }
        }
        throw new protocol_js_1.UnknownErrorException(`Unexpected orientation natural ${orientation.natural}`);
      }
      async setLocaleOverride(locale) {
        if (locale === null) {
          await this.cdpClient.sendCommand("Emulation.setLocaleOverride", {});
        } else {
          await this.cdpClient.sendCommand("Emulation.setLocaleOverride", {
            locale
          });
        }
      }
      async setScriptingEnabled(scriptingEnabled) {
        await this.cdpClient.sendCommand("Emulation.setScriptExecutionDisabled", {
          value: scriptingEnabled === false
        });
      }
      async setTimezoneOverride(timezone) {
        if (timezone === null) {
          await this.cdpClient.sendCommand("Emulation.setTimezoneOverride", {
            // If empty, disables the override and restores default host system timezone.
            timezoneId: ""
          });
        } else {
          await this.cdpClient.sendCommand("Emulation.setTimezoneOverride", {
            timezoneId: timezone
          });
        }
      }
      async setExtraHeaders(headers) {
        await this.cdpClient.sendCommand("Network.setExtraHTTPHeaders", {
          headers
        });
      }
      async setUserAgentAndAcceptLanguage(userAgent, acceptLanguage, clientHints) {
        const userAgentMetadata = clientHints ? {
          brands: clientHints.brands?.map((b) => ({
            brand: b.brand,
            version: b.version
          })),
          fullVersionList: clientHints.fullVersionList,
          platform: clientHints.platform ?? "",
          platformVersion: clientHints.platformVersion ?? "",
          architecture: clientHints.architecture ?? "",
          model: clientHints.model ?? "",
          mobile: clientHints.mobile ?? false,
          bitness: clientHints.bitness ?? void 0,
          wow64: clientHints.wow64 ?? void 0,
          formFactors: clientHints.formFactors ?? void 0
        } : void 0;
        await this.cdpClient.sendCommand("Emulation.setUserAgentOverride", {
          // `userAgent` is required if `userAgentMetadata` is provided.
          userAgent: userAgent || (userAgentMetadata ? this.#defaultUserAgent : ""),
          acceptLanguage: acceptLanguage ?? void 0,
          // We need to provide the platform to enable platform emulation.
          // Note that the value might be different from the one expected by the
          // legacy `navigator.platform` (e.g. `Win32` vs `Windows`).
          // https://github.com/w3c/webdriver-bidi/issues/1065
          platform: clientHints?.platform ?? void 0,
          userAgentMetadata
        });
      }
      async setEmulatedNetworkConditions(networkConditions) {
        if (networkConditions !== null && networkConditions.type !== "offline") {
          throw new protocol_js_1.UnsupportedOperationException(`Unsupported network conditions ${networkConditions.type}`);
        }
        await Promise.all([
          this.cdpClient.sendCommand("Network.emulateNetworkConditionsByRule", {
            offline: networkConditions?.type === "offline",
            matchedNetworkConditions: [
              {
                urlPattern: "",
                latency: 0,
                downloadThroughput: -1,
                uploadThroughput: -1
              }
            ]
          }),
          this.cdpClient.sendCommand("Network.overrideNetworkState", {
            offline: networkConditions?.type === "offline",
            // TODO: restore the original `latency` value when emulation is removed.
            latency: 0,
            downloadThroughput: -1,
            uploadThroughput: -1
          })
        ]);
      }
    };
    exports2.CdpTarget = CdpTarget;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/cdp/CdpTargetManager.js
var require_CdpTargetManager = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/cdp/CdpTargetManager.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CdpTargetManager = void 0;
    var log_js_1 = require_log();
    var BrowsingContextImpl_js_1 = require_BrowsingContextImpl();
    var WorkerRealm_js_1 = require_WorkerRealm();
    var CdpTarget_js_1 = require_CdpTarget();
    var cdpToBidiTargetTypes = {
      service_worker: "service-worker",
      shared_worker: "shared-worker",
      worker: "dedicated-worker"
    };
    var CdpTargetManager = class {
      #browserCdpClient;
      #cdpConnection;
      #targetKeysToBeIgnoredByAutoAttach = /* @__PURE__ */ new Set();
      #selfTargetId;
      #eventManager;
      #browsingContextStorage;
      #networkStorage;
      #bluetoothProcessor;
      #preloadScriptStorage;
      #realmStorage;
      #configStorage;
      #speculationProcessor;
      #defaultUserContextId;
      #defaultUserAgent;
      #logger;
      constructor(cdpConnection, browserCdpClient, selfTargetId, eventManager, browsingContextStorage, realmStorage, networkStorage, configStorage, bluetoothProcessor, speculationProcessor, preloadScriptStorage, defaultUserContextId, defaultUserAgent, logger) {
        this.#cdpConnection = cdpConnection;
        this.#browserCdpClient = browserCdpClient;
        this.#targetKeysToBeIgnoredByAutoAttach.add(selfTargetId);
        this.#selfTargetId = selfTargetId;
        this.#eventManager = eventManager;
        this.#browsingContextStorage = browsingContextStorage;
        this.#preloadScriptStorage = preloadScriptStorage;
        this.#networkStorage = networkStorage;
        this.#configStorage = configStorage;
        this.#bluetoothProcessor = bluetoothProcessor;
        this.#speculationProcessor = speculationProcessor;
        this.#realmStorage = realmStorage;
        this.#defaultUserContextId = defaultUserContextId;
        this.#defaultUserAgent = defaultUserAgent;
        this.#logger = logger;
        this.#setEventListeners(browserCdpClient);
      }
      /**
       * This method is called for each CDP session, since this class is responsible
       * for creating and destroying all targets and browsing contexts.
       */
      #setEventListeners(cdpClient) {
        cdpClient.on("Target.attachedToTarget", (params) => {
          this.#handleAttachedToTargetEvent(params, cdpClient);
        });
        cdpClient.on("Target.detachedFromTarget", this.#handleDetachedFromTargetEvent.bind(this));
        cdpClient.on("Target.targetInfoChanged", this.#handleTargetInfoChangedEvent.bind(this));
        cdpClient.on("Inspector.targetCrashed", () => {
          this.#handleTargetCrashedEvent(cdpClient);
        });
        cdpClient.on("Page.frameAttached", this.#handleFrameAttachedEvent.bind(this));
        cdpClient.on("Page.frameSubtreeWillBeDetached", this.#handleFrameSubtreeWillBeDetached.bind(this));
      }
      #handleFrameAttachedEvent(params) {
        const parentBrowsingContext = this.#browsingContextStorage.findContext(params.parentFrameId);
        if (parentBrowsingContext !== void 0) {
          BrowsingContextImpl_js_1.BrowsingContextImpl.create(
            params.frameId,
            params.parentFrameId,
            parentBrowsingContext.userContext,
            parentBrowsingContext.cdpTarget,
            this.#eventManager,
            this.#browsingContextStorage,
            this.#realmStorage,
            this.#configStorage,
            // At this point, we don't know the URL of the frame yet, so it will be updated
            // later.
            "about:blank",
            void 0,
            this.#logger
          );
        }
      }
      #handleFrameSubtreeWillBeDetached(params) {
        this.#browsingContextStorage.findContext(params.frameId)?.dispose(true);
      }
      #handleAttachedToTargetEvent(params, parentSessionCdpClient) {
        const { sessionId, targetInfo } = params;
        const targetCdpClient = this.#cdpConnection.getCdpClient(sessionId);
        const detach = async () => {
          await targetCdpClient.sendCommand("Runtime.runIfWaitingForDebugger").then(() => parentSessionCdpClient.sendCommand("Target.detachFromTarget", params)).catch((error) => this.#logger?.(log_js_1.LogType.debugError, error));
        };
        if (this.#selfTargetId === targetInfo.targetId) {
          void detach();
          return;
        }
        const targetKey = targetInfo.type === "service_worker" ? `${parentSessionCdpClient.sessionId}_${targetInfo.targetId}` : targetInfo.targetId;
        if (this.#targetKeysToBeIgnoredByAutoAttach.has(targetKey)) {
          return;
        }
        this.#targetKeysToBeIgnoredByAutoAttach.add(targetKey);
        const userContext = targetInfo.browserContextId && targetInfo.browserContextId !== this.#defaultUserContextId ? targetInfo.browserContextId : "default";
        switch (targetInfo.type) {
          case "tab": {
            this.#setEventListeners(targetCdpClient);
            void (async () => {
              await targetCdpClient.sendCommand("Target.setAutoAttach", {
                autoAttach: true,
                waitForDebuggerOnStart: true,
                flatten: true
              });
            })();
            return;
          }
          case "page":
          case "iframe": {
            const cdpTarget = this.#createCdpTarget(targetCdpClient, parentSessionCdpClient, targetInfo, userContext);
            const maybeContext = this.#browsingContextStorage.findContext(targetInfo.targetId);
            if (maybeContext && targetInfo.type === "iframe") {
              maybeContext.updateCdpTarget(cdpTarget);
            } else {
              const parentId = this.#findFrameParentId(targetInfo, parentSessionCdpClient.sessionId);
              BrowsingContextImpl_js_1.BrowsingContextImpl.create(
                targetInfo.targetId,
                parentId,
                userContext,
                cdpTarget,
                this.#eventManager,
                this.#browsingContextStorage,
                this.#realmStorage,
                this.#configStorage,
                // Hack: when a new target created, CDP emits targetInfoChanged with an empty
                // url, and navigates it to about:blank later. When the event is emitted for
                // an existing target (reconnect), the url is already known, and navigation
                // events will not be emitted anymore. Replacing empty url with `about:blank`
                // allows to handle both cases in the same way.
                // "7.3.2.1 Creating browsing contexts".
                // https://html.spec.whatwg.org/multipage/document-sequences.html#creating-browsing-contexts
                // TODO: check who to deal with non-null creator and its `creatorOrigin`.
                targetInfo.url === "" ? "about:blank" : targetInfo.url,
                targetInfo.openerFrameId ?? targetInfo.openerId,
                this.#logger
              );
            }
            return;
          }
          case "service_worker":
          case "worker": {
            const realm = this.#realmStorage.findRealm({
              cdpSessionId: parentSessionCdpClient.sessionId,
              sandbox: null
              // Non-sandboxed realms.
            });
            if (!realm) {
              void detach();
              return;
            }
            const cdpTarget = this.#createCdpTarget(targetCdpClient, parentSessionCdpClient, targetInfo, userContext);
            this.#handleWorkerTarget(cdpToBidiTargetTypes[targetInfo.type], cdpTarget, realm);
            return;
          }
          // In CDP, we only emit shared workers on the browser and not the set of
          // frames that use the shared worker. If we change this in the future to
          // behave like service workers (emits on both browser and frame targets),
          // we can remove this block and merge service workers with the above one.
          case "shared_worker": {
            const cdpTarget = this.#createCdpTarget(targetCdpClient, parentSessionCdpClient, targetInfo, userContext);
            this.#handleWorkerTarget(cdpToBidiTargetTypes[targetInfo.type], cdpTarget);
            return;
          }
        }
        void detach();
      }
      /** Try to find the parent browsing context ID for the given attached target. */
      #findFrameParentId(targetInfo, parentSessionId) {
        if (targetInfo.type !== "iframe") {
          return null;
        }
        const parentId = targetInfo.openerFrameId ?? targetInfo.openerId;
        if (parentId !== void 0) {
          return parentId;
        }
        if (parentSessionId !== void 0) {
          return this.#browsingContextStorage.findContextBySession(parentSessionId)?.id ?? null;
        }
        return null;
      }
      #createCdpTarget(targetCdpClient, parentCdpClient, targetInfo, userContext) {
        this.#setEventListeners(targetCdpClient);
        this.#preloadScriptStorage.onCdpTargetCreated(targetInfo.targetId, userContext);
        const target = CdpTarget_js_1.CdpTarget.create(
          targetInfo.targetId,
          targetCdpClient,
          this.#browserCdpClient,
          parentCdpClient,
          this.#realmStorage,
          this.#eventManager,
          this.#preloadScriptStorage,
          this.#browsingContextStorage,
          this.#networkStorage,
          this.#configStorage,
          userContext,
          // Pass the cached default User Agent to the new target.
          this.#defaultUserAgent,
          this.#logger
        );
        this.#networkStorage.onCdpTargetCreated(target);
        this.#bluetoothProcessor.onCdpTargetCreated(target);
        this.#speculationProcessor.onCdpTargetCreated(target);
        return target;
      }
      #workers = /* @__PURE__ */ new Map();
      #handleWorkerTarget(realmType, cdpTarget, ownerRealm) {
        cdpTarget.cdpClient.on("Runtime.executionContextCreated", (params) => {
          const { uniqueId, id, origin } = params.context;
          const workerRealm = new WorkerRealm_js_1.WorkerRealm(cdpTarget.cdpClient, this.#eventManager, id, this.#logger, (0, BrowsingContextImpl_js_1.serializeOrigin)(origin), ownerRealm ? [ownerRealm] : [], uniqueId, this.#realmStorage, realmType);
          this.#workers.set(cdpTarget.cdpSessionId, workerRealm);
        });
      }
      #handleDetachedFromTargetEvent({ sessionId, targetId }) {
        if (targetId) {
          this.#preloadScriptStorage.find({ targetId }).map((preloadScript) => {
            preloadScript.dispose(targetId);
          });
        }
        const context = this.#browsingContextStorage.findContextBySession(sessionId);
        if (context) {
          context.dispose(true);
          return;
        }
        const worker = this.#workers.get(sessionId);
        if (worker) {
          this.#realmStorage.deleteRealms({
            cdpSessionId: worker.cdpClient.sessionId
          });
        }
      }
      #handleTargetInfoChangedEvent(params) {
        const context = this.#browsingContextStorage.findContext(params.targetInfo.targetId);
        if (context) {
          context.onTargetInfoChanged(params);
        }
      }
      #handleTargetCrashedEvent(cdpClient) {
        const realms = this.#realmStorage.findRealms({
          cdpSessionId: cdpClient.sessionId
        });
        for (const realm of realms) {
          realm.dispose();
        }
      }
    };
    exports2.CdpTargetManager = CdpTargetManager;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/context/BrowsingContextStorage.js
var require_BrowsingContextStorage = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/context/BrowsingContextStorage.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BrowsingContextStorage = void 0;
    var protocol_js_1 = require_protocol();
    var EventEmitter_js_1 = require_EventEmitter2();
    var BrowsingContextStorage = class {
      /** Map from context ID to context implementation. */
      #contexts = /* @__PURE__ */ new Map();
      /** Event emitter for browsing context storage eventsis not expected to be exposed to
       * the outside world. */
      #eventEmitter = new EventEmitter_js_1.EventEmitter();
      /** Gets all top-level contexts, i.e. those with no parent. */
      getTopLevelContexts() {
        return this.getAllContexts().filter((context) => context.isTopLevelContext());
      }
      /** Gets all contexts. */
      getAllContexts() {
        return Array.from(this.#contexts.values());
      }
      /** Deletes the context with the given ID. */
      deleteContextById(id) {
        this.#contexts.delete(id);
      }
      /** Deletes the given context. */
      deleteContext(context) {
        this.#contexts.delete(context.id);
      }
      /** Tracks the given context. */
      addContext(context) {
        this.#contexts.set(context.id, context);
        this.#eventEmitter.emit("added", {
          browsingContext: context
        });
      }
      /**
       * Waits for a context with the given ID to be added and returns it.
       */
      waitForContext(browsingContextId) {
        if (this.#contexts.has(browsingContextId)) {
          return Promise.resolve(this.getContext(browsingContextId));
        }
        return new Promise((resolve5) => {
          const listener = (event) => {
            if (event.browsingContext.id === browsingContextId) {
              this.#eventEmitter.off("added", listener);
              resolve5(event.browsingContext);
            }
          };
          this.#eventEmitter.on("added", listener);
        });
      }
      /** Returns true whether there is an existing context with the given ID. */
      hasContext(id) {
        return this.#contexts.has(id);
      }
      /** Gets the context with the given ID, if any. */
      findContext(id) {
        return this.#contexts.get(id);
      }
      /** Returns the top-level context ID of the given context, if any. */
      findTopLevelContextId(id) {
        if (id === null) {
          return null;
        }
        const maybeContext = this.findContext(id);
        if (!maybeContext) {
          return null;
        }
        const parentId = maybeContext.parentId ?? null;
        if (parentId === null) {
          return id;
        }
        return this.findTopLevelContextId(parentId);
      }
      findContextBySession(sessionId) {
        for (const context of this.#contexts.values()) {
          if (context.cdpTarget.cdpSessionId === sessionId) {
            return context;
          }
        }
        return;
      }
      /** Gets the context with the given ID, if any, otherwise throws. */
      getContext(id) {
        const result = this.findContext(id);
        if (result === void 0) {
          throw new protocol_js_1.NoSuchFrameException(`Context ${id} not found`);
        }
        return result;
      }
      verifyTopLevelContextsList(contexts) {
        const foundContexts = /* @__PURE__ */ new Set();
        if (!contexts) {
          return foundContexts;
        }
        for (const contextId of contexts) {
          const context = this.getContext(contextId);
          if (context.isTopLevelContext()) {
            foundContexts.add(context);
          } else {
            throw new protocol_js_1.InvalidArgumentException(`Non top-level context '${contextId}' given.`);
          }
        }
        return foundContexts;
      }
      verifyContextsList(contexts) {
        if (!contexts.length) {
          return;
        }
        for (const contextId of contexts) {
          this.getContext(contextId);
        }
      }
    };
    exports2.BrowsingContextStorage = BrowsingContextStorage;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/script/PreloadScriptStorage.js
var require_PreloadScriptStorage = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/script/PreloadScriptStorage.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PreloadScriptStorage = void 0;
    var ErrorResponse_js_1 = require_ErrorResponse();
    var PreloadScriptStorage = class {
      /** Tracks all BiDi preload scripts.  */
      #scripts = /* @__PURE__ */ new Set();
      /**
       * Finds all entries that match the given filter (OR logic).
       */
      find(filter) {
        if (!filter) {
          return [...this.#scripts];
        }
        return [...this.#scripts].filter((script) => {
          if (script.contexts === void 0 && script.userContexts === void 0) {
            return true;
          }
          if (filter.targetId !== void 0 && script.targetIds.has(filter.targetId)) {
            return true;
          }
          return false;
        });
      }
      add(preloadScript) {
        this.#scripts.add(preloadScript);
      }
      /** Deletes all BiDi preload script entries that match the given filter. */
      remove(id) {
        const script = [...this.#scripts].find((script2) => script2.id === id);
        if (script === void 0) {
          throw new ErrorResponse_js_1.NoSuchScriptException(`No preload script with id '${id}'`);
        }
        this.#scripts.delete(script);
      }
      /** Gets the preload script with the given ID, if any, otherwise throws. */
      getPreloadScript(id) {
        const script = [...this.#scripts].find((script2) => script2.id === id);
        if (script === void 0) {
          throw new ErrorResponse_js_1.NoSuchScriptException(`No preload script with id '${id}'`);
        }
        return script;
      }
      onCdpTargetCreated(targetId, userContext) {
        const scriptInUserContext = [...this.#scripts].filter((script) => {
          if (!script.userContexts && !script.contexts) {
            return true;
          }
          return script.userContexts?.includes(userContext);
        });
        for (const script of scriptInUserContext) {
          script.targetIds.add(targetId);
        }
      }
    };
    exports2.PreloadScriptStorage = PreloadScriptStorage;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/script/RealmStorage.js
var require_RealmStorage = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/script/RealmStorage.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RealmStorage = void 0;
    var protocol_js_1 = require_protocol();
    var WindowRealm_js_1 = require_WindowRealm();
    var RealmStorage = class {
      /** Tracks handles and their realms sent to the client. */
      #knownHandlesToRealmMap = /* @__PURE__ */ new Map();
      /** Map from realm ID to Realm. */
      #realmMap = /* @__PURE__ */ new Map();
      /** List of the internal sandboxed realms which should not be reported to the user. */
      hiddenSandboxes = /* @__PURE__ */ new Set();
      get knownHandlesToRealmMap() {
        return this.#knownHandlesToRealmMap;
      }
      addRealm(realm) {
        this.#realmMap.set(realm.realmId, realm);
      }
      /** Finds all realms that match the given filter. */
      findRealms(filter) {
        const sandboxFilterValue = filter.sandbox === null ? void 0 : filter.sandbox;
        return Array.from(this.#realmMap.values()).filter((realm) => {
          if (filter.realmId !== void 0 && filter.realmId !== realm.realmId) {
            return false;
          }
          if (filter.browsingContextId !== void 0 && !realm.associatedBrowsingContexts.map((browsingContext) => browsingContext.id).includes(filter.browsingContextId)) {
            return false;
          }
          if (filter.sandbox !== void 0 && (!(realm instanceof WindowRealm_js_1.WindowRealm) || sandboxFilterValue !== realm.sandbox)) {
            return false;
          }
          if (filter.executionContextId !== void 0 && filter.executionContextId !== realm.executionContextId) {
            return false;
          }
          if (filter.origin !== void 0 && filter.origin !== realm.origin) {
            return false;
          }
          if (filter.type !== void 0 && filter.type !== realm.realmType) {
            return false;
          }
          if (filter.cdpSessionId !== void 0 && filter.cdpSessionId !== realm.cdpClient.sessionId) {
            return false;
          }
          if (filter.isHidden !== void 0 && filter.isHidden !== realm.isHidden()) {
            return false;
          }
          return true;
        });
      }
      findRealm(filter) {
        return this.findRealms(filter)[0];
      }
      /** Gets the only realm that matches the given filter, if any, otherwise throws. */
      getRealm(filter) {
        const maybeRealm = this.findRealm(filter);
        if (maybeRealm === void 0) {
          throw new protocol_js_1.NoSuchFrameException(`Realm ${JSON.stringify(filter)} not found`);
        }
        return maybeRealm;
      }
      /** Deletes all realms that match the given filter. */
      deleteRealms(filter) {
        this.findRealms(filter).map((realm) => {
          realm.dispose();
          this.#realmMap.delete(realm.realmId);
          Array.from(this.knownHandlesToRealmMap.entries()).filter(([, r]) => r === realm.realmId).map(([handle]) => this.knownHandlesToRealmMap.delete(handle));
        });
      }
    };
    exports2.RealmStorage = RealmStorage;
  }
});

// node_modules/chromium-bidi/lib/cjs/utils/Buffer.js
var require_Buffer = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/utils/Buffer.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Buffer = void 0;
    var Buffer2 = class {
      #capacity;
      #entries = [];
      #onItemRemoved;
      /**
       * @param capacity The buffer capacity.
       * @param onItemRemoved Delegate called for each removed element.
       */
      constructor(capacity, onItemRemoved) {
        this.#capacity = capacity;
        this.#onItemRemoved = onItemRemoved;
      }
      get() {
        return this.#entries;
      }
      add(value) {
        this.#entries.push(value);
        while (this.#entries.length > this.#capacity) {
          const item = this.#entries.shift();
          if (item !== void 0) {
            this.#onItemRemoved?.(item);
          }
        }
      }
    };
    exports2.Buffer = Buffer2;
  }
});

// node_modules/chromium-bidi/lib/cjs/utils/IdWrapper.js
var require_IdWrapper = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/utils/IdWrapper.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.IdWrapper = void 0;
    var IdWrapper = class _IdWrapper {
      static #counter = 0;
      #id;
      constructor() {
        this.#id = ++_IdWrapper.#counter;
      }
      get id() {
        return this.#id;
      }
    };
    exports2.IdWrapper = IdWrapper;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/session/events.js
var require_events = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/session/events.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isCdpEvent = isCdpEvent;
    exports2.assertSupportedEvent = assertSupportedEvent;
    var protocol_js_1 = require_protocol();
    function isCdpEvent(name) {
      return name.split(".").at(0)?.startsWith(protocol_js_1.ChromiumBidi.BiDiModule.Cdp) ?? false;
    }
    function assertSupportedEvent(name) {
      if (!protocol_js_1.ChromiumBidi.EVENT_NAMES.has(name) && !isCdpEvent(name)) {
        throw new protocol_js_1.InvalidArgumentException(`Unknown event: ${name}`);
      }
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/session/SubscriptionManager.js
var require_SubscriptionManager = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/session/SubscriptionManager.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SubscriptionManager = void 0;
    exports2.cartesianProduct = cartesianProduct;
    exports2.unrollEvents = unrollEvents;
    exports2.difference = difference;
    var protocol_js_1 = require_protocol();
    var uuid_js_1 = require_uuid();
    function cartesianProduct(...a) {
      return a.reduce((a2, b) => a2.flatMap((d) => b.map((e) => [d, e].flat())));
    }
    function unrollEvents(events) {
      const allEvents = /* @__PURE__ */ new Set();
      function addEvents(events2) {
        for (const event of events2) {
          allEvents.add(event);
        }
      }
      for (const event of events) {
        switch (event) {
          case protocol_js_1.ChromiumBidi.BiDiModule.Bluetooth:
            addEvents(Object.values(protocol_js_1.ChromiumBidi.Bluetooth.EventNames));
            break;
          case protocol_js_1.ChromiumBidi.BiDiModule.BrowsingContext:
            addEvents(Object.values(protocol_js_1.ChromiumBidi.BrowsingContext.EventNames));
            break;
          case protocol_js_1.ChromiumBidi.BiDiModule.Input:
            addEvents(Object.values(protocol_js_1.ChromiumBidi.Input.EventNames));
            break;
          case protocol_js_1.ChromiumBidi.BiDiModule.Log:
            addEvents(Object.values(protocol_js_1.ChromiumBidi.Log.EventNames));
            break;
          case protocol_js_1.ChromiumBidi.BiDiModule.Network:
            addEvents(Object.values(protocol_js_1.ChromiumBidi.Network.EventNames));
            break;
          case protocol_js_1.ChromiumBidi.BiDiModule.Script:
            addEvents(Object.values(protocol_js_1.ChromiumBidi.Script.EventNames));
            break;
          case protocol_js_1.ChromiumBidi.BiDiModule.Speculation:
            addEvents(Object.values(protocol_js_1.ChromiumBidi.Speculation.EventNames));
            break;
          default:
            allEvents.add(event);
        }
      }
      return allEvents.values();
    }
    var SubscriptionManager = class {
      #subscriptions = [];
      #knownSubscriptionIds = /* @__PURE__ */ new Set();
      #browsingContextStorage;
      constructor(browsingContextStorage) {
        this.#browsingContextStorage = browsingContextStorage;
      }
      getGoogChannelsSubscribedToEvent(eventName, contextId) {
        const googChannels = /* @__PURE__ */ new Set();
        for (const subscription of this.#subscriptions) {
          if (this.#isSubscribedTo(subscription, eventName, contextId)) {
            googChannels.add(subscription.googChannel);
          }
        }
        return Array.from(googChannels);
      }
      getGoogChannelsSubscribedToEventGlobally(eventName) {
        const googChannels = /* @__PURE__ */ new Set();
        for (const subscription of this.#subscriptions) {
          if (this.#isSubscribedTo(subscription, eventName)) {
            googChannels.add(subscription.googChannel);
          }
        }
        return Array.from(googChannels);
      }
      #isSubscribedTo(subscription, moduleOrEvent, browsingContextId) {
        let includesEvent = false;
        for (const eventName of subscription.eventNames) {
          if (
            // Event explicitly subscribed
            eventName === moduleOrEvent || // Event subscribed via module
            eventName === moduleOrEvent.split(".").at(0) || // Event explicitly subscribed compared to module
            eventName.split(".").at(0) === moduleOrEvent
          ) {
            includesEvent = true;
            break;
          }
        }
        if (!includesEvent) {
          return false;
        }
        if (subscription.userContextIds.size !== 0) {
          if (!browsingContextId) {
            return false;
          }
          const context = this.#browsingContextStorage.findContext(browsingContextId);
          if (!context) {
            return false;
          }
          return subscription.userContextIds.has(context.userContext);
        }
        if (subscription.topLevelTraversableIds.size !== 0) {
          if (!browsingContextId) {
            return false;
          }
          const topLevelContext = this.#browsingContextStorage.findTopLevelContextId(browsingContextId);
          return topLevelContext !== null && subscription.topLevelTraversableIds.has(topLevelContext);
        }
        return true;
      }
      isSubscribedTo(moduleOrEvent, contextId) {
        for (const subscription of this.#subscriptions) {
          if (this.#isSubscribedTo(subscription, moduleOrEvent, contextId)) {
            return true;
          }
        }
        return false;
      }
      /**
       * Subscribes to event in the given context and goog:channel.
       * @return {SubscriptionItem[]} List of
       * subscriptions. If the event is a whole module, it will return all the specific
       * events. If the contextId is null, it will return all the top-level contexts which were
       * not subscribed before the command.
       */
      subscribe(eventNames, contextIds, userContextIds, googChannel) {
        const subscription = {
          id: (0, uuid_js_1.uuidv4)(),
          eventNames: new Set(unrollEvents(eventNames)),
          topLevelTraversableIds: new Set(contextIds.map((contextId) => {
            const topLevelContext = this.#browsingContextStorage.findTopLevelContextId(contextId);
            if (!topLevelContext) {
              throw new protocol_js_1.NoSuchFrameException(`Top-level navigable not found for context id ${contextId}`);
            }
            return topLevelContext;
          })),
          userContextIds: new Set(userContextIds),
          googChannel
        };
        this.#subscriptions.push(subscription);
        this.#knownSubscriptionIds.add(subscription.id);
        return subscription;
      }
      /**
       * Unsubscribes atomically from all events in the given contexts and channel.
       *
       * This is a legacy spec branch to unsubscribe by attributes.
       */
      unsubscribe(inputEventNames, googChannel) {
        const eventNames = new Set(unrollEvents(inputEventNames));
        const newSubscriptions = [];
        const eventsMatched = /* @__PURE__ */ new Set();
        for (const subscription of this.#subscriptions) {
          if (subscription.googChannel !== googChannel) {
            newSubscriptions.push(subscription);
            continue;
          }
          if (subscription.userContextIds.size !== 0) {
            newSubscriptions.push(subscription);
            continue;
          }
          if (intersection(subscription.eventNames, eventNames).size === 0) {
            newSubscriptions.push(subscription);
            continue;
          }
          if (subscription.topLevelTraversableIds.size !== 0) {
            newSubscriptions.push(subscription);
            continue;
          }
          const subscriptionEventNames = new Set(subscription.eventNames);
          for (const eventName of eventNames) {
            if (subscriptionEventNames.has(eventName)) {
              eventsMatched.add(eventName);
              subscriptionEventNames.delete(eventName);
            }
          }
          if (subscriptionEventNames.size !== 0) {
            newSubscriptions.push({
              ...subscription,
              eventNames: subscriptionEventNames
            });
          }
        }
        if (!equal(eventsMatched, eventNames)) {
          throw new protocol_js_1.InvalidArgumentException("No subscription found");
        }
        this.#subscriptions = newSubscriptions;
      }
      /**
       * Unsubscribes by subscriptionId.
       */
      unsubscribeById(subscriptionIds) {
        const subscriptionIdsSet = new Set(subscriptionIds);
        const unknownIds = difference(subscriptionIdsSet, this.#knownSubscriptionIds);
        if (unknownIds.size !== 0) {
          throw new protocol_js_1.InvalidArgumentException("No subscription found");
        }
        this.#subscriptions = this.#subscriptions.filter((subscription) => {
          return !subscriptionIdsSet.has(subscription.id);
        });
        this.#knownSubscriptionIds = difference(this.#knownSubscriptionIds, subscriptionIdsSet);
      }
    };
    exports2.SubscriptionManager = SubscriptionManager;
    function intersection(setA, setB) {
      const result = /* @__PURE__ */ new Set();
      for (const a of setA) {
        if (setB.has(a)) {
          result.add(a);
        }
      }
      return result;
    }
    function difference(setA, setB) {
      const result = /* @__PURE__ */ new Set();
      for (const a of setA) {
        if (!setB.has(a)) {
          result.add(a);
        }
      }
      return result;
    }
    function equal(setA, setB) {
      if (setA.size !== setB.size) {
        return false;
      }
      for (const a of setA) {
        if (!setB.has(a)) {
          return false;
        }
      }
      return true;
    }
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/session/EventManager.js
var require_EventManager = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/session/EventManager.js"(exports2) {
    "use strict";
    init_prefix();
    var _a2;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.EventManager = void 0;
    var protocol_js_1 = require_protocol();
    var Buffer_js_1 = require_Buffer();
    var DefaultMap_js_1 = require_DefaultMap();
    var EventEmitter_js_1 = require_EventEmitter2();
    var IdWrapper_js_1 = require_IdWrapper();
    var OutgoingMessage_js_1 = require_OutgoingMessage();
    var events_js_1 = require_events();
    var SubscriptionManager_js_1 = require_SubscriptionManager();
    var EventWrapper = class {
      #idWrapper = new IdWrapper_js_1.IdWrapper();
      #contextId;
      #event;
      constructor(event, contextId) {
        this.#event = event;
        this.#contextId = contextId;
      }
      get id() {
        return this.#idWrapper.id;
      }
      get contextId() {
        return this.#contextId;
      }
      get event() {
        return this.#event;
      }
    };
    var eventBufferLength = /* @__PURE__ */ new Map([[protocol_js_1.ChromiumBidi.Log.EventNames.LogEntryAdded, 100]]);
    var EventManager = class extends EventEmitter_js_1.EventEmitter {
      /**
       * Maps event name to a set of contexts where this event already happened.
       * Needed for getting buffered events from all the contexts in case of
       * subscripting to all contexts.
       */
      #eventToContextsMap = new DefaultMap_js_1.DefaultMap(() => /* @__PURE__ */ new Set());
      /**
       * Maps `eventName` + `browsingContext` to buffer. Used to get buffered events
       * during subscription. Channel-agnostic.
       */
      #eventBuffers = /* @__PURE__ */ new Map();
      /**
       * Maps `eventName` + `browsingContext` to  Map of goog:channel to last id.
       * Used to avoid sending duplicated events when user
       * subscribes -> unsubscribes -> subscribes.
       */
      #lastMessageSent = /* @__PURE__ */ new Map();
      #subscriptionManager;
      #browsingContextStorage;
      /**
       * Map of event name to hooks to be called when client is subscribed to the event.
       */
      #subscribeHooks;
      #userContextStorage;
      constructor(browsingContextStorage, userContextStorage) {
        super();
        this.#browsingContextStorage = browsingContextStorage;
        this.#userContextStorage = userContextStorage;
        this.#subscriptionManager = new SubscriptionManager_js_1.SubscriptionManager(browsingContextStorage);
        this.#subscribeHooks = new DefaultMap_js_1.DefaultMap(() => []);
      }
      get subscriptionManager() {
        return this.#subscriptionManager;
      }
      /**
       * Returns consistent key to be used to access value maps.
       */
      static #getMapKey(eventName, browsingContext) {
        return JSON.stringify({ eventName, browsingContext });
      }
      addSubscribeHook(event, hook) {
        this.#subscribeHooks.get(event).push(hook);
      }
      registerEvent(event, contextId) {
        this.registerPromiseEvent(Promise.resolve({
          kind: "success",
          value: event
        }), contextId, event.method);
      }
      registerGlobalEvent(event) {
        this.registerGlobalPromiseEvent(Promise.resolve({
          kind: "success",
          value: event
        }), event.method);
      }
      registerPromiseEvent(event, contextId, eventName) {
        const eventWrapper = new EventWrapper(event, contextId);
        const sortedGoogChannels = this.#subscriptionManager.getGoogChannelsSubscribedToEvent(eventName, contextId);
        this.#bufferEvent(eventWrapper, eventName);
        for (const googChannel of sortedGoogChannels) {
          this.emit("event", {
            message: OutgoingMessage_js_1.OutgoingMessage.createFromPromise(event, googChannel),
            event: eventName
          });
          this.#markEventSent(eventWrapper, googChannel, eventName);
        }
      }
      registerGlobalPromiseEvent(event, eventName) {
        const eventWrapper = new EventWrapper(event, null);
        const sortedGoogChannels = this.#subscriptionManager.getGoogChannelsSubscribedToEventGlobally(eventName);
        this.#bufferEvent(eventWrapper, eventName);
        for (const googChannel of sortedGoogChannels) {
          this.emit("event", {
            message: OutgoingMessage_js_1.OutgoingMessage.createFromPromise(event, googChannel),
            event: eventName
          });
          this.#markEventSent(eventWrapper, googChannel, eventName);
        }
      }
      async subscribe(eventNames, contextIds, userContextIds, googChannel) {
        for (const name of eventNames) {
          (0, events_js_1.assertSupportedEvent)(name);
        }
        if (userContextIds.length && contextIds.length) {
          throw new protocol_js_1.InvalidArgumentException("Both userContexts and contexts cannot be specified.");
        }
        this.#browsingContextStorage.verifyContextsList(contextIds);
        await this.#userContextStorage.verifyUserContextIdList(userContextIds);
        const unrolledEventNames = new Set((0, SubscriptionManager_js_1.unrollEvents)(eventNames));
        const subscribeStepEvents = /* @__PURE__ */ new Map();
        const subscriptionNavigableIds = new Set(contextIds.length ? contextIds.map((contextId) => {
          const id = this.#browsingContextStorage.findTopLevelContextId(contextId);
          if (!id) {
            throw new protocol_js_1.InvalidArgumentException("Invalid context id");
          }
          return id;
        }) : this.#browsingContextStorage.getTopLevelContexts().map((c) => c.id));
        for (const eventName of unrolledEventNames) {
          const subscribedNavigableIds = new Set(this.#browsingContextStorage.getTopLevelContexts().map((c) => c.id).filter((id) => {
            return this.#subscriptionManager.isSubscribedTo(eventName, id);
          }));
          subscribeStepEvents.set(eventName, (0, SubscriptionManager_js_1.difference)(subscriptionNavigableIds, subscribedNavigableIds));
        }
        const subscription = this.#subscriptionManager.subscribe(eventNames, contextIds, userContextIds, googChannel);
        for (const eventName of subscription.eventNames) {
          for (const contextId of subscriptionNavigableIds) {
            for (const eventWrapper of this.#getBufferedEvents(eventName, contextId, googChannel)) {
              this.emit("event", {
                message: OutgoingMessage_js_1.OutgoingMessage.createFromPromise(eventWrapper.event, googChannel),
                event: eventName
              });
              this.#markEventSent(eventWrapper, googChannel, eventName);
            }
          }
        }
        for (const [eventName, contextIds2] of subscribeStepEvents) {
          for (const contextId of contextIds2) {
            this.#subscribeHooks.get(eventName).forEach((hook) => hook(contextId));
          }
        }
        await this.toggleModulesIfNeeded();
        return subscription.id;
      }
      async unsubscribe(eventNames, googChannel) {
        for (const name of eventNames) {
          (0, events_js_1.assertSupportedEvent)(name);
        }
        this.#subscriptionManager.unsubscribe(eventNames, googChannel);
        await this.toggleModulesIfNeeded();
      }
      async unsubscribeByIds(subscriptionIds) {
        this.#subscriptionManager.unsubscribeById(subscriptionIds);
        await this.toggleModulesIfNeeded();
      }
      async toggleModulesIfNeeded() {
        await Promise.all(this.#browsingContextStorage.getAllContexts().map(async (context) => {
          return await context.toggleModulesIfNeeded();
        }));
      }
      clearBufferedEvents(contextId) {
        for (const eventName of eventBufferLength.keys()) {
          const bufferMapKey = _a2.#getMapKey(eventName, contextId);
          this.#eventBuffers.delete(bufferMapKey);
        }
      }
      /**
       * If the event is buffer-able, put it in the buffer.
       */
      #bufferEvent(eventWrapper, eventName) {
        if (!eventBufferLength.has(eventName)) {
          return;
        }
        const bufferMapKey = _a2.#getMapKey(eventName, eventWrapper.contextId);
        if (!this.#eventBuffers.has(bufferMapKey)) {
          this.#eventBuffers.set(bufferMapKey, new Buffer_js_1.Buffer(eventBufferLength.get(eventName)));
        }
        this.#eventBuffers.get(bufferMapKey).add(eventWrapper);
        this.#eventToContextsMap.get(eventName).add(eventWrapper.contextId);
      }
      /**
       * If the event is buffer-able, mark it as sent to the given contextId and goog:channel.
       */
      #markEventSent(eventWrapper, googChannel, eventName) {
        if (!eventBufferLength.has(eventName)) {
          return;
        }
        const lastSentMapKey = _a2.#getMapKey(eventName, eventWrapper.contextId);
        const lastId = Math.max(this.#lastMessageSent.get(lastSentMapKey)?.get(googChannel) ?? 0, eventWrapper.id);
        const googChannelMap = this.#lastMessageSent.get(lastSentMapKey);
        if (googChannelMap) {
          googChannelMap.set(googChannel, lastId);
        } else {
          this.#lastMessageSent.set(lastSentMapKey, /* @__PURE__ */ new Map([[googChannel, lastId]]));
        }
      }
      /**
       * Returns events which are buffered and not yet sent to the given goog:channel events.
       */
      #getBufferedEvents(eventName, contextId, googChannel) {
        const bufferMapKey = _a2.#getMapKey(eventName, contextId);
        const lastSentMessageId = this.#lastMessageSent.get(bufferMapKey)?.get(googChannel) ?? -Infinity;
        const result = this.#eventBuffers.get(bufferMapKey)?.get().filter((wrapper) => wrapper.id > lastSentMessageId) ?? [];
        if (contextId === null) {
          Array.from(this.#eventToContextsMap.get(eventName).keys()).filter((_contextId) => (
            // Events without context are already in the result.
            _contextId !== null && // Events from deleted contexts should not be sent.
            this.#browsingContextStorage.hasContext(_contextId)
          )).map((_contextId) => this.#getBufferedEvents(eventName, _contextId, googChannel)).forEach((events) => result.push(...events));
        }
        return result.sort((e1, e2) => e1.id - e2.id);
      }
    };
    exports2.EventManager = EventManager;
    _a2 = EventManager;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/speculation/SpeculationProcessor.js
var require_SpeculationProcessor = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/modules/speculation/SpeculationProcessor.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SpeculationProcessor = void 0;
    var log_js_1 = require_log();
    var SpeculationProcessor = class {
      #eventManager;
      #logger;
      constructor(eventManager, logger) {
        this.#eventManager = eventManager;
        this.#logger = logger;
      }
      onCdpTargetCreated(cdpTarget) {
        cdpTarget.cdpClient.on("Preload.prefetchStatusUpdated", (event) => {
          let prefetchStatus;
          switch (event.status) {
            case "Running":
              prefetchStatus = "pending";
              break;
            case "Ready":
              prefetchStatus = "ready";
              break;
            case "Success":
              prefetchStatus = "success";
              break;
            case "Failure":
              prefetchStatus = "failure";
              break;
            default:
              this.#logger?.(log_js_1.LogType.debugWarn, `Unknown prefetch status: ${event.status}`);
              return;
          }
          this.#eventManager.registerEvent({
            type: "event",
            method: "speculation.prefetchStatusUpdated",
            params: {
              context: event.initiatingFrameId,
              url: event.prefetchUrl,
              status: prefetchStatus
            }
          }, cdpTarget.id);
        });
      }
    };
    exports2.SpeculationProcessor = SpeculationProcessor;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/BidiServer.js
var require_BidiServer = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/BidiServer.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiServer = void 0;
    var EventEmitter_js_1 = require_EventEmitter2();
    var log_js_1 = require_log();
    var ProcessingQueue_js_1 = require_ProcessingQueue();
    var CommandProcessor_js_1 = require_CommandProcessor();
    var BluetoothProcessor_js_1 = require_BluetoothProcessor();
    var ContextConfigStorage_js_1 = require_ContextConfigStorage();
    var UserContextStorage_js_1 = require_UserContextStorage();
    var CdpTargetManager_js_1 = require_CdpTargetManager();
    var BrowsingContextStorage_js_1 = require_BrowsingContextStorage();
    var NetworkStorage_js_1 = require_NetworkStorage();
    var PreloadScriptStorage_js_1 = require_PreloadScriptStorage();
    var RealmStorage_js_1 = require_RealmStorage();
    var EventManager_js_1 = require_EventManager();
    var SpeculationProcessor_js_1 = require_SpeculationProcessor();
    var BidiServer = class _BidiServer extends EventEmitter_js_1.EventEmitter {
      #messageQueue;
      #transport;
      #commandProcessor;
      #eventManager;
      #browsingContextStorage = new BrowsingContextStorage_js_1.BrowsingContextStorage();
      #realmStorage = new RealmStorage_js_1.RealmStorage();
      #preloadScriptStorage = new PreloadScriptStorage_js_1.PreloadScriptStorage();
      #bluetoothProcessor;
      #speculationProcessor;
      #logger;
      #handleIncomingMessage = (message) => {
        void this.#commandProcessor.processCommand(message).catch((error) => {
          this.#logger?.(log_js_1.LogType.debugError, error);
        });
      };
      #processOutgoingMessage = async (messageEntry) => {
        const message = messageEntry.message;
        if (messageEntry.googChannel !== null) {
          message["goog:channel"] = messageEntry.googChannel;
        }
        await this.#transport.sendMessage(message);
      };
      constructor(bidiTransport, cdpConnection, browserCdpClient, selfTargetId, defaultUserContextId, defaultUserAgent, parser2, logger) {
        super();
        this.#logger = logger;
        this.#messageQueue = new ProcessingQueue_js_1.ProcessingQueue(this.#processOutgoingMessage, this.#logger);
        this.#transport = bidiTransport;
        this.#transport.setOnMessage(this.#handleIncomingMessage);
        const contextConfigStorage = new ContextConfigStorage_js_1.ContextConfigStorage();
        const userContextStorage = new UserContextStorage_js_1.UserContextStorage(browserCdpClient);
        this.#eventManager = new EventManager_js_1.EventManager(this.#browsingContextStorage, userContextStorage);
        const networkStorage = new NetworkStorage_js_1.NetworkStorage(this.#eventManager, this.#browsingContextStorage, browserCdpClient, logger);
        this.#bluetoothProcessor = new BluetoothProcessor_js_1.BluetoothProcessor(this.#eventManager, this.#browsingContextStorage);
        this.#speculationProcessor = new SpeculationProcessor_js_1.SpeculationProcessor(this.#eventManager, this.#logger);
        this.#commandProcessor = new CommandProcessor_js_1.CommandProcessor(cdpConnection, browserCdpClient, this.#eventManager, this.#browsingContextStorage, this.#realmStorage, this.#preloadScriptStorage, networkStorage, contextConfigStorage, this.#bluetoothProcessor, userContextStorage, parser2, async (options) => {
          await browserCdpClient.sendCommand("Security.setIgnoreCertificateErrors", {
            ignore: options.acceptInsecureCerts ?? false
          });
          contextConfigStorage.updateGlobalConfig({
            acceptInsecureCerts: options.acceptInsecureCerts ?? false,
            userPromptHandler: options.unhandledPromptBehavior,
            prerenderingDisabled: options?.["goog:prerenderingDisabled"] ?? false,
            disableNetworkDurableMessages: options?.["goog:disableNetworkDurableMessages"]
          });
          new CdpTargetManager_js_1.CdpTargetManager(cdpConnection, browserCdpClient, selfTargetId, this.#eventManager, this.#browsingContextStorage, this.#realmStorage, networkStorage, contextConfigStorage, this.#bluetoothProcessor, this.#speculationProcessor, this.#preloadScriptStorage, defaultUserContextId, defaultUserAgent, logger);
          await browserCdpClient.sendCommand("Target.setDiscoverTargets", {
            discover: true
          });
          await browserCdpClient.sendCommand("Target.setAutoAttach", {
            autoAttach: true,
            waitForDebuggerOnStart: true,
            flatten: true,
            // Browser session should attach to tab instead of the page, so that
            // prerendering is not blocked.
            filter: [
              {
                type: "page",
                exclude: true
              },
              {}
            ]
          });
          await this.#topLevelContextsLoaded();
        }, this.#logger);
        this.#eventManager.on("event", ({ message, event }) => {
          this.emitOutgoingMessage(message, event);
        });
        this.#commandProcessor.on("response", ({ message, event }) => {
          this.emitOutgoingMessage(message, event);
        });
      }
      /**
       * Creates and starts BiDi Mapper instance.
       */
      static async createAndStart(bidiTransport, cdpConnection, browserCdpClient, selfTargetId, parser2, logger) {
        const [defaultUserContextId, version] = await Promise.all([
          this.#getDefaultUserContextId(browserCdpClient),
          // Fetch the default User Agent to be used in `CdpTarget`. This allows to avoid
          // round trips to the browser for every target override.
          browserCdpClient.sendCommand("Browser.getVersion"),
          // Required for `Browser.downloadWillBegin` events.
          browserCdpClient.sendCommand("Browser.setDownloadBehavior", {
            behavior: "default",
            eventsEnabled: true
          })
        ]);
        const server = new _BidiServer(bidiTransport, cdpConnection, browserCdpClient, selfTargetId, defaultUserContextId, version.userAgent, parser2, logger);
        return server;
      }
      static async #getDefaultUserContextId(browserCdpClient) {
        const [{ defaultBrowserContextId, browserContextIds }, { targetInfos }] = await Promise.all([
          browserCdpClient.sendCommand("Target.getBrowserContexts"),
          browserCdpClient.sendCommand("Target.getTargets")
        ]);
        if (defaultBrowserContextId) {
          return defaultBrowserContextId;
        }
        for (const info of targetInfos) {
          if (info.browserContextId && !browserContextIds.includes(info.browserContextId)) {
            return info.browserContextId;
          }
        }
        return "default";
      }
      /**
       * Sends BiDi message.
       */
      emitOutgoingMessage(messageEntry, event) {
        this.#messageQueue.add(messageEntry, event);
      }
      close() {
        this.#transport.close();
      }
      async #topLevelContextsLoaded() {
        await Promise.all(this.#browsingContextStorage.getTopLevelContexts().map((c) => c.lifecycleLoaded()));
      }
    };
    exports2.BidiServer = BidiServer;
  }
});

// node_modules/chromium-bidi/lib/cjs/bidiMapper/BidiMapper.js
var require_BidiMapper = __commonJS({
  "node_modules/chromium-bidi/lib/cjs/bidiMapper/BidiMapper.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OutgoingMessage = exports2.EventEmitter = exports2.BidiServer = void 0;
    var BidiServer_js_1 = require_BidiServer();
    Object.defineProperty(exports2, "BidiServer", { enumerable: true, get: function() {
      return BidiServer_js_1.BidiServer;
    } });
    var EventEmitter_js_1 = require_EventEmitter2();
    Object.defineProperty(exports2, "EventEmitter", { enumerable: true, get: function() {
      return EventEmitter_js_1.EventEmitter;
    } });
    var OutgoingMessage_js_1 = require_OutgoingMessage();
    Object.defineProperty(exports2, "OutgoingMessage", { enumerable: true, get: function() {
      return OutgoingMessage_js_1.OutgoingMessage;
    } });
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/CDPSession.js
var require_CDPSession2 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/CDPSession.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiCdpSession = void 0;
    var CDPSession_js_1 = require_CDPSession();
    var Errors_js_1 = require_Errors();
    var Deferred_js_1 = require_Deferred();
    var BidiCdpSession = class _BidiCdpSession extends CDPSession_js_1.CDPSession {
      static sessions = /* @__PURE__ */ new Map();
      #detached = false;
      #connection;
      #sessionId = Deferred_js_1.Deferred.create();
      frame;
      constructor(frame, sessionId) {
        super();
        this.frame = frame;
        if (!this.frame.page().browser().cdpSupported) {
          return;
        }
        const connection = this.frame.page().browser().connection;
        this.#connection = connection;
        if (sessionId) {
          this.#sessionId.resolve(sessionId);
          _BidiCdpSession.sessions.set(sessionId, this);
        } else {
          (async () => {
            try {
              const { result } = await connection.send("goog:cdp.getSession", {
                context: frame._id
              });
              this.#sessionId.resolve(result.session);
              _BidiCdpSession.sessions.set(result.session, this);
            } catch (error) {
              this.#sessionId.reject(error);
            }
          })();
        }
        _BidiCdpSession.sessions.set(this.#sessionId.value(), this);
      }
      connection() {
        return void 0;
      }
      get detached() {
        return this.#detached;
      }
      async send(method, params, options) {
        if (this.#connection === void 0) {
          throw new Errors_js_1.UnsupportedOperation("CDP support is required for this feature. The current browser does not support CDP.");
        }
        if (this.#detached) {
          throw new Errors_js_1.TargetCloseError(`Protocol error (${method}): Session closed. Most likely the page has been closed.`);
        }
        const session = await this.#sessionId.valueOrThrow();
        const { result } = await this.#connection.send("goog:cdp.sendCommand", {
          method,
          params,
          session
        }, options?.timeout);
        return result.result;
      }
      async detach() {
        if (this.#connection === void 0 || this.#connection.closed || this.#detached) {
          return;
        }
        try {
          await this.frame.client.send("Target.detachFromTarget", {
            sessionId: this.id()
          });
        } finally {
          this.onClose();
        }
      }
      /**
       * @internal
       */
      onClose = () => {
        _BidiCdpSession.sessions.delete(this.id());
        this.#detached = true;
      };
      id() {
        const value = this.#sessionId.value();
        return typeof value === "string" ? value : "";
      }
    };
    exports2.BidiCdpSession = BidiCdpSession;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Connection.js
var require_Connection2 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Connection.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiConnection = void 0;
    var CallbackRegistry_js_1 = require_CallbackRegistry();
    var Debug_js_1 = require_Debug();
    var Errors_js_1 = require_Errors();
    var EventEmitter_js_1 = require_EventEmitter();
    var util_js_1 = require_util();
    var CDPSession_js_1 = require_CDPSession2();
    var debugProtocolSend = (0, Debug_js_1.debug)("puppeteer:webDriverBiDi:SEND \u25BA");
    var debugProtocolReceive = (0, Debug_js_1.debug)("puppeteer:webDriverBiDi:RECV \u25C0");
    var BidiConnection = class extends EventEmitter_js_1.EventEmitter {
      #url;
      #transport;
      #delay;
      #timeout = 0;
      #closed = false;
      #callbacks;
      #emitters = [];
      constructor(url, transport, idGenerator, delay = 0, timeout) {
        super();
        this.#url = url;
        this.#delay = delay;
        this.#timeout = timeout ?? 18e4;
        this.#callbacks = new CallbackRegistry_js_1.CallbackRegistry(idGenerator);
        this.#transport = transport;
        this.#transport.onmessage = this.onMessage.bind(this);
        this.#transport.onclose = this.unbind.bind(this);
      }
      get closed() {
        return this.#closed;
      }
      get url() {
        return this.#url;
      }
      pipeTo(emitter) {
        this.#emitters.push(emitter);
      }
      #toWebDriverOnlyEvent(event) {
        for (const key in event) {
          if (key.startsWith("goog:")) {
            delete event[key];
          } else {
            if (typeof event[key] === "object" && event[key] !== null) {
              this.#toWebDriverOnlyEvent(event[key]);
            }
          }
        }
      }
      emit(type, event) {
        if (process.env["PUPPETEER_WEBDRIVER_BIDI_ONLY"] === "true") {
          this.#toWebDriverOnlyEvent(event);
        }
        for (const emitter of this.#emitters) {
          emitter.emit(type, event);
        }
        return super.emit(type, event);
      }
      send(method, params, timeout) {
        if (this.#closed) {
          return Promise.reject(new Errors_js_1.ConnectionClosedError("Connection closed."));
        }
        return this.#callbacks.create(method, timeout ?? this.#timeout, (id) => {
          const stringifiedMessage = JSON.stringify({
            id,
            method,
            params
          });
          debugProtocolSend(stringifiedMessage);
          this.#transport.send(stringifiedMessage);
        });
      }
      /**
       * @internal
       */
      async onMessage(message) {
        if (this.#delay) {
          await new Promise((f) => {
            return setTimeout(f, this.#delay);
          });
        }
        debugProtocolReceive(message);
        const object = JSON.parse(message);
        if ("type" in object) {
          switch (object.type) {
            case "success":
              this.#callbacks.resolve(object.id, object);
              return;
            case "error":
              if (object.id === null) {
                break;
              }
              this.#callbacks.reject(object.id, createProtocolError(object), `${object.error}: ${object.message}`);
              return;
            case "event":
              if (isCdpEvent(object)) {
                CDPSession_js_1.BidiCdpSession.sessions.get(object.params.session)?.emit(object.params.event, object.params.params);
                return;
              }
              this.emit(object.method, object.params);
              return;
          }
        }
        if ("id" in object) {
          this.#callbacks.reject(object.id, `Protocol Error. Message is not in BiDi protocol format: '${message}'`, object.message);
        }
        (0, util_js_1.debugError)(object);
      }
      /**
       * Unbinds the connection, but keeps the transport open. Useful when the transport will
       * be reused by other connection e.g. with different protocol.
       * @internal
       */
      unbind() {
        if (this.#closed) {
          return;
        }
        this.#closed = true;
        this.#transport.onmessage = () => {
        };
        this.#transport.onclose = () => {
        };
        this.#callbacks.clear();
      }
      /**
       * Unbinds the connection and closes the transport.
       */
      dispose() {
        this.unbind();
        this.#transport.close();
      }
      getPendingProtocolErrors() {
        return this.#callbacks.getPendingProtocolErrors();
      }
    };
    exports2.BidiConnection = BidiConnection;
    function createProtocolError(object) {
      let message = `${object.error} ${object.message}`;
      if (object.stacktrace) {
        message += ` ${object.stacktrace}`;
      }
      return message;
    }
    function isCdpEvent(event) {
      return event.method.startsWith("goog:cdp.");
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/BidiOverCdp.js
var require_BidiOverCdp = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/BidiOverCdp.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
      var ownKeys2 = function(o) {
        ownKeys2 = 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 ownKeys2(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]);
        }
        __setModuleDefault2(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.connectBidiOverCdp = connectBidiOverCdp;
    var BidiMapper = __importStar2(require_BidiMapper());
    var Debug_js_1 = require_Debug();
    var Errors_js_1 = require_Errors();
    var Connection_js_1 = require_Connection2();
    var bidiServerLogger = (prefix, ...args2) => {
      (0, Debug_js_1.debug)(`bidi:${prefix}`)(args2);
    };
    async function connectBidiOverCdp(cdp) {
      const transportBiDi = new NoOpTransport();
      const cdpConnectionAdapter = new CdpConnectionAdapter(cdp);
      const pptrTransport = {
        send(message) {
          transportBiDi.emitMessage(JSON.parse(message));
        },
        close() {
          bidiServer.close();
          cdpConnectionAdapter.close();
          cdp.dispose();
        },
        onmessage(_message) {
        }
      };
      transportBiDi.on("bidiResponse", (message) => {
        pptrTransport.onmessage(JSON.stringify(message));
      });
      const pptrBiDiConnection = new Connection_js_1.BidiConnection(cdp.url(), pptrTransport, cdp._idGenerator, cdp.delay, cdp.timeout);
      const bidiServer = await BidiMapper.BidiServer.createAndStart(
        transportBiDi,
        cdpConnectionAdapter,
        cdpConnectionAdapter.browserClient(),
        /* selfTargetId= */
        "",
        void 0,
        bidiServerLogger
      );
      return pptrBiDiConnection;
    }
    var CdpConnectionAdapter = class {
      #cdp;
      #adapters = /* @__PURE__ */ new Map();
      #browserCdpConnection;
      constructor(cdp) {
        this.#cdp = cdp;
        this.#browserCdpConnection = new CDPClientAdapter(cdp);
      }
      browserClient() {
        return this.#browserCdpConnection;
      }
      getCdpClient(id) {
        const session = this.#cdp.session(id);
        if (!session) {
          throw new Error(`Unknown CDP session with id ${id}`);
        }
        if (!this.#adapters.has(session)) {
          const adapter = new CDPClientAdapter(session, id, this.#browserCdpConnection);
          this.#adapters.set(session, adapter);
          return adapter;
        }
        return this.#adapters.get(session);
      }
      close() {
        this.#browserCdpConnection.close();
        for (const adapter of this.#adapters.values()) {
          adapter.close();
        }
      }
    };
    var CDPClientAdapter = class extends BidiMapper.EventEmitter {
      #closed = false;
      #client;
      sessionId = void 0;
      #browserClient;
      constructor(client2, sessionId, browserClient) {
        super();
        this.#client = client2;
        this.sessionId = sessionId;
        this.#browserClient = browserClient;
        this.#client.on("*", this.#forwardMessage);
      }
      browserClient() {
        return this.#browserClient;
      }
      #forwardMessage = (method, event) => {
        this.emit(method, event);
      };
      async sendCommand(method, ...params) {
        if (this.#closed) {
          return;
        }
        try {
          return await this.#client.send(method, ...params);
        } catch (err) {
          if (this.#closed) {
            return;
          }
          throw err;
        }
      }
      close() {
        this.#client.off("*", this.#forwardMessage);
        this.#closed = true;
      }
      isCloseError(error) {
        return error instanceof Errors_js_1.TargetCloseError;
      }
    };
    var NoOpTransport = class extends BidiMapper.EventEmitter {
      #onMessage = async (_m) => {
        return;
      };
      emitMessage(message) {
        void this.#onMessage(message);
      }
      setOnMessage(onMessage) {
        this.#onMessage = onMessage;
      }
      async sendMessage(message) {
        this.emit("bidiResponse", message);
      }
      close() {
        this.#onMessage = async (_m) => {
          return;
        };
      }
    };
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/BluetoothEmulation.js
var require_BluetoothEmulation2 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/BluetoothEmulation.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiBluetoothEmulation = void 0;
    var BidiBluetoothEmulation = class {
      #session;
      #contextId;
      constructor(contextId, session) {
        this.#contextId = contextId;
        this.#session = session;
      }
      async emulateAdapter(state, leSupported = true) {
        await this.#session.send("bluetooth.simulateAdapter", {
          context: this.#contextId,
          state,
          leSupported
        });
      }
      async disableEmulation() {
        await this.#session.send("bluetooth.disableSimulation", {
          context: this.#contextId
        });
      }
      async simulatePreconnectedPeripheral(preconnectedPeripheral) {
        await this.#session.send("bluetooth.simulatePreconnectedPeripheral", {
          context: this.#contextId,
          address: preconnectedPeripheral.address,
          name: preconnectedPeripheral.name,
          manufacturerData: preconnectedPeripheral.manufacturerData,
          knownServiceUuids: preconnectedPeripheral.knownServiceUuids
        });
      }
    };
    exports2.BidiBluetoothEmulation = BidiBluetoothEmulation;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/DeviceRequestPrompt.js
var require_DeviceRequestPrompt3 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/DeviceRequestPrompt.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiDeviceRequestPrompt = exports2.BidiDeviceRequestPromptManager = void 0;
    var DeviceRequestPrompt_js_1 = require_DeviceRequestPrompt();
    var Errors_js_1 = require_Errors();
    var Deferred_js_1 = require_Deferred();
    var BidiDeviceRequestPromptManager = class {
      #session;
      #contextId;
      #enabled = false;
      constructor(contextId, session) {
        this.#session = session;
        this.#contextId = contextId;
      }
      async #enableIfNeeded() {
        if (!this.#enabled) {
          this.#enabled = true;
          await this.#session.subscribe(["bluetooth.requestDevicePromptUpdated"], [this.#contextId]);
        }
      }
      async waitForDevicePrompt(timeout, signal) {
        const deferred = Deferred_js_1.Deferred.create({
          message: `Waiting for \`DeviceRequestPrompt\` failed: ${timeout}ms exceeded`,
          timeout
        });
        const onRequestDevicePromptUpdated = (params) => {
          if (params.context === this.#contextId) {
            deferred.resolve(new BidiDeviceRequestPrompt(this.#contextId, params.prompt, this.#session, params.devices));
            this.#session.off("bluetooth.requestDevicePromptUpdated", onRequestDevicePromptUpdated);
          }
        };
        this.#session.on("bluetooth.requestDevicePromptUpdated", onRequestDevicePromptUpdated);
        if (signal) {
          signal.addEventListener("abort", () => {
            deferred.reject(signal.reason);
          }, { once: true });
        }
        await this.#enableIfNeeded();
        return await deferred.valueOrThrow();
      }
    };
    exports2.BidiDeviceRequestPromptManager = BidiDeviceRequestPromptManager;
    var BidiDeviceRequestPrompt = class extends DeviceRequestPrompt_js_1.DeviceRequestPrompt {
      #session;
      #promptId;
      #contextId;
      constructor(contextId, promptId, session, devices) {
        super();
        this.#session = session;
        this.#promptId = promptId;
        this.#contextId = contextId;
        this.devices.push(...devices.map((d) => {
          return {
            id: d.id,
            name: d.name ?? "UNKNOWN"
          };
        }));
      }
      async cancel() {
        await this.#session.send("bluetooth.handleRequestDevicePrompt", {
          context: this.#contextId,
          prompt: this.#promptId,
          accept: false
        });
      }
      async select(device) {
        await this.#session.send("bluetooth.handleRequestDevicePrompt", {
          context: this.#contextId,
          prompt: this.#promptId,
          accept: true,
          device: device.id
        });
      }
      waitForDevice() {
        throw new Errors_js_1.UnsupportedOperation();
      }
    };
    exports2.BidiDeviceRequestPrompt = BidiDeviceRequestPrompt;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/core/Navigation.js
var require_Navigation = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/core/Navigation.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Navigation = void 0;
    var EventEmitter_js_1 = require_EventEmitter();
    var decorators_js_1 = require_decorators();
    var disposable_js_1 = require_disposable();
    var Navigation = (() => {
      var _a2;
      let _classSuper = EventEmitter_js_1.EventEmitter;
      let _instanceExtraInitializers = [];
      let _dispose_decorators;
      return class Navigation2 extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          __esDecorate2(this, null, _dispose_decorators, { kind: "method", name: "dispose", static: false, private: false, access: { has: (obj) => "dispose" in obj, get: (obj) => obj.dispose }, metadata: _metadata }, null, _instanceExtraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        static from(context) {
          const navigation = new Navigation2(context);
          navigation.#initialize();
          return navigation;
        }
        #request = __runInitializers2(this, _instanceExtraInitializers);
        #navigation;
        #browsingContext;
        #disposables = new disposable_js_1.DisposableStack();
        #id;
        constructor(context) {
          super();
          this.#browsingContext = context;
        }
        #initialize() {
          const browsingContextEmitter = this.#disposables.use(new EventEmitter_js_1.EventEmitter(this.#browsingContext));
          browsingContextEmitter.once("closed", () => {
            this.emit("failed", {
              url: this.#browsingContext.url,
              timestamp: /* @__PURE__ */ new Date()
            });
            this.dispose();
          });
          browsingContextEmitter.on("request", ({ request }) => {
            if (request.navigation === void 0 || // If a request with a navigation ID comes in, then the navigation ID is
            // for this navigation.
            !this.#matches(request.navigation)) {
              return;
            }
            this.#request = request;
            this.emit("request", request);
            const requestEmitter = this.#disposables.use(new EventEmitter_js_1.EventEmitter(this.#request));
            requestEmitter.on("redirect", (request2) => {
              this.#request = request2;
            });
          });
          const sessionEmitter = this.#disposables.use(new EventEmitter_js_1.EventEmitter(this.#session));
          sessionEmitter.on("browsingContext.navigationStarted", (info) => {
            if (info.context !== this.#browsingContext.id || this.#navigation !== void 0) {
              return;
            }
            this.#navigation = Navigation2.from(this.#browsingContext);
          });
          for (const eventName of [
            "browsingContext.domContentLoaded",
            "browsingContext.load",
            "browsingContext.navigationCommitted"
          ]) {
            sessionEmitter.on(eventName, (info) => {
              if (info.context !== this.#browsingContext.id || info.navigation === null || !this.#matches(info.navigation)) {
                return;
              }
              this.dispose();
            });
          }
          for (const [eventName, event] of [
            ["browsingContext.fragmentNavigated", "fragment"],
            ["browsingContext.navigationFailed", "failed"],
            ["browsingContext.navigationAborted", "aborted"]
          ]) {
            sessionEmitter.on(eventName, (info) => {
              if (info.context !== this.#browsingContext.id || // Note we don't check if `navigation` is null since `null` means the
              // fragment navigated.
              !this.#matches(info.navigation)) {
                return;
              }
              this.emit(event, {
                url: info.url,
                timestamp: new Date(info.timestamp)
              });
              this.dispose();
            });
          }
        }
        #matches(navigation) {
          if (this.#navigation !== void 0 && !this.#navigation.disposed) {
            return false;
          }
          if (this.#id === void 0) {
            this.#id = navigation;
            return true;
          }
          return this.#id === navigation;
        }
        get #session() {
          return this.#browsingContext.userContext.browser.session;
        }
        get disposed() {
          return this.#disposables.disposed;
        }
        get request() {
          return this.#request;
        }
        get navigation() {
          return this.#navigation;
        }
        dispose() {
          this[disposable_js_1.disposeSymbol]();
        }
        [(_dispose_decorators = [decorators_js_1.inertIfDisposed], disposable_js_1.disposeSymbol)]() {
          this.#disposables.dispose();
          super[disposable_js_1.disposeSymbol]();
        }
      };
    })();
    exports2.Navigation = Navigation;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/core/Realm.js
var require_Realm3 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/core/Realm.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    var _a2;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SharedWorkerRealm = exports2.DedicatedWorkerRealm = exports2.WindowRealm = exports2.Realm = void 0;
    var EventEmitter_js_1 = require_EventEmitter();
    var decorators_js_1 = require_decorators();
    var disposable_js_1 = require_disposable();
    var Realm = (() => {
      let _classSuper = EventEmitter_js_1.EventEmitter;
      let _instanceExtraInitializers = [];
      let _dispose_decorators;
      let _disown_decorators;
      let _callFunction_decorators;
      let _evaluate_decorators;
      let _resolveExecutionContextId_decorators;
      return class Realm extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          __esDecorate2(this, null, _dispose_decorators, { kind: "method", name: "dispose", static: false, private: false, access: { has: (obj) => "dispose" in obj, get: (obj) => obj.dispose }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _disown_decorators, { kind: "method", name: "disown", static: false, private: false, access: { has: (obj) => "disown" in obj, get: (obj) => obj.disown }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _callFunction_decorators, { kind: "method", name: "callFunction", static: false, private: false, access: { has: (obj) => "callFunction" in obj, get: (obj) => obj.callFunction }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _evaluate_decorators, { kind: "method", name: "evaluate", static: false, private: false, access: { has: (obj) => "evaluate" in obj, get: (obj) => obj.evaluate }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _resolveExecutionContextId_decorators, { kind: "method", name: "resolveExecutionContextId", static: false, private: false, access: { has: (obj) => "resolveExecutionContextId" in obj, get: (obj) => obj.resolveExecutionContextId }, metadata: _metadata }, null, _instanceExtraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #reason = __runInitializers2(this, _instanceExtraInitializers);
        disposables = new disposable_js_1.DisposableStack();
        id;
        origin;
        executionContextId;
        constructor(id, origin) {
          super();
          this.id = id;
          this.origin = origin;
        }
        get disposed() {
          return this.#reason !== void 0;
        }
        get target() {
          return { realm: this.id };
        }
        dispose(reason) {
          this.#reason = reason;
          this[disposable_js_1.disposeSymbol]();
        }
        async disown(handles) {
          await this.session.send("script.disown", {
            target: this.target,
            handles
          });
        }
        async callFunction(functionDeclaration, awaitPromise, options = {}) {
          const { result } = await this.session.send("script.callFunction", {
            functionDeclaration,
            awaitPromise,
            target: this.target,
            ...options
          });
          return result;
        }
        async evaluate(expression, awaitPromise, options = {}) {
          const { result } = await this.session.send("script.evaluate", {
            expression,
            awaitPromise,
            target: this.target,
            ...options
          });
          return result;
        }
        async resolveExecutionContextId() {
          if (!this.executionContextId) {
            const { result } = await this.session.connection.send("goog:cdp.resolveRealm", { realm: this.id });
            this.executionContextId = result.executionContextId;
          }
          return this.executionContextId;
        }
        [(_dispose_decorators = [decorators_js_1.inertIfDisposed], _disown_decorators = [(0, decorators_js_1.throwIfDisposed)((realm) => {
          return realm.#reason;
        })], _callFunction_decorators = [(0, decorators_js_1.throwIfDisposed)((realm) => {
          return realm.#reason;
        })], _evaluate_decorators = [(0, decorators_js_1.throwIfDisposed)((realm) => {
          return realm.#reason;
        })], _resolveExecutionContextId_decorators = [(0, decorators_js_1.throwIfDisposed)((realm) => {
          return realm.#reason;
        })], disposable_js_1.disposeSymbol)]() {
          this.#reason ??= "Realm already destroyed, probably because all associated browsing contexts closed.";
          this.emit("destroyed", { reason: this.#reason });
          this.disposables.dispose();
          super[disposable_js_1.disposeSymbol]();
        }
      };
    })();
    exports2.Realm = Realm;
    var WindowRealm = class _WindowRealm extends Realm {
      static from(context, sandbox) {
        const realm = new _WindowRealm(context, sandbox);
        realm.#initialize();
        return realm;
      }
      browsingContext;
      sandbox;
      #workers = /* @__PURE__ */ new Map();
      constructor(context, sandbox) {
        super("", "");
        this.browsingContext = context;
        this.sandbox = sandbox;
      }
      #initialize() {
        const browsingContextEmitter = this.disposables.use(new EventEmitter_js_1.EventEmitter(this.browsingContext));
        browsingContextEmitter.on("closed", ({ reason }) => {
          this.dispose(reason);
        });
        const sessionEmitter = this.disposables.use(new EventEmitter_js_1.EventEmitter(this.session));
        sessionEmitter.on("script.realmCreated", (info) => {
          if (info.type !== "window" || info.context !== this.browsingContext.id || info.sandbox !== this.sandbox) {
            return;
          }
          this.id = info.realm;
          this.origin = info.origin;
          this.executionContextId = void 0;
          this.emit("updated", this);
        });
        sessionEmitter.on("script.realmCreated", (info) => {
          if (info.type !== "dedicated-worker") {
            return;
          }
          if (!info.owners.includes(this.id)) {
            return;
          }
          const realm = DedicatedWorkerRealm.from(this, info.realm, info.origin);
          this.#workers.set(realm.id, realm);
          const realmEmitter = this.disposables.use(new EventEmitter_js_1.EventEmitter(realm));
          realmEmitter.once("destroyed", () => {
            realmEmitter.removeAllListeners();
            this.#workers.delete(realm.id);
          });
          this.emit("worker", realm);
        });
      }
      get session() {
        return this.browsingContext.userContext.browser.session;
      }
      get target() {
        return { context: this.browsingContext.id, sandbox: this.sandbox };
      }
    };
    exports2.WindowRealm = WindowRealm;
    var DedicatedWorkerRealm = class extends Realm {
      static from(owner, id, origin) {
        const realm = new _a2(owner, id, origin);
        realm.#initialize();
        return realm;
      }
      #workers = /* @__PURE__ */ new Map();
      owners;
      constructor(owner, id, origin) {
        super(id, origin);
        this.owners = /* @__PURE__ */ new Set([owner]);
      }
      #initialize() {
        const sessionEmitter = this.disposables.use(new EventEmitter_js_1.EventEmitter(this.session));
        sessionEmitter.on("script.realmDestroyed", (info) => {
          if (info.realm !== this.id) {
            return;
          }
          this.dispose("Realm already destroyed.");
        });
        sessionEmitter.on("script.realmCreated", (info) => {
          if (info.type !== "dedicated-worker") {
            return;
          }
          if (!info.owners.includes(this.id)) {
            return;
          }
          const realm = _a2.from(this, info.realm, info.origin);
          this.#workers.set(realm.id, realm);
          const realmEmitter = this.disposables.use(new EventEmitter_js_1.EventEmitter(realm));
          realmEmitter.once("destroyed", () => {
            this.#workers.delete(realm.id);
          });
          this.emit("worker", realm);
        });
      }
      get session() {
        return this.owners.values().next().value.session;
      }
    };
    exports2.DedicatedWorkerRealm = DedicatedWorkerRealm;
    _a2 = DedicatedWorkerRealm;
    var SharedWorkerRealm = class _SharedWorkerRealm extends Realm {
      static from(browser, id, origin) {
        const realm = new _SharedWorkerRealm(browser, id, origin);
        realm.#initialize();
        return realm;
      }
      #workers = /* @__PURE__ */ new Map();
      browser;
      constructor(browser, id, origin) {
        super(id, origin);
        this.browser = browser;
      }
      #initialize() {
        const sessionEmitter = this.disposables.use(new EventEmitter_js_1.EventEmitter(this.session));
        sessionEmitter.on("script.realmDestroyed", (info) => {
          if (info.realm !== this.id) {
            return;
          }
          this.dispose("Realm already destroyed.");
        });
        sessionEmitter.on("script.realmCreated", (info) => {
          if (info.type !== "dedicated-worker") {
            return;
          }
          if (!info.owners.includes(this.id)) {
            return;
          }
          const realm = DedicatedWorkerRealm.from(this, info.realm, info.origin);
          this.#workers.set(realm.id, realm);
          const realmEmitter = this.disposables.use(new EventEmitter_js_1.EventEmitter(realm));
          realmEmitter.once("destroyed", () => {
            this.#workers.delete(realm.id);
          });
          this.emit("worker", realm);
        });
      }
      get session() {
        return this.browser.session;
      }
    };
    exports2.SharedWorkerRealm = SharedWorkerRealm;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/core/Request.js
var require_Request = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/core/Request.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Request = void 0;
    var Errors_js_1 = require_Errors();
    var EventEmitter_js_1 = require_EventEmitter();
    var decorators_js_1 = require_decorators();
    var disposable_js_1 = require_disposable();
    var encoding_js_1 = require_encoding();
    var Request = (() => {
      var _a2;
      let _classSuper = EventEmitter_js_1.EventEmitter;
      let _instanceExtraInitializers = [];
      let _dispose_decorators;
      return class Request2 extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          __esDecorate2(this, null, _dispose_decorators, { kind: "method", name: "dispose", static: false, private: false, access: { has: (obj) => "dispose" in obj, get: (obj) => obj.dispose }, metadata: _metadata }, null, _instanceExtraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        static from(browsingContext, event) {
          const request = new Request2(browsingContext, event);
          request.#initialize();
          return request;
        }
        #responseContentPromise = (__runInitializers2(this, _instanceExtraInitializers), null);
        #requestBodyPromise = null;
        #error;
        #redirect;
        #response;
        #browsingContext;
        #disposables = new disposable_js_1.DisposableStack();
        #event;
        constructor(browsingContext, event) {
          super();
          this.#browsingContext = browsingContext;
          this.#event = event;
        }
        #initialize() {
          const browsingContextEmitter = this.#disposables.use(new EventEmitter_js_1.EventEmitter(this.#browsingContext));
          browsingContextEmitter.once("closed", ({ reason }) => {
            this.#error = reason;
            this.emit("error", this.#error);
            this.dispose();
          });
          const sessionEmitter = this.#disposables.use(new EventEmitter_js_1.EventEmitter(this.#session));
          sessionEmitter.on("network.beforeRequestSent", (event) => {
            if (event.context !== this.#browsingContext.id || event.request.request !== this.id) {
              return;
            }
            const previousRequestHasAuth = this.#event.request.headers.find((header) => {
              return header.name.toLowerCase() === "authorization";
            });
            const newRequestHasAuth = event.request.headers.find((header) => {
              return header.name.toLowerCase() === "authorization";
            });
            const isAfterAuth = newRequestHasAuth && !previousRequestHasAuth;
            if (event.redirectCount !== this.#event.redirectCount + 1 && !isAfterAuth) {
              return;
            }
            this.#redirect = Request2.from(this.#browsingContext, event);
            this.emit("redirect", this.#redirect);
            this.dispose();
          });
          sessionEmitter.on("network.authRequired", (event) => {
            if (event.context !== this.#browsingContext.id || event.request.request !== this.id || // Don't try to authenticate for events that are not blocked
            !event.isBlocked) {
              return;
            }
            this.emit("authenticate", void 0);
          });
          sessionEmitter.on("network.fetchError", (event) => {
            if (event.context !== this.#browsingContext.id || event.request.request !== this.id || this.#event.redirectCount !== event.redirectCount) {
              return;
            }
            this.#error = event.errorText;
            this.emit("error", this.#error);
            this.dispose();
          });
          sessionEmitter.on("network.responseStarted", (event) => {
            if (event.context !== this.#browsingContext.id || event.request.request !== this.id || this.#event.redirectCount !== event.redirectCount) {
              return;
            }
            this.#response = event.response;
            this.#event.request.timings = event.request.timings;
            this.emit("response", this.#response);
          });
          sessionEmitter.on("network.responseCompleted", (event) => {
            if (event.context !== this.#browsingContext.id || event.request.request !== this.id || this.#event.redirectCount !== event.redirectCount) {
              return;
            }
            this.#response = event.response;
            this.#event.request.timings = event.request.timings;
            this.emit("success", this.#response);
            if (this.#response.status >= 300 && this.#response.status < 400) {
              return;
            }
            this.dispose();
          });
        }
        get #session() {
          return this.#browsingContext.userContext.browser.session;
        }
        get disposed() {
          return this.#disposables.disposed;
        }
        get error() {
          return this.#error;
        }
        get headers() {
          return this.#event.request.headers;
        }
        get id() {
          return this.#event.request.request;
        }
        get initiator() {
          return {
            ...this.#event.initiator,
            // Initiator URL is not specified in BiDi.
            // @ts-expect-error non-standard property.
            url: this.#event.request["goog:resourceInitiator"]?.url,
            // @ts-expect-error non-standard property.
            stack: this.#event.request["goog:resourceInitiator"]?.stack
          };
        }
        get method() {
          return this.#event.request.method;
        }
        get navigation() {
          return this.#event.navigation ?? void 0;
        }
        get redirect() {
          return this.#redirect;
        }
        get lastRedirect() {
          let redirect = this.#redirect;
          while (redirect) {
            if (redirect && !redirect.#redirect) {
              return redirect;
            }
            redirect = redirect.#redirect;
          }
          return redirect;
        }
        get response() {
          return this.#response;
        }
        get url() {
          return this.#event.request.url;
        }
        get isBlocked() {
          return this.#event.isBlocked;
        }
        get resourceType() {
          return this.#event.request["goog:resourceType"] ?? void 0;
        }
        get postData() {
          return this.#event.request["goog:postData"] ?? void 0;
        }
        get hasPostData() {
          return (this.#event.request.bodySize ?? 0) > 0;
        }
        async continueRequest({ url, method, headers, cookies, body }) {
          await this.#session.send("network.continueRequest", {
            request: this.id,
            url,
            method,
            headers,
            body,
            cookies
          });
        }
        async failRequest() {
          await this.#session.send("network.failRequest", {
            request: this.id
          });
        }
        async provideResponse({ statusCode, reasonPhrase, headers, body }) {
          await this.#session.send("network.provideResponse", {
            request: this.id,
            statusCode,
            reasonPhrase,
            headers,
            body
          });
        }
        async fetchPostData() {
          if (!this.hasPostData) {
            return void 0;
          }
          if (!this.#requestBodyPromise) {
            this.#requestBodyPromise = (async () => {
              const data = await this.#session.send("network.getData", {
                dataType: "request",
                request: this.id
              });
              if (data.result.bytes.type === "string") {
                return data.result.bytes.value;
              }
              throw new Errors_js_1.UnsupportedOperation(`Collected request body data of type ${data.result.bytes.type} is not supported`);
            })();
          }
          return await this.#requestBodyPromise;
        }
        async getResponseContent() {
          if (!this.#responseContentPromise) {
            this.#responseContentPromise = (async () => {
              try {
                const data = await this.#session.send("network.getData", {
                  dataType: "response",
                  request: this.id
                });
                return (0, encoding_js_1.stringToTypedArray)(data.result.bytes.value, data.result.bytes.type === "base64");
              } catch (error) {
                if (error instanceof Errors_js_1.ProtocolError && error.originalMessage.includes("No resource with given identifier found")) {
                  throw new Errors_js_1.ProtocolError("Could not load response body for this request. This might happen if the request is a preflight request.");
                }
                throw error;
              }
            })();
          }
          return await this.#responseContentPromise;
        }
        async continueWithAuth(parameters) {
          if (parameters.action === "provideCredentials") {
            await this.#session.send("network.continueWithAuth", {
              request: this.id,
              action: parameters.action,
              credentials: parameters.credentials
            });
          } else {
            await this.#session.send("network.continueWithAuth", {
              request: this.id,
              action: parameters.action
            });
          }
        }
        dispose() {
          this[disposable_js_1.disposeSymbol]();
        }
        [(_dispose_decorators = [decorators_js_1.inertIfDisposed], disposable_js_1.disposeSymbol)]() {
          this.#disposables.dispose();
          super[disposable_js_1.disposeSymbol]();
        }
        timing() {
          return this.#event.request.timings;
        }
      };
    })();
    exports2.Request = Request;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/core/UserPrompt.js
var require_UserPrompt = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/core/UserPrompt.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.UserPrompt = void 0;
    var EventEmitter_js_1 = require_EventEmitter();
    var decorators_js_1 = require_decorators();
    var disposable_js_1 = require_disposable();
    var UserPrompt = (() => {
      let _classSuper = EventEmitter_js_1.EventEmitter;
      let _instanceExtraInitializers = [];
      let _dispose_decorators;
      let _handle_decorators;
      return class UserPrompt2 extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          __esDecorate2(this, null, _dispose_decorators, { kind: "method", name: "dispose", static: false, private: false, access: { has: (obj) => "dispose" in obj, get: (obj) => obj.dispose }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _handle_decorators, { kind: "method", name: "handle", static: false, private: false, access: { has: (obj) => "handle" in obj, get: (obj) => obj.handle }, metadata: _metadata }, null, _instanceExtraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        static from(browsingContext, info) {
          const userPrompt = new UserPrompt2(browsingContext, info);
          userPrompt.#initialize();
          return userPrompt;
        }
        #reason = __runInitializers2(this, _instanceExtraInitializers);
        #result;
        #disposables = new disposable_js_1.DisposableStack();
        browsingContext;
        info;
        constructor(context, info) {
          super();
          this.browsingContext = context;
          this.info = info;
        }
        #initialize() {
          const browserContextEmitter = this.#disposables.use(new EventEmitter_js_1.EventEmitter(this.browsingContext));
          browserContextEmitter.once("closed", ({ reason }) => {
            this.dispose(`User prompt already closed: ${reason}`);
          });
          const sessionEmitter = this.#disposables.use(new EventEmitter_js_1.EventEmitter(this.#session));
          sessionEmitter.on("browsingContext.userPromptClosed", (parameters) => {
            if (parameters.context !== this.browsingContext.id) {
              return;
            }
            this.#result = parameters;
            this.emit("handled", parameters);
            this.dispose("User prompt already handled.");
          });
        }
        get #session() {
          return this.browsingContext.userContext.browser.session;
        }
        get closed() {
          return this.#reason !== void 0;
        }
        get disposed() {
          return this.closed;
        }
        get handled() {
          if (this.info.handler === "accept" || this.info.handler === "dismiss") {
            return true;
          }
          return this.#result !== void 0;
        }
        get result() {
          return this.#result;
        }
        dispose(reason) {
          this.#reason = reason;
          this[disposable_js_1.disposeSymbol]();
        }
        async handle(options = {}) {
          await this.#session.send("browsingContext.handleUserPrompt", {
            ...options,
            context: this.info.context
          });
          return this.#result;
        }
        [(_dispose_decorators = [decorators_js_1.inertIfDisposed], _handle_decorators = [(0, decorators_js_1.throwIfDisposed)((prompt) => {
          return prompt.#reason;
        })], disposable_js_1.disposeSymbol)]() {
          this.#reason ??= "User prompt already closed, probably because the associated browsing context was destroyed.";
          this.emit("closed", { reason: this.#reason });
          this.#disposables.dispose();
          super[disposable_js_1.disposeSymbol]();
        }
      };
    })();
    exports2.UserPrompt = UserPrompt;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/core/BrowsingContext.js
var require_BrowsingContext = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/core/BrowsingContext.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BrowsingContext = void 0;
    var EventEmitter_js_1 = require_EventEmitter();
    var util_js_1 = require_util();
    var assert_js_1 = require_assert();
    var decorators_js_1 = require_decorators();
    var disposable_js_1 = require_disposable();
    var BluetoothEmulation_js_1 = require_BluetoothEmulation2();
    var DeviceRequestPrompt_js_1 = require_DeviceRequestPrompt3();
    var Navigation_js_1 = require_Navigation();
    var Realm_js_1 = require_Realm3();
    var Request_js_1 = require_Request();
    var UserPrompt_js_1 = require_UserPrompt();
    var BrowsingContext = (() => {
      var _a2;
      let _classSuper = EventEmitter_js_1.EventEmitter;
      let _instanceExtraInitializers = [];
      let _dispose_decorators;
      let _activate_decorators;
      let _captureScreenshot_decorators;
      let _close_decorators;
      let _traverseHistory_decorators;
      let _navigate_decorators;
      let _reload_decorators;
      let _setCacheBehavior_decorators;
      let _print_decorators;
      let _handleUserPrompt_decorators;
      let _setViewport_decorators;
      let _setTouchOverride_decorators;
      let _performActions_decorators;
      let _releaseActions_decorators;
      let _createWindowRealm_decorators;
      let _addPreloadScript_decorators;
      let _addIntercept_decorators;
      let _removePreloadScript_decorators;
      let _setGeolocationOverride_decorators;
      let _setTimezoneOverride_decorators;
      let _setScreenOrientationOverride_decorators;
      let _getCookies_decorators;
      let _setCookie_decorators;
      let _setFiles_decorators;
      let _subscribe_decorators;
      let _addInterception_decorators;
      let _deleteCookie_decorators;
      let _locateNodes_decorators;
      return class BrowsingContext2 extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          _deleteCookie_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
            return context.#reason;
          })];
          _locateNodes_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
            return context.#reason;
          })];
          __esDecorate2(this, null, _dispose_decorators, { kind: "method", name: "dispose", static: false, private: false, access: { has: (obj) => "dispose" in obj, get: (obj) => obj.dispose }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _activate_decorators, { kind: "method", name: "activate", static: false, private: false, access: { has: (obj) => "activate" in obj, get: (obj) => obj.activate }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _captureScreenshot_decorators, { kind: "method", name: "captureScreenshot", static: false, private: false, access: { has: (obj) => "captureScreenshot" in obj, get: (obj) => obj.captureScreenshot }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _close_decorators, { kind: "method", name: "close", static: false, private: false, access: { has: (obj) => "close" in obj, get: (obj) => obj.close }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _traverseHistory_decorators, { kind: "method", name: "traverseHistory", static: false, private: false, access: { has: (obj) => "traverseHistory" in obj, get: (obj) => obj.traverseHistory }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _navigate_decorators, { kind: "method", name: "navigate", static: false, private: false, access: { has: (obj) => "navigate" in obj, get: (obj) => obj.navigate }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _reload_decorators, { kind: "method", name: "reload", static: false, private: false, access: { has: (obj) => "reload" in obj, get: (obj) => obj.reload }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _setCacheBehavior_decorators, { kind: "method", name: "setCacheBehavior", static: false, private: false, access: { has: (obj) => "setCacheBehavior" in obj, get: (obj) => obj.setCacheBehavior }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _print_decorators, { kind: "method", name: "print", static: false, private: false, access: { has: (obj) => "print" in obj, get: (obj) => obj.print }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _handleUserPrompt_decorators, { kind: "method", name: "handleUserPrompt", static: false, private: false, access: { has: (obj) => "handleUserPrompt" in obj, get: (obj) => obj.handleUserPrompt }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _setViewport_decorators, { kind: "method", name: "setViewport", static: false, private: false, access: { has: (obj) => "setViewport" in obj, get: (obj) => obj.setViewport }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _setTouchOverride_decorators, { kind: "method", name: "setTouchOverride", static: false, private: false, access: { has: (obj) => "setTouchOverride" in obj, get: (obj) => obj.setTouchOverride }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _performActions_decorators, { kind: "method", name: "performActions", static: false, private: false, access: { has: (obj) => "performActions" in obj, get: (obj) => obj.performActions }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _releaseActions_decorators, { kind: "method", name: "releaseActions", static: false, private: false, access: { has: (obj) => "releaseActions" in obj, get: (obj) => obj.releaseActions }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _createWindowRealm_decorators, { kind: "method", name: "createWindowRealm", static: false, private: false, access: { has: (obj) => "createWindowRealm" in obj, get: (obj) => obj.createWindowRealm }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _addPreloadScript_decorators, { kind: "method", name: "addPreloadScript", static: false, private: false, access: { has: (obj) => "addPreloadScript" in obj, get: (obj) => obj.addPreloadScript }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _addIntercept_decorators, { kind: "method", name: "addIntercept", static: false, private: false, access: { has: (obj) => "addIntercept" in obj, get: (obj) => obj.addIntercept }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _removePreloadScript_decorators, { kind: "method", name: "removePreloadScript", static: false, private: false, access: { has: (obj) => "removePreloadScript" in obj, get: (obj) => obj.removePreloadScript }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _setGeolocationOverride_decorators, { kind: "method", name: "setGeolocationOverride", static: false, private: false, access: { has: (obj) => "setGeolocationOverride" in obj, get: (obj) => obj.setGeolocationOverride }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _setTimezoneOverride_decorators, { kind: "method", name: "setTimezoneOverride", static: false, private: false, access: { has: (obj) => "setTimezoneOverride" in obj, get: (obj) => obj.setTimezoneOverride }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _setScreenOrientationOverride_decorators, { kind: "method", name: "setScreenOrientationOverride", static: false, private: false, access: { has: (obj) => "setScreenOrientationOverride" in obj, get: (obj) => obj.setScreenOrientationOverride }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _getCookies_decorators, { kind: "method", name: "getCookies", static: false, private: false, access: { has: (obj) => "getCookies" in obj, get: (obj) => obj.getCookies }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _setCookie_decorators, { kind: "method", name: "setCookie", static: false, private: false, access: { has: (obj) => "setCookie" in obj, get: (obj) => obj.setCookie }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _setFiles_decorators, { kind: "method", name: "setFiles", static: false, private: false, access: { has: (obj) => "setFiles" in obj, get: (obj) => obj.setFiles }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _subscribe_decorators, { kind: "method", name: "subscribe", static: false, private: false, access: { has: (obj) => "subscribe" in obj, get: (obj) => obj.subscribe }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _addInterception_decorators, { kind: "method", name: "addInterception", static: false, private: false, access: { has: (obj) => "addInterception" in obj, get: (obj) => obj.addInterception }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _deleteCookie_decorators, { kind: "method", name: "deleteCookie", static: false, private: false, access: { has: (obj) => "deleteCookie" in obj, get: (obj) => obj.deleteCookie }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _locateNodes_decorators, { kind: "method", name: "locateNodes", static: false, private: false, access: { has: (obj) => "locateNodes" in obj, get: (obj) => obj.locateNodes }, metadata: _metadata }, null, _instanceExtraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        static from(userContext, parent, id, url, originalOpener, clientWindow) {
          const browsingContext = new BrowsingContext2(userContext, parent, id, url, originalOpener, clientWindow);
          browsingContext.#initialize();
          return browsingContext;
        }
        #navigation = __runInitializers2(this, _instanceExtraInitializers);
        #reason;
        #url;
        // Indicated whether client hints have been set to non-default.
        #clientHintsAreSet = false;
        #children = /* @__PURE__ */ new Map();
        #disposables = new disposable_js_1.DisposableStack();
        #realms = /* @__PURE__ */ new Map();
        #requests = /* @__PURE__ */ new Map();
        defaultRealm;
        id;
        parent;
        userContext;
        originalOpener;
        windowId;
        #emulationState = { javaScriptEnabled: true };
        #bluetoothEmulation;
        #deviceRequestPromptManager;
        constructor(userContext, parent, id, url, originalOpener, clientWindow) {
          super();
          this.#url = url;
          this.id = id;
          this.parent = parent;
          this.userContext = userContext;
          this.originalOpener = originalOpener;
          this.windowId = clientWindow;
          this.defaultRealm = this.#createWindowRealm();
          this.#bluetoothEmulation = new BluetoothEmulation_js_1.BidiBluetoothEmulation(this.id, this.#session);
          this.#deviceRequestPromptManager = new DeviceRequestPrompt_js_1.BidiDeviceRequestPromptManager(this.id, this.#session);
        }
        #initialize() {
          const userContextEmitter = this.#disposables.use(new EventEmitter_js_1.EventEmitter(this.userContext));
          userContextEmitter.once("closed", ({ reason }) => {
            this.dispose(`Browsing context already closed: ${reason}`);
          });
          const sessionEmitter = this.#disposables.use(new EventEmitter_js_1.EventEmitter(this.#session));
          sessionEmitter.on("input.fileDialogOpened", (info) => {
            if (this.id !== info.context) {
              return;
            }
            this.emit("filedialogopened", info);
          });
          sessionEmitter.on("browsingContext.contextCreated", (info) => {
            if (info.parent !== this.id) {
              return;
            }
            const browsingContext = BrowsingContext2.from(this.userContext, this, info.context, info.url, info.originalOpener, info.clientWindow);
            this.#children.set(info.context, browsingContext);
            const browsingContextEmitter = this.#disposables.use(new EventEmitter_js_1.EventEmitter(browsingContext));
            browsingContextEmitter.once("closed", () => {
              browsingContextEmitter.removeAllListeners();
              this.#children.delete(browsingContext.id);
            });
            this.emit("browsingcontext", { browsingContext });
          });
          sessionEmitter.on("browsingContext.contextDestroyed", (info) => {
            if (info.context !== this.id) {
              return;
            }
            this.dispose("Browsing context already closed.");
          });
          sessionEmitter.on("browsingContext.historyUpdated", (info) => {
            if (info.context !== this.id) {
              return;
            }
            this.#url = info.url;
            this.emit("historyUpdated", void 0);
          });
          sessionEmitter.on("browsingContext.domContentLoaded", (info) => {
            if (info.context !== this.id) {
              return;
            }
            this.#url = info.url;
            this.emit("DOMContentLoaded", void 0);
          });
          sessionEmitter.on("browsingContext.load", (info) => {
            if (info.context !== this.id) {
              return;
            }
            this.#url = info.url;
            this.emit("load", void 0);
          });
          sessionEmitter.on("browsingContext.navigationStarted", (info) => {
            if (info.context !== this.id) {
              return;
            }
            for (const [id, request] of this.#requests) {
              if (request.disposed) {
                this.#requests.delete(id);
              }
            }
            if (this.#navigation !== void 0 && !this.#navigation.disposed) {
              return;
            }
            this.#navigation = Navigation_js_1.Navigation.from(this);
            const navigationEmitter = this.#disposables.use(new EventEmitter_js_1.EventEmitter(this.#navigation));
            for (const eventName of ["fragment", "failed", "aborted"]) {
              navigationEmitter.once(eventName, ({ url }) => {
                navigationEmitter[disposable_js_1.disposeSymbol]();
                this.#url = url;
              });
            }
            this.emit("navigation", { navigation: this.#navigation });
          });
          sessionEmitter.on("network.beforeRequestSent", (event) => {
            if (event.context !== this.id) {
              return;
            }
            if (this.#requests.has(event.request.request)) {
              return;
            }
            const request = Request_js_1.Request.from(this, event);
            this.#requests.set(request.id, request);
            this.emit("request", { request });
          });
          sessionEmitter.on("log.entryAdded", (entry) => {
            if (entry.source.context !== this.id) {
              return;
            }
            this.emit("log", { entry });
          });
          sessionEmitter.on("browsingContext.userPromptOpened", (info) => {
            if (info.context !== this.id) {
              return;
            }
            const userPrompt = UserPrompt_js_1.UserPrompt.from(this, info);
            this.emit("userprompt", { userPrompt });
          });
        }
        get #session() {
          return this.userContext.browser.session;
        }
        get children() {
          return this.#children.values();
        }
        get closed() {
          return this.#reason !== void 0;
        }
        get disposed() {
          return this.closed;
        }
        get realms() {
          const self2 = this;
          return (function* () {
            yield self2.defaultRealm;
            yield* self2.#realms.values();
          })();
        }
        get top() {
          let context = this;
          for (let { parent } = context; parent; { parent } = context) {
            context = parent;
          }
          return context;
        }
        get url() {
          return this.#url;
        }
        #createWindowRealm(sandbox) {
          const realm = Realm_js_1.WindowRealm.from(this, sandbox);
          realm.on("worker", (realm2) => {
            this.emit("worker", { realm: realm2 });
          });
          return realm;
        }
        dispose(reason) {
          this.#reason = reason;
          for (const context of this.#children.values()) {
            context.dispose("Parent browsing context was disposed");
          }
          this[disposable_js_1.disposeSymbol]();
        }
        async activate() {
          await this.#session.send("browsingContext.activate", {
            context: this.id
          });
        }
        async captureScreenshot(options = {}) {
          const { result: { data } } = await this.#session.send("browsingContext.captureScreenshot", {
            context: this.id,
            ...options
          });
          return data;
        }
        async close(promptUnload) {
          await this.#session.send("browsingContext.close", {
            context: this.id,
            promptUnload
          });
        }
        async traverseHistory(delta) {
          await this.#session.send("browsingContext.traverseHistory", {
            context: this.id,
            delta
          });
        }
        async navigate(url, wait) {
          await this.#session.send("browsingContext.navigate", {
            context: this.id,
            url,
            wait
          });
        }
        async reload(options = {}) {
          await this.#session.send("browsingContext.reload", {
            context: this.id,
            ...options
          });
        }
        async setCacheBehavior(cacheBehavior) {
          await this.#session.send("network.setCacheBehavior", {
            contexts: [this.id],
            cacheBehavior
          });
        }
        async print(options = {}) {
          const { result: { data } } = await this.#session.send("browsingContext.print", {
            context: this.id,
            ...options
          });
          return data;
        }
        async handleUserPrompt(options = {}) {
          await this.#session.send("browsingContext.handleUserPrompt", {
            context: this.id,
            ...options
          });
        }
        async setViewport(options = {}) {
          await this.#session.send("browsingContext.setViewport", {
            context: this.id,
            ...options
          });
        }
        async setTouchOverride(maxTouchPoints) {
          await this.#session.send("emulation.setTouchOverride", {
            contexts: [this.id],
            maxTouchPoints
          });
        }
        async performActions(actions) {
          await this.#session.send("input.performActions", {
            context: this.id,
            actions
          });
        }
        async releaseActions() {
          await this.#session.send("input.releaseActions", {
            context: this.id
          });
        }
        createWindowRealm(sandbox) {
          return this.#createWindowRealm(sandbox);
        }
        async addPreloadScript(functionDeclaration, options = {}) {
          return await this.userContext.browser.addPreloadScript(functionDeclaration, {
            ...options,
            contexts: [this]
          });
        }
        async addIntercept(options) {
          const { result: { intercept } } = await this.userContext.browser.session.send("network.addIntercept", {
            ...options,
            contexts: [this.id]
          });
          return intercept;
        }
        async removePreloadScript(script) {
          await this.userContext.browser.removePreloadScript(script);
        }
        async setGeolocationOverride(options) {
          if (!("coordinates" in options)) {
            throw new Error("Missing coordinates");
          }
          await this.userContext.browser.session.send("emulation.setGeolocationOverride", {
            coordinates: options.coordinates,
            contexts: [this.id]
          });
        }
        async setTimezoneOverride(timezoneId) {
          if (timezoneId?.startsWith("GMT")) {
            timezoneId = timezoneId?.replace("GMT", "");
          }
          await this.userContext.browser.session.send("emulation.setTimezoneOverride", {
            timezone: timezoneId ?? null,
            contexts: [this.id]
          });
        }
        async setScreenOrientationOverride(screenOrientation) {
          await this.#session.send("emulation.setScreenOrientationOverride", {
            screenOrientation,
            contexts: [this.id]
          });
        }
        async getCookies(options = {}) {
          const { result: { cookies } } = await this.#session.send("storage.getCookies", {
            ...options,
            partition: {
              type: "context",
              context: this.id
            }
          });
          return cookies;
        }
        async setCookie(cookie) {
          await this.#session.send("storage.setCookie", {
            cookie,
            partition: {
              type: "context",
              context: this.id
            }
          });
        }
        async setFiles(element, files) {
          await this.#session.send("input.setFiles", {
            context: this.id,
            element,
            files
          });
        }
        async subscribe(events) {
          await this.#session.subscribe(events, [this.id]);
        }
        async addInterception(events) {
          await this.#session.subscribe(events, [this.id]);
        }
        [(_dispose_decorators = [decorators_js_1.inertIfDisposed], _activate_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _captureScreenshot_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _close_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _traverseHistory_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _navigate_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _reload_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _setCacheBehavior_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _print_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _handleUserPrompt_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _setViewport_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _setTouchOverride_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _performActions_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _releaseActions_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _createWindowRealm_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _addPreloadScript_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _addIntercept_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _removePreloadScript_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _setGeolocationOverride_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _setTimezoneOverride_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _setScreenOrientationOverride_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _getCookies_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _setCookie_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _setFiles_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _subscribe_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _addInterception_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], disposable_js_1.disposeSymbol)]() {
          this.#reason ??= "Browsing context already closed, probably because the user context closed.";
          this.emit("closed", { reason: this.#reason });
          this.#disposables.dispose();
          super[disposable_js_1.disposeSymbol]();
        }
        async deleteCookie(...cookieFilters) {
          await Promise.all(cookieFilters.map(async (filter) => {
            await this.#session.send("storage.deleteCookies", {
              filter,
              partition: {
                type: "context",
                context: this.id
              }
            });
          }));
        }
        async locateNodes(locator, startNodes = []) {
          const result = await this.#session.send("browsingContext.locateNodes", {
            context: this.id,
            locator,
            startNodes: startNodes.length ? startNodes : void 0
          });
          return result.result.nodes;
        }
        async setJavaScriptEnabled(enabled) {
          await this.userContext.browser.session.send("emulation.setScriptingEnabled", {
            // Enabled `null` means `default`, `false` means `disabled`.
            enabled: enabled ? null : false,
            contexts: [this.id]
          });
          this.#emulationState.javaScriptEnabled = enabled;
        }
        isJavaScriptEnabled() {
          return this.#emulationState.javaScriptEnabled;
        }
        async setUserAgent(userAgent) {
          await this.#session.send("emulation.setUserAgentOverride", {
            userAgent,
            contexts: [this.id]
          });
        }
        async setClientHintsOverride(clientHints) {
          if (clientHints === null && !this.#clientHintsAreSet) {
            return;
          }
          this.#clientHintsAreSet = true;
          await this.#session.send("userAgentClientHints.setClientHintsOverride", {
            clientHints,
            contexts: [this.id]
          });
        }
        async setOfflineMode(enabled) {
          await this.#session.send("emulation.setNetworkConditions", {
            networkConditions: enabled ? {
              type: "offline"
            } : null,
            contexts: [this.id]
          });
        }
        get bluetooth() {
          return this.#bluetoothEmulation;
        }
        async waitForDevicePrompt(timeout, signal) {
          return await this.#deviceRequestPromptManager.waitForDevicePrompt(timeout, signal);
        }
        async setExtraHTTPHeaders(headers) {
          await this.#session.send("network.setExtraHeaders", {
            headers: Object.entries(headers).map(([key, value]) => {
              (0, assert_js_1.assert)((0, util_js_1.isString)(value), `Expected value of header "${key}" to be String, but "${typeof value}" is found.`);
              return {
                name: key.toLowerCase(),
                value: { type: "string", value }
              };
            }),
            contexts: [this.id]
          });
        }
      };
    })();
    exports2.BrowsingContext = BrowsingContext;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/core/UserContext.js
var require_UserContext = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/core/UserContext.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.UserContext = void 0;
    var EventEmitter_js_1 = require_EventEmitter();
    var assert_js_1 = require_assert();
    var decorators_js_1 = require_decorators();
    var disposable_js_1 = require_disposable();
    var BrowsingContext_js_1 = require_BrowsingContext();
    var UserContext = (() => {
      let _classSuper = EventEmitter_js_1.EventEmitter;
      let _instanceExtraInitializers = [];
      let _dispose_decorators;
      let _createBrowsingContext_decorators;
      let _remove_decorators;
      let _getCookies_decorators;
      let _setCookie_decorators;
      let _setPermissions_decorators;
      return class UserContext2 extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          __esDecorate2(this, null, _dispose_decorators, { kind: "method", name: "dispose", static: false, private: false, access: { has: (obj) => "dispose" in obj, get: (obj) => obj.dispose }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _createBrowsingContext_decorators, { kind: "method", name: "createBrowsingContext", static: false, private: false, access: { has: (obj) => "createBrowsingContext" in obj, get: (obj) => obj.createBrowsingContext }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _remove_decorators, { kind: "method", name: "remove", static: false, private: false, access: { has: (obj) => "remove" in obj, get: (obj) => obj.remove }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _getCookies_decorators, { kind: "method", name: "getCookies", static: false, private: false, access: { has: (obj) => "getCookies" in obj, get: (obj) => obj.getCookies }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _setCookie_decorators, { kind: "method", name: "setCookie", static: false, private: false, access: { has: (obj) => "setCookie" in obj, get: (obj) => obj.setCookie }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _setPermissions_decorators, { kind: "method", name: "setPermissions", static: false, private: false, access: { has: (obj) => "setPermissions" in obj, get: (obj) => obj.setPermissions }, metadata: _metadata }, null, _instanceExtraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        static DEFAULT = "default";
        static create(browser, id) {
          const context = new UserContext2(browser, id);
          context.#initialize();
          return context;
        }
        #reason = __runInitializers2(this, _instanceExtraInitializers);
        // Note these are only top-level contexts.
        #browsingContexts = /* @__PURE__ */ new Map();
        #disposables = new disposable_js_1.DisposableStack();
        #id;
        browser;
        constructor(browser, id) {
          super();
          this.#id = id;
          this.browser = browser;
        }
        #initialize() {
          const browserEmitter = this.#disposables.use(new EventEmitter_js_1.EventEmitter(this.browser));
          browserEmitter.once("closed", ({ reason }) => {
            this.dispose(`User context was closed: ${reason}`);
          });
          browserEmitter.once("disconnected", ({ reason }) => {
            this.dispose(`User context was closed: ${reason}`);
          });
          const sessionEmitter = this.#disposables.use(new EventEmitter_js_1.EventEmitter(this.#session));
          sessionEmitter.on("browsingContext.contextCreated", (info) => {
            if (info.parent) {
              return;
            }
            if (info.userContext !== this.#id) {
              return;
            }
            const browsingContext = BrowsingContext_js_1.BrowsingContext.from(this, void 0, info.context, info.url, info.originalOpener, info.clientWindow);
            this.#browsingContexts.set(browsingContext.id, browsingContext);
            const browsingContextEmitter = this.#disposables.use(new EventEmitter_js_1.EventEmitter(browsingContext));
            browsingContextEmitter.on("closed", () => {
              browsingContextEmitter.removeAllListeners();
              this.#browsingContexts.delete(browsingContext.id);
            });
            this.emit("browsingcontext", { browsingContext });
          });
        }
        get #session() {
          return this.browser.session;
        }
        get browsingContexts() {
          return this.#browsingContexts.values();
        }
        get closed() {
          return this.#reason !== void 0;
        }
        get disposed() {
          return this.closed;
        }
        get id() {
          return this.#id;
        }
        dispose(reason) {
          this.#reason = reason;
          this[disposable_js_1.disposeSymbol]();
        }
        async createBrowsingContext(type, options = {}) {
          const { result: { context: contextId } } = await this.#session.send("browsingContext.create", {
            type,
            ...options,
            referenceContext: options.referenceContext?.id,
            background: options.background,
            userContext: this.#id
          });
          const browsingContext = this.#browsingContexts.get(contextId);
          (0, assert_js_1.assert)(browsingContext, "The WebDriver BiDi implementation is failing to create a browsing context correctly.");
          return browsingContext;
        }
        async remove() {
          try {
            await this.#session.send("browser.removeUserContext", {
              userContext: this.#id
            });
          } finally {
            this.dispose("User context already closed.");
          }
        }
        async getCookies(options = {}, sourceOrigin = void 0) {
          const { result: { cookies } } = await this.#session.send("storage.getCookies", {
            ...options,
            partition: {
              type: "storageKey",
              userContext: this.#id,
              sourceOrigin
            }
          });
          return cookies;
        }
        async setCookie(cookie, sourceOrigin) {
          await this.#session.send("storage.setCookie", {
            cookie,
            partition: {
              type: "storageKey",
              sourceOrigin,
              userContext: this.id
            }
          });
        }
        async setPermissions(origin, descriptor, state) {
          await this.#session.send("permissions.setPermission", {
            origin,
            descriptor,
            state,
            userContext: this.#id
          });
        }
        [(_dispose_decorators = [decorators_js_1.inertIfDisposed], _createBrowsingContext_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _remove_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _getCookies_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _setCookie_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], _setPermissions_decorators = [(0, decorators_js_1.throwIfDisposed)((context) => {
          return context.#reason;
        })], disposable_js_1.disposeSymbol)]() {
          this.#reason ??= "User context already closed, probably because the browser disconnected/closed.";
          this.emit("closed", { reason: this.#reason });
          this.#disposables.dispose();
          super[disposable_js_1.disposeSymbol]();
        }
      };
    })();
    exports2.UserContext = UserContext;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Deserializer.js
var require_Deserializer = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Deserializer.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiDeserializer = void 0;
    var util_js_1 = require_util();
    var BidiDeserializer = class {
      static deserialize(result) {
        if (!result) {
          (0, util_js_1.debugError)("Service did not produce a result.");
          return void 0;
        }
        switch (result.type) {
          case "array":
            return result.value?.map((value) => {
              return this.deserialize(value);
            });
          case "set":
            return result.value?.reduce((acc, value) => {
              return acc.add(this.deserialize(value));
            }, /* @__PURE__ */ new Set());
          case "object":
            return result.value?.reduce((acc, tuple) => {
              const { key, value } = this.#deserializeTuple(tuple);
              acc[key] = value;
              return acc;
            }, {});
          case "map":
            return result.value?.reduce((acc, tuple) => {
              const { key, value } = this.#deserializeTuple(tuple);
              return acc.set(key, value);
            }, /* @__PURE__ */ new Map());
          case "promise":
            return {};
          case "regexp":
            return new RegExp(result.value.pattern, result.value.flags);
          case "date":
            return new Date(result.value);
          case "undefined":
            return void 0;
          case "null":
            return null;
          case "number":
            return this.#deserializeNumber(result.value);
          case "bigint":
            return BigInt(result.value);
          case "boolean":
            return Boolean(result.value);
          case "string":
            return result.value;
        }
        (0, util_js_1.debugError)(`Deserialization of type ${result.type} not supported.`);
        return void 0;
      }
      static #deserializeNumber(value) {
        switch (value) {
          case "-0":
            return -0;
          case "NaN":
            return NaN;
          case "Infinity":
            return Infinity;
          case "-Infinity":
            return -Infinity;
          default:
            return value;
        }
      }
      static #deserializeTuple([serializedKey, serializedValue]) {
        const key = typeof serializedKey === "string" ? serializedKey : this.deserialize(serializedKey);
        const value = this.deserialize(serializedValue);
        return { key, value };
      }
    };
    exports2.BidiDeserializer = BidiDeserializer;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/JSHandle.js
var require_JSHandle3 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/JSHandle.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiJSHandle = void 0;
    var JSHandle_js_1 = require_JSHandle();
    var Errors_js_1 = require_Errors();
    var Deserializer_js_1 = require_Deserializer();
    var BidiJSHandle = class _BidiJSHandle extends JSHandle_js_1.JSHandle {
      static from(value, realm) {
        return new _BidiJSHandle(value, realm);
      }
      #remoteValue;
      realm;
      #disposed = false;
      constructor(value, realm) {
        super();
        this.#remoteValue = value;
        this.realm = realm;
      }
      get disposed() {
        return this.#disposed;
      }
      async jsonValue() {
        return await this.evaluate((value) => {
          return value;
        });
      }
      asElement() {
        return null;
      }
      async dispose() {
        if (this.#disposed) {
          return;
        }
        this.#disposed = true;
        await this.realm.destroyHandles([this]);
      }
      get isPrimitiveValue() {
        switch (this.#remoteValue.type) {
          case "string":
          case "number":
          case "bigint":
          case "boolean":
          case "undefined":
          case "null":
            return true;
          default:
            return false;
        }
      }
      toString() {
        if (this.isPrimitiveValue) {
          return "JSHandle:" + Deserializer_js_1.BidiDeserializer.deserialize(this.#remoteValue);
        }
        return "JSHandle@" + this.#remoteValue.type;
      }
      get id() {
        return "handle" in this.#remoteValue ? this.#remoteValue.handle : void 0;
      }
      remoteValue() {
        return this.#remoteValue;
      }
      remoteObject() {
        throw new Errors_js_1.UnsupportedOperation("Not available in WebDriver BiDi");
      }
    };
    exports2.BidiJSHandle = BidiJSHandle;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/ElementHandle.js
var require_ElementHandle3 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/ElementHandle.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiElementHandle = void 0;
    var ElementHandle_js_1 = require_ElementHandle();
    var Errors_js_1 = require_Errors();
    var environment_js_1 = require_environment();
    var AsyncIterableUtil_js_1 = require_AsyncIterableUtil();
    var decorators_js_1 = require_decorators();
    var JSHandle_js_1 = require_JSHandle3();
    var BidiElementHandle = (() => {
      let _classSuper = ElementHandle_js_1.ElementHandle;
      let _instanceExtraInitializers = [];
      let _autofill_decorators;
      let _contentFrame_decorators;
      return class BidiElementHandle2 extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          _autofill_decorators = [(0, decorators_js_1.throwIfDisposed)()];
          _contentFrame_decorators = [(0, decorators_js_1.throwIfDisposed)(), ElementHandle_js_1.bindIsolatedHandle];
          __esDecorate2(this, null, _autofill_decorators, { kind: "method", name: "autofill", static: false, private: false, access: { has: (obj) => "autofill" in obj, get: (obj) => obj.autofill }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _contentFrame_decorators, { kind: "method", name: "contentFrame", static: false, private: false, access: { has: (obj) => "contentFrame" in obj, get: (obj) => obj.contentFrame }, metadata: _metadata }, null, _instanceExtraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #backendNodeId = __runInitializers2(this, _instanceExtraInitializers);
        static from(value, realm) {
          return new BidiElementHandle2(value, realm);
        }
        constructor(value, realm) {
          super(JSHandle_js_1.BidiJSHandle.from(value, realm));
        }
        get realm() {
          return this.handle.realm;
        }
        get frame() {
          return this.realm.environment;
        }
        remoteValue() {
          return this.handle.remoteValue();
        }
        async autofill(data) {
          const client2 = this.frame.client;
          const nodeInfo = await client2.send("DOM.describeNode", {
            objectId: this.handle.id
          });
          const fieldId = nodeInfo.node.backendNodeId;
          const frameId = this.frame._id;
          await client2.send("Autofill.trigger", {
            fieldId,
            frameId,
            card: data.creditCard
          });
        }
        async contentFrame() {
          const env_1 = { stack: [], error: void 0, hasError: false };
          try {
            const handle = __addDisposableResource2(env_1, await this.evaluateHandle((element) => {
              if (element instanceof HTMLIFrameElement || element instanceof HTMLFrameElement) {
                return element.contentWindow;
              }
              return;
            }), false);
            const value = handle.remoteValue();
            if (value.type === "window") {
              return this.frame.page().frames().find((frame) => {
                return frame._id === value.value.context;
              }) ?? null;
            }
            return null;
          } catch (e_1) {
            env_1.error = e_1;
            env_1.hasError = true;
          } finally {
            __disposeResources2(env_1);
          }
        }
        async uploadFile(...files) {
          const path2 = environment_js_1.environment.value.path;
          if (path2) {
            files = files.map((file) => {
              if (path2.win32.isAbsolute(file) || path2.posix.isAbsolute(file)) {
                return file;
              } else {
                return path2.resolve(file);
              }
            });
          }
          await this.frame.setFiles(this, files);
        }
        async *queryAXTree(name, role) {
          const results = await this.frame.locateNodes(this, {
            type: "accessibility",
            value: {
              role,
              name
            }
          });
          return yield* AsyncIterableUtil_js_1.AsyncIterableUtil.map(results, (node) => {
            return Promise.resolve(BidiElementHandle2.from(node, this.realm));
          });
        }
        async backendNodeId() {
          if (!this.frame.page().browser().cdpSupported) {
            throw new Errors_js_1.UnsupportedOperation();
          }
          if (this.#backendNodeId) {
            return this.#backendNodeId;
          }
          const { node } = await this.frame.client.send("DOM.describeNode", {
            objectId: this.handle.id
          });
          this.#backendNodeId = node.backendNodeId;
          return this.#backendNodeId;
        }
      };
    })();
    exports2.BidiElementHandle = BidiElementHandle;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Dialog.js
var require_Dialog3 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Dialog.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiDialog = void 0;
    var Dialog_js_1 = require_Dialog();
    var BidiDialog = class _BidiDialog extends Dialog_js_1.Dialog {
      static from(prompt) {
        return new _BidiDialog(prompt);
      }
      #prompt;
      constructor(prompt) {
        super(prompt.info.type, prompt.info.message, prompt.info.defaultValue);
        this.#prompt = prompt;
        this.handled = prompt.handled;
      }
      async handle(options) {
        await this.#prompt.handle({
          accept: options.accept,
          userText: options.text
        });
      }
    };
    exports2.BidiDialog = BidiDialog;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/ExposedFunction.js
var require_ExposedFunction = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/ExposedFunction.js"(exports2) {
    "use strict";
    init_prefix();
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ExposableFunction = void 0;
    var EventEmitter_js_1 = require_EventEmitter();
    var util_js_1 = require_util();
    var disposable_js_1 = require_disposable();
    var Function_js_1 = require_Function();
    var ElementHandle_js_1 = require_ElementHandle3();
    var JSHandle_js_1 = require_JSHandle3();
    var ExposableFunction = class _ExposableFunction {
      static async from(frame, name, apply, isolate = false) {
        const func = new _ExposableFunction(frame, name, apply, isolate);
        await func.#initialize();
        return func;
      }
      #frame;
      name;
      #apply;
      #isolate;
      #channel;
      #scripts = [];
      #disposables = new disposable_js_1.DisposableStack();
      constructor(frame, name, apply, isolate = false) {
        this.#frame = frame;
        this.name = name;
        this.#apply = apply;
        this.#isolate = isolate;
        this.#channel = `__puppeteer__${this.#frame._id}_page_exposeFunction_${this.name}`;
      }
      async #initialize() {
        const connection = this.#connection;
        const channel = {
          type: "channel",
          value: {
            channel: this.#channel,
            ownership: "root"
          }
        };
        const connectionEmitter = this.#disposables.use(new EventEmitter_js_1.EventEmitter(connection));
        connectionEmitter.on("script.message", this.#handleMessage);
        const functionDeclaration = (0, Function_js_1.stringifyFunction)((0, Function_js_1.interpolateFunction)((callback) => {
          Object.assign(globalThis, {
            [PLACEHOLDER("name")]: function(...args2) {
              return new Promise((resolve5, reject) => {
                callback([resolve5, reject, args2]);
              });
            }
          });
        }, { name: JSON.stringify(this.name) }));
        const frames = [this.#frame];
        for (const frame of frames) {
          frames.push(...frame.childFrames());
        }
        await Promise.all(frames.map(async (frame) => {
          const realm = this.#isolate ? frame.isolatedRealm() : frame.mainRealm();
          try {
            const [script] = await Promise.all([
              frame.browsingContext.addPreloadScript(functionDeclaration, {
                arguments: [channel],
                sandbox: realm.sandbox
              }),
              realm.realm.callFunction(functionDeclaration, false, {
                arguments: [channel]
              })
            ]);
            this.#scripts.push([frame, script]);
          } catch (error) {
            (0, util_js_1.debugError)(error);
          }
        }));
      }
      get #connection() {
        return this.#frame.page().browser().connection;
      }
      #handleMessage = async (params) => {
        const env_1 = { stack: [], error: void 0, hasError: false };
        try {
          if (params.channel !== this.#channel) {
            return;
          }
          const realm = this.#getRealm(params.source);
          if (!realm) {
            return;
          }
          const dataHandle = __addDisposableResource2(env_1, JSHandle_js_1.BidiJSHandle.from(params.data, realm), false);
          const stack = __addDisposableResource2(env_1, new disposable_js_1.DisposableStack(), false);
          const args2 = [];
          let result;
          try {
            const env_2 = { stack: [], error: void 0, hasError: false };
            try {
              const argsHandle = __addDisposableResource2(env_2, await dataHandle.evaluateHandle(([, , args3]) => {
                return args3;
              }), false);
              for (const [index, handle] of await argsHandle.getProperties()) {
                stack.use(handle);
                if (handle instanceof ElementHandle_js_1.BidiElementHandle) {
                  args2[+index] = handle;
                  stack.use(handle);
                  continue;
                }
                args2[+index] = handle.jsonValue();
              }
              result = await this.#apply(...await Promise.all(args2));
            } catch (e_1) {
              env_2.error = e_1;
              env_2.hasError = true;
            } finally {
              __disposeResources2(env_2);
            }
          } catch (error) {
            try {
              if (error instanceof Error) {
                await dataHandle.evaluate(([, reject], name, message, stack2) => {
                  const error2 = new Error(message);
                  error2.name = name;
                  if (stack2) {
                    error2.stack = stack2;
                  }
                  reject(error2);
                }, error.name, error.message, error.stack);
              } else {
                await dataHandle.evaluate(([, reject], error2) => {
                  reject(error2);
                }, error);
              }
            } catch (error2) {
              (0, util_js_1.debugError)(error2);
            }
            return;
          }
          try {
            await dataHandle.evaluate(([resolve5], result2) => {
              resolve5(result2);
            }, result);
          } catch (error) {
            (0, util_js_1.debugError)(error);
          }
        } catch (e_2) {
          env_1.error = e_2;
          env_1.hasError = true;
        } finally {
          __disposeResources2(env_1);
        }
      };
      #getRealm(source) {
        const frame = this.#findFrame(source.context);
        if (!frame) {
          return;
        }
        return frame.realm(source.realm);
      }
      #findFrame(id) {
        const frames = [this.#frame];
        for (const frame of frames) {
          if (frame._id === id) {
            return frame;
          }
          frames.push(...frame.childFrames());
        }
        return;
      }
      [Symbol.dispose]() {
        void this[Symbol.asyncDispose]().catch(util_js_1.debugError);
      }
      async [Symbol.asyncDispose]() {
        this.#disposables.dispose();
        await Promise.all(this.#scripts.map(async ([frame, script]) => {
          const realm = this.#isolate ? frame.isolatedRealm() : frame.mainRealm();
          try {
            await Promise.all([
              realm.evaluate((name) => {
                delete globalThis[name];
              }, this.name),
              ...frame.childFrames().map((childFrame) => {
                return childFrame.evaluate((name) => {
                  delete globalThis[name];
                }, this.name);
              }),
              frame.browsingContext.removePreloadScript(script)
            ]);
          } catch (error) {
            (0, util_js_1.debugError)(error);
          }
        }));
      }
    };
    exports2.ExposableFunction = ExposableFunction;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/HTTPResponse.js
var require_HTTPResponse3 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/HTTPResponse.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiHTTPResponse = void 0;
    var HTTPResponse_js_1 = require_HTTPResponse();
    var Errors_js_1 = require_Errors();
    var SecurityDetails_js_1 = require_SecurityDetails();
    var decorators_js_1 = require_decorators();
    var BidiHTTPResponse = (() => {
      let _classSuper = HTTPResponse_js_1.HTTPResponse;
      let _instanceExtraInitializers = [];
      let _remoteAddress_decorators;
      return class BidiHTTPResponse2 extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          _remoteAddress_decorators = [decorators_js_1.invokeAtMostOnceForArguments];
          __esDecorate2(this, null, _remoteAddress_decorators, { kind: "method", name: "remoteAddress", static: false, private: false, access: { has: (obj) => "remoteAddress" in obj, get: (obj) => obj.remoteAddress }, metadata: _metadata }, null, _instanceExtraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        /**
         * Returns a new BidiHTTPResponse or updates the existing one if it already exists.
         */
        static from(data, request, cdpSupported) {
          const existingResponse = request.response();
          if (existingResponse) {
            existingResponse.#data = data;
            return existingResponse;
          }
          const response = new BidiHTTPResponse2(data, request, cdpSupported);
          response.#initialize();
          return response;
        }
        #data = __runInitializers2(this, _instanceExtraInitializers);
        #request;
        #securityDetails;
        #cdpSupported = false;
        constructor(data, request, cdpSupported) {
          super();
          this.#data = data;
          this.#request = request;
          this.#cdpSupported = cdpSupported;
          const securityDetails = data["goog:securityDetails"];
          if (cdpSupported && securityDetails) {
            this.#securityDetails = new SecurityDetails_js_1.SecurityDetails(securityDetails);
          }
        }
        #initialize() {
          if (this.#data.fromCache) {
            this.#request._fromMemoryCache = true;
            this.#request.frame()?.page().trustedEmitter.emit("requestservedfromcache", this.#request);
          }
          this.#request.frame()?.page().trustedEmitter.emit("response", this);
        }
        remoteAddress() {
          return {
            ip: "",
            port: -1
          };
        }
        url() {
          return this.#data.url;
        }
        status() {
          return this.#data.status;
        }
        statusText() {
          return this.#data.statusText;
        }
        headers() {
          const headers = {};
          for (const header of this.#data.headers) {
            if (header.value.type === "string") {
              headers[header.name.toLowerCase()] = header.value.value;
            }
          }
          return headers;
        }
        request() {
          return this.#request;
        }
        fromCache() {
          return this.#data.fromCache;
        }
        timing() {
          const bidiTiming = this.#request.timing();
          return {
            requestTime: bidiTiming.requestTime,
            proxyStart: -1,
            proxyEnd: -1,
            dnsStart: bidiTiming.dnsStart,
            dnsEnd: bidiTiming.dnsEnd,
            connectStart: bidiTiming.connectStart,
            connectEnd: bidiTiming.connectEnd,
            sslStart: bidiTiming.tlsStart,
            sslEnd: -1,
            workerStart: -1,
            workerReady: -1,
            workerFetchStart: -1,
            workerRespondWithSettled: -1,
            workerRouterEvaluationStart: -1,
            workerCacheLookupStart: -1,
            sendStart: bidiTiming.requestStart,
            sendEnd: -1,
            pushStart: -1,
            pushEnd: -1,
            receiveHeadersStart: bidiTiming.responseStart,
            receiveHeadersEnd: bidiTiming.responseEnd
          };
        }
        frame() {
          return this.#request.frame();
        }
        fromServiceWorker() {
          return false;
        }
        securityDetails() {
          if (!this.#cdpSupported) {
            throw new Errors_js_1.UnsupportedOperation();
          }
          return this.#securityDetails ?? null;
        }
        async content() {
          return await this.#request.getResponseContent();
        }
      };
    })();
    exports2.BidiHTTPResponse = BidiHTTPResponse;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/HTTPRequest.js
var require_HTTPRequest3 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/HTTPRequest.js"(exports2) {
    "use strict";
    init_prefix();
    var _a2;
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiHTTPRequest = exports2.requests = void 0;
    var HTTPRequest_js_1 = require_HTTPRequest();
    var Errors_js_1 = require_Errors();
    var encoding_js_1 = require_encoding();
    var HTTPResponse_js_1 = require_HTTPResponse3();
    exports2.requests = /* @__PURE__ */ new WeakMap();
    var BidiHTTPRequest = class extends HTTPRequest_js_1.HTTPRequest {
      static from(bidiRequest, frame, isNetworkInterceptionEnabled, redirect) {
        const request = new _a2(bidiRequest, frame, isNetworkInterceptionEnabled, redirect);
        request.#initialize();
        return request;
      }
      #redirectChain;
      #response = null;
      id;
      #frame;
      #request;
      constructor(request, frame, isNetworkInterceptionEnabled, redirect) {
        super();
        exports2.requests.set(request, this);
        this.interception.enabled = isNetworkInterceptionEnabled;
        this.#request = request;
        this.#frame = frame;
        this.#redirectChain = redirect ? redirect.#redirectChain : [];
        this.id = request.id;
      }
      get client() {
        return this.#frame.client;
      }
      #initialize() {
        this.#request.on("redirect", (request) => {
          const httpRequest = _a2.from(request, this.#frame, this.interception.enabled, this);
          this.#redirectChain.push(this);
          request.once("success", () => {
            this.#frame.page().trustedEmitter.emit("requestfinished", httpRequest);
          });
          request.once("error", () => {
            this.#frame.page().trustedEmitter.emit("requestfailed", httpRequest);
          });
          void httpRequest.finalizeInterceptions();
        });
        this.#request.once("response", (data) => {
          this.#response = HTTPResponse_js_1.BidiHTTPResponse.from(data, this, this.#frame.page().browser().cdpSupported);
        });
        this.#request.once("success", (data) => {
          this.#response = HTTPResponse_js_1.BidiHTTPResponse.from(data, this, this.#frame.page().browser().cdpSupported);
        });
        this.#request.on("authenticate", this.#handleAuthentication);
        this.#frame.page().trustedEmitter.emit("request", this);
      }
      canBeIntercepted() {
        return this.#request.isBlocked;
      }
      interceptResolutionState() {
        if (!this.#request.isBlocked) {
          return { action: HTTPRequest_js_1.InterceptResolutionAction.Disabled };
        }
        return super.interceptResolutionState();
      }
      url() {
        return this.#request.url;
      }
      resourceType() {
        if (!this.#frame.page().browser().cdpSupported) {
          throw new Errors_js_1.UnsupportedOperation();
        }
        return (this.#request.resourceType || "other").toLowerCase();
      }
      method() {
        return this.#request.method;
      }
      postData() {
        if (!this.#frame.page().browser().cdpSupported) {
          throw new Errors_js_1.UnsupportedOperation();
        }
        return this.#request.postData;
      }
      hasPostData() {
        return this.#request.hasPostData;
      }
      async fetchPostData() {
        return await this.#request.fetchPostData();
      }
      headers() {
        const headers = {};
        for (const header of this.#request.headers) {
          headers[header.name.toLowerCase()] = header.value.value;
        }
        return {
          ...headers
        };
      }
      response() {
        return this.#response;
      }
      failure() {
        if (this.#request.error === void 0) {
          return null;
        }
        return { errorText: this.#request.error };
      }
      isNavigationRequest() {
        return this.#request.navigation !== void 0;
      }
      initiator() {
        return {
          ...this.#request.initiator,
          type: this.#request.initiator?.type ?? "other"
        };
      }
      redirectChain() {
        return this.#redirectChain.slice();
      }
      frame() {
        return this.#frame;
      }
      async _continue(overrides = {}) {
        const headers = getBidiHeaders(overrides.headers);
        this.interception.handled = true;
        return await this.#request.continueRequest({
          url: overrides.url,
          method: overrides.method,
          body: overrides.postData ? {
            type: "base64",
            value: (0, encoding_js_1.stringToBase64)(overrides.postData)
          } : void 0,
          headers: headers.length > 0 ? headers : void 0
        }).catch((error) => {
          this.interception.handled = false;
          return (0, HTTPRequest_js_1.handleError)(error);
        });
      }
      async _abort() {
        this.interception.handled = true;
        return await this.#request.failRequest().catch((error) => {
          this.interception.handled = false;
          throw error;
        });
      }
      async _respond(response, _priority) {
        this.interception.handled = true;
        let parsedBody;
        if (response.body) {
          parsedBody = HTTPRequest_js_1.HTTPRequest.getResponse(response.body);
        }
        const headers = getBidiHeaders(response.headers);
        const hasContentLength = headers.some((header) => {
          return header.name === "content-length";
        });
        if (response.contentType) {
          headers.push({
            name: "content-type",
            value: {
              type: "string",
              value: response.contentType
            }
          });
        }
        if (parsedBody?.contentLength && !hasContentLength) {
          headers.push({
            name: "content-length",
            value: {
              type: "string",
              value: String(parsedBody.contentLength)
            }
          });
        }
        const status = response.status || 200;
        return await this.#request.provideResponse({
          statusCode: status,
          headers: headers.length > 0 ? headers : void 0,
          reasonPhrase: HTTPRequest_js_1.STATUS_TEXTS[status],
          body: parsedBody?.base64 ? {
            type: "base64",
            value: parsedBody?.base64
          } : void 0
        }).catch((error) => {
          this.interception.handled = false;
          throw error;
        });
      }
      #authenticationHandled = false;
      #handleAuthentication = async () => {
        if (!this.#frame) {
          return;
        }
        const credentials = this.#frame.page()._credentials;
        if (credentials && !this.#authenticationHandled) {
          this.#authenticationHandled = true;
          void this.#request.continueWithAuth({
            action: "provideCredentials",
            credentials: {
              type: "password",
              username: credentials.username,
              password: credentials.password
            }
          });
        } else {
          void this.#request.continueWithAuth({
            action: "cancel"
          });
        }
      };
      timing() {
        return this.#request.timing();
      }
      getResponseContent() {
        return this.#request.getResponseContent();
      }
    };
    exports2.BidiHTTPRequest = BidiHTTPRequest;
    _a2 = BidiHTTPRequest;
    function getBidiHeaders(rawHeaders) {
      const headers = [];
      for (const [name, value] of Object.entries(rawHeaders ?? [])) {
        if (!Object.is(value, void 0)) {
          const values = Array.isArray(value) ? value : [value];
          for (const value2 of values) {
            headers.push({
              name: name.toLowerCase(),
              value: {
                type: "string",
                value: String(value2)
              }
            });
          }
        }
      }
      return headers;
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Serializer.js
var require_Serializer = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Serializer.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiSerializer = void 0;
    var util_js_1 = require_util();
    var UnserializableError = class extends Error {
    };
    var BidiSerializer = class {
      static serialize(arg) {
        switch (typeof arg) {
          case "symbol":
          case "function":
            throw new UnserializableError(`Unable to serializable ${typeof arg}`);
          case "object":
            return this.#serializeObject(arg);
          case "undefined":
            return {
              type: "undefined"
            };
          case "number":
            return this.#serializeNumber(arg);
          case "bigint":
            return {
              type: "bigint",
              value: arg.toString()
            };
          case "string":
            return {
              type: "string",
              value: arg
            };
          case "boolean":
            return {
              type: "boolean",
              value: arg
            };
        }
      }
      static #serializeNumber(arg) {
        let value;
        if (Object.is(arg, -0)) {
          value = "-0";
        } else if (Object.is(arg, Infinity)) {
          value = "Infinity";
        } else if (Object.is(arg, -Infinity)) {
          value = "-Infinity";
        } else if (Object.is(arg, NaN)) {
          value = "NaN";
        } else {
          value = arg;
        }
        return {
          type: "number",
          value
        };
      }
      static #serializeObject(arg) {
        if (arg === null) {
          return {
            type: "null"
          };
        } else if (Array.isArray(arg)) {
          const parsedArray = arg.map((subArg) => {
            return this.serialize(subArg);
          });
          return {
            type: "array",
            value: parsedArray
          };
        } else if ((0, util_js_1.isPlainObject)(arg)) {
          try {
            JSON.stringify(arg);
          } catch (error) {
            if (error instanceof TypeError && error.message.startsWith("Converting circular structure to JSON")) {
              error.message += " Recursive objects are not allowed.";
            }
            throw error;
          }
          const parsedObject = [];
          for (const key in arg) {
            parsedObject.push([this.serialize(key), this.serialize(arg[key])]);
          }
          return {
            type: "object",
            value: parsedObject
          };
        } else if ((0, util_js_1.isRegExp)(arg)) {
          return {
            type: "regexp",
            value: {
              pattern: arg.source,
              flags: arg.flags
            }
          };
        } else if ((0, util_js_1.isDate)(arg)) {
          return {
            type: "date",
            value: arg.toISOString()
          };
        }
        throw new UnserializableError("Custom object serialization not possible. Use plain objects instead.");
      }
    };
    exports2.BidiSerializer = BidiSerializer;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/util.js
var require_util2 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/util.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createEvaluationError = createEvaluationError;
    exports2.rewriteNavigationError = rewriteNavigationError;
    exports2.rewriteEvaluationError = rewriteEvaluationError;
    var Errors_js_1 = require_Errors();
    var util_js_1 = require_util();
    var Deserializer_js_1 = require_Deserializer();
    function createEvaluationError(details) {
      if (details.exception.type === "object" && !("value" in details.exception)) {
        return new Error(details.text);
      }
      if (details.exception.type !== "error") {
        return Deserializer_js_1.BidiDeserializer.deserialize(details.exception);
      }
      const [name = "", ...parts] = details.text.split(": ");
      const message = parts.join(": ");
      const error = new Error(message);
      error.name = name;
      const stackLines = [];
      if (details.stackTrace && stackLines.length < Error.stackTraceLimit) {
        for (const frame of details.stackTrace.callFrames.reverse()) {
          if (util_js_1.PuppeteerURL.isPuppeteerURL(frame.url) && frame.url !== util_js_1.PuppeteerURL.INTERNAL_URL) {
            const url = util_js_1.PuppeteerURL.parse(frame.url);
            stackLines.unshift(`    at ${frame.functionName || url.functionName} (${url.functionName} at ${url.siteString}, <anonymous>:${frame.lineNumber}:${frame.columnNumber})`);
          } else {
            stackLines.push(`    at ${frame.functionName || "<anonymous>"} (${frame.url}:${frame.lineNumber}:${frame.columnNumber})`);
          }
          if (stackLines.length >= Error.stackTraceLimit) {
            break;
          }
        }
      }
      error.stack = [details.text, ...stackLines].join("\n");
      return error;
    }
    function rewriteNavigationError(message, ms) {
      return (error) => {
        if (error instanceof Errors_js_1.ProtocolError) {
          error.message += ` at ${message}`;
        } else if (error instanceof Errors_js_1.TimeoutError) {
          error.message = `Navigation timeout of ${ms} ms exceeded`;
        }
        throw error;
      };
    }
    function rewriteEvaluationError(error) {
      if (error instanceof Error) {
        if (error.message.includes("ExecutionContext was destroyed") || error.message.includes("Inspected target navigated or closed")) {
          throw new Error("Execution context was destroyed, most likely because of a navigation.");
        }
      }
      throw error;
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Realm.js
var require_Realm4 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Realm.js"(exports2) {
    "use strict";
    init_prefix();
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiWorkerRealm = exports2.BidiFrameRealm = exports2.BidiRealm = void 0;
    var Realm_js_1 = require_Realm();
    var AriaQueryHandler_js_1 = require_AriaQueryHandler();
    var LazyArg_js_1 = require_LazyArg();
    var ScriptInjector_js_1 = require_ScriptInjector();
    var util_js_1 = require_util();
    var AsyncIterableUtil_js_1 = require_AsyncIterableUtil();
    var Function_js_1 = require_Function();
    var Deserializer_js_1 = require_Deserializer();
    var ElementHandle_js_1 = require_ElementHandle3();
    var ExposedFunction_js_1 = require_ExposedFunction();
    var JSHandle_js_1 = require_JSHandle3();
    var Serializer_js_1 = require_Serializer();
    var util_js_2 = require_util2();
    var BidiRealm = class extends Realm_js_1.Realm {
      realm;
      constructor(realm, timeoutSettings) {
        super(timeoutSettings);
        this.realm = realm;
      }
      initialize() {
        this.realm.on("destroyed", ({ reason }) => {
          this.taskManager.terminateAll(new Error(reason));
          this.dispose();
        });
        this.realm.on("updated", () => {
          this.internalPuppeteerUtil = void 0;
          void this.taskManager.rerunAll();
        });
      }
      internalPuppeteerUtil;
      get puppeteerUtil() {
        const promise = Promise.resolve();
        ScriptInjector_js_1.scriptInjector.inject((script) => {
          if (this.internalPuppeteerUtil) {
            void this.internalPuppeteerUtil.then((handle) => {
              void handle.dispose();
            });
          }
          this.internalPuppeteerUtil = promise.then(() => {
            return this.evaluateHandle(script);
          });
        }, !this.internalPuppeteerUtil);
        return this.internalPuppeteerUtil;
      }
      async evaluateHandle(pageFunction, ...args2) {
        return await this.#evaluate(false, pageFunction, ...args2);
      }
      async evaluate(pageFunction, ...args2) {
        return await this.#evaluate(true, pageFunction, ...args2);
      }
      async #evaluate(returnByValue, pageFunction, ...args2) {
        const sourceUrlComment = (0, util_js_1.getSourceUrlComment)((0, util_js_1.getSourcePuppeteerURLIfAvailable)(pageFunction)?.toString() ?? util_js_1.PuppeteerURL.INTERNAL_URL);
        let responsePromise;
        const resultOwnership = returnByValue ? "none" : "root";
        const serializationOptions = returnByValue ? {} : {
          maxObjectDepth: 0,
          maxDomDepth: 0
        };
        if ((0, util_js_1.isString)(pageFunction)) {
          const expression = util_js_1.SOURCE_URL_REGEX.test(pageFunction) ? pageFunction : `${pageFunction}
${sourceUrlComment}
`;
          responsePromise = this.realm.evaluate(expression, true, {
            resultOwnership,
            userActivation: true,
            serializationOptions
          });
        } else {
          let functionDeclaration = (0, Function_js_1.stringifyFunction)(pageFunction);
          functionDeclaration = util_js_1.SOURCE_URL_REGEX.test(functionDeclaration) ? functionDeclaration : `${functionDeclaration}
${sourceUrlComment}
`;
          responsePromise = this.realm.callFunction(
            functionDeclaration,
            /* awaitPromise= */
            true,
            {
              // LazyArgs are used only internally and should not affect the order
              // evaluate calls for the public APIs.
              arguments: args2.some((arg) => {
                return arg instanceof LazyArg_js_1.LazyArg;
              }) ? await Promise.all(args2.map((arg) => {
                return this.serializeAsync(arg);
              })) : args2.map((arg) => {
                return this.serialize(arg);
              }),
              resultOwnership,
              userActivation: true,
              serializationOptions
            }
          );
        }
        const result = await responsePromise.catch(util_js_2.rewriteEvaluationError);
        if ("type" in result && result.type === "exception") {
          throw (0, util_js_2.createEvaluationError)(result.exceptionDetails);
        }
        if (returnByValue) {
          return Deserializer_js_1.BidiDeserializer.deserialize(result.result);
        }
        return this.createHandle(result.result);
      }
      createHandle(result) {
        if ((result.type === "node" || result.type === "window") && this instanceof BidiFrameRealm) {
          return ElementHandle_js_1.BidiElementHandle.from(result, this);
        }
        return JSHandle_js_1.BidiJSHandle.from(result, this);
      }
      async serializeAsync(arg) {
        if (arg instanceof LazyArg_js_1.LazyArg) {
          arg = await arg.get(this);
        }
        return this.serialize(arg);
      }
      serialize(arg) {
        if (arg instanceof JSHandle_js_1.BidiJSHandle || arg instanceof ElementHandle_js_1.BidiElementHandle) {
          if (arg.realm !== this) {
            if (!(arg.realm instanceof BidiFrameRealm) || !(this instanceof BidiFrameRealm)) {
              throw new Error("Trying to evaluate JSHandle from different global types. Usually this means you're using a handle from a worker in a page or vice versa.");
            }
            if (arg.realm.environment !== this.environment) {
              throw new Error("Trying to evaluate JSHandle from different frames. Usually this means you're using a handle from a page on a different page.");
            }
          }
          if (arg.disposed) {
            throw new Error("JSHandle is disposed!");
          }
          return arg.remoteValue();
        }
        return Serializer_js_1.BidiSerializer.serialize(arg);
      }
      async destroyHandles(handles) {
        if (this.disposed) {
          return;
        }
        const handleIds = handles.map(({ id }) => {
          return id;
        }).filter((id) => {
          return id !== void 0;
        });
        if (handleIds.length === 0) {
          return;
        }
        await this.realm.disown(handleIds).catch((error) => {
          (0, util_js_1.debugError)(error);
        });
      }
      async adoptHandle(handle) {
        return await this.evaluateHandle((node) => {
          return node;
        }, handle);
      }
      async transferHandle(handle) {
        if (handle.realm === this) {
          return handle;
        }
        const transferredHandle = this.adoptHandle(handle);
        await handle.dispose();
        return await transferredHandle;
      }
    };
    exports2.BidiRealm = BidiRealm;
    var BidiFrameRealm = class _BidiFrameRealm extends BidiRealm {
      static from(realm, frame) {
        const frameRealm = new _BidiFrameRealm(realm, frame);
        frameRealm.#initialize();
        return frameRealm;
      }
      #frame;
      constructor(realm, frame) {
        super(realm, frame.timeoutSettings);
        this.#frame = frame;
      }
      #initialize() {
        super.initialize();
        this.realm.on("updated", () => {
          this.environment.clearDocumentHandle();
          this.#bindingsInstalled = false;
        });
      }
      #bindingsInstalled = false;
      get puppeteerUtil() {
        let promise = Promise.resolve();
        if (!this.#bindingsInstalled) {
          promise = Promise.all([
            ExposedFunction_js_1.ExposableFunction.from(this.environment, "__ariaQuerySelector", AriaQueryHandler_js_1.ARIAQueryHandler.queryOne, !!this.sandbox),
            ExposedFunction_js_1.ExposableFunction.from(this.environment, "__ariaQuerySelectorAll", async (element, selector) => {
              const results = AriaQueryHandler_js_1.ARIAQueryHandler.queryAll(element, selector);
              return await element.realm.evaluateHandle((...elements) => {
                return elements;
              }, ...await AsyncIterableUtil_js_1.AsyncIterableUtil.collect(results));
            }, !!this.sandbox)
          ]);
          this.#bindingsInstalled = true;
        }
        return promise.then(() => {
          return super.puppeteerUtil;
        });
      }
      get sandbox() {
        return this.realm.sandbox;
      }
      get environment() {
        return this.#frame;
      }
      async adoptBackendNode(backendNodeId) {
        const env_1 = { stack: [], error: void 0, hasError: false };
        try {
          const { object } = await this.#frame.client.send("DOM.resolveNode", {
            backendNodeId,
            executionContextId: await this.realm.resolveExecutionContextId()
          });
          const handle = __addDisposableResource2(env_1, ElementHandle_js_1.BidiElementHandle.from({
            handle: object.objectId,
            type: "node"
          }, this), false);
          return await handle.evaluateHandle((element) => {
            return element;
          });
        } catch (e_1) {
          env_1.error = e_1;
          env_1.hasError = true;
        } finally {
          __disposeResources2(env_1);
        }
      }
    };
    exports2.BidiFrameRealm = BidiFrameRealm;
    var BidiWorkerRealm = class _BidiWorkerRealm extends BidiRealm {
      static from(realm, worker) {
        const workerRealm = new _BidiWorkerRealm(realm, worker);
        workerRealm.initialize();
        return workerRealm;
      }
      #worker;
      constructor(realm, frame) {
        super(realm, frame.timeoutSettings);
        this.#worker = frame;
      }
      get environment() {
        return this.#worker;
      }
      async adoptBackendNode() {
        throw new Error("Cannot adopt DOM nodes into a worker.");
      }
    };
    exports2.BidiWorkerRealm = BidiWorkerRealm;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/WebWorker.js
var require_WebWorker3 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/WebWorker.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiWebWorker = void 0;
    var WebWorker_js_1 = require_WebWorker();
    var Errors_js_1 = require_Errors();
    var Realm_js_1 = require_Realm4();
    var BidiWebWorker = class _BidiWebWorker extends WebWorker_js_1.WebWorker {
      static from(frame, realm) {
        const worker = new _BidiWebWorker(frame, realm);
        return worker;
      }
      #frame;
      #realm;
      constructor(frame, realm) {
        super(realm.origin);
        this.#frame = frame;
        this.#realm = Realm_js_1.BidiWorkerRealm.from(realm, this);
      }
      get frame() {
        return this.#frame;
      }
      mainRealm() {
        return this.#realm;
      }
      get client() {
        throw new Errors_js_1.UnsupportedOperation();
      }
    };
    exports2.BidiWebWorker = BidiWebWorker;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Frame.js
var require_Frame3 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Frame.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    var __setFunctionName2 = exports2 && exports2.__setFunctionName || function(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 });
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiFrame = void 0;
    var rxjs_js_1 = require_rxjs();
    var Frame_js_1 = require_Frame();
    var Accessibility_js_1 = require_Accessibility();
    var ConsoleMessage_js_1 = require_ConsoleMessage();
    var Errors_js_1 = require_Errors();
    var util_js_1 = require_util();
    var ErrorLike_js_1 = require_ErrorLike();
    var CDPSession_js_1 = require_CDPSession2();
    var Deserializer_js_1 = require_Deserializer();
    var Dialog_js_1 = require_Dialog3();
    var ElementHandle_js_1 = require_ElementHandle3();
    var ExposedFunction_js_1 = require_ExposedFunction();
    var HTTPRequest_js_1 = require_HTTPRequest3();
    var JSHandle_js_1 = require_JSHandle3();
    var Realm_js_1 = require_Realm4();
    var util_js_2 = require_util2();
    var WebWorker_js_1 = require_WebWorker3();
    function convertConsoleMessageLevel(method) {
      switch (method) {
        case "group":
          return "startGroup";
        case "groupCollapsed":
          return "startGroupCollapsed";
        case "groupEnd":
          return "endGroup";
        default:
          return method;
      }
    }
    var BidiFrame = (() => {
      var _a2;
      let _classSuper = Frame_js_1.Frame;
      let _instanceExtraInitializers = [];
      let _goto_decorators;
      let _setContent_decorators;
      let _waitForNavigation_decorators;
      let _private_waitForLoad$_decorators;
      let _private_waitForLoad$_descriptor;
      let _private_waitForNetworkIdle$_decorators;
      let _private_waitForNetworkIdle$_descriptor;
      let _setFiles_decorators;
      let _frameElement_decorators;
      let _locateNodes_decorators;
      return class BidiFrame2 extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          _goto_decorators = [Frame_js_1.throwIfDetached];
          _setContent_decorators = [Frame_js_1.throwIfDetached];
          _waitForNavigation_decorators = [Frame_js_1.throwIfDetached];
          _private_waitForLoad$_decorators = [Frame_js_1.throwIfDetached];
          _private_waitForNetworkIdle$_decorators = [Frame_js_1.throwIfDetached];
          _setFiles_decorators = [Frame_js_1.throwIfDetached];
          _frameElement_decorators = [Frame_js_1.throwIfDetached];
          _locateNodes_decorators = [Frame_js_1.throwIfDetached];
          __esDecorate2(this, null, _goto_decorators, { kind: "method", name: "goto", static: false, private: false, access: { has: (obj) => "goto" in obj, get: (obj) => obj.goto }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _setContent_decorators, { kind: "method", name: "setContent", static: false, private: false, access: { has: (obj) => "setContent" in obj, get: (obj) => obj.setContent }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _waitForNavigation_decorators, { kind: "method", name: "waitForNavigation", static: false, private: false, access: { has: (obj) => "waitForNavigation" in obj, get: (obj) => obj.waitForNavigation }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, _private_waitForLoad$_descriptor = { value: __setFunctionName2(function(options = {}) {
            let { waitUntil = "load" } = options;
            const { timeout: ms = this.timeoutSettings.navigationTimeout() } = options;
            if (!Array.isArray(waitUntil)) {
              waitUntil = [waitUntil];
            }
            const events = /* @__PURE__ */ new Set();
            for (const lifecycleEvent of waitUntil) {
              switch (lifecycleEvent) {
                case "load": {
                  events.add("load");
                  break;
                }
                case "domcontentloaded": {
                  events.add("DOMContentLoaded");
                  break;
                }
              }
            }
            if (events.size === 0) {
              return (0, rxjs_js_1.of)(void 0);
            }
            return (0, rxjs_js_1.combineLatest)([...events].map((event) => {
              return (0, util_js_1.fromEmitterEvent)(this.browsingContext, event);
            })).pipe((0, rxjs_js_1.map)(() => {
            }), (0, rxjs_js_1.first)(), (0, rxjs_js_1.raceWith)((0, util_js_1.timeout)(ms), this.#detached$().pipe((0, rxjs_js_1.map)(() => {
              throw new Error("Frame detached.");
            }))));
          }, "#waitForLoad$") }, _private_waitForLoad$_decorators, { kind: "method", name: "#waitForLoad$", static: false, private: true, access: { has: (obj) => #waitForLoad$ in obj, get: (obj) => obj.#waitForLoad$ }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, _private_waitForNetworkIdle$_descriptor = { value: __setFunctionName2(function(options = {}) {
            let { waitUntil = "load" } = options;
            if (!Array.isArray(waitUntil)) {
              waitUntil = [waitUntil];
            }
            let concurrency = Infinity;
            for (const event of waitUntil) {
              switch (event) {
                case "networkidle0": {
                  concurrency = Math.min(0, concurrency);
                  break;
                }
                case "networkidle2": {
                  concurrency = Math.min(2, concurrency);
                  break;
                }
              }
            }
            if (concurrency === Infinity) {
              return (0, rxjs_js_1.of)(void 0);
            }
            return this.page().waitForNetworkIdle$({
              idleTime: 500,
              timeout: options.timeout ?? this.timeoutSettings.timeout(),
              concurrency
            });
          }, "#waitForNetworkIdle$") }, _private_waitForNetworkIdle$_decorators, { kind: "method", name: "#waitForNetworkIdle$", static: false, private: true, access: { has: (obj) => #waitForNetworkIdle$ in obj, get: (obj) => obj.#waitForNetworkIdle$ }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _setFiles_decorators, { kind: "method", name: "setFiles", static: false, private: false, access: { has: (obj) => "setFiles" in obj, get: (obj) => obj.setFiles }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _frameElement_decorators, { kind: "method", name: "frameElement", static: false, private: false, access: { has: (obj) => "frameElement" in obj, get: (obj) => obj.frameElement }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _locateNodes_decorators, { kind: "method", name: "locateNodes", static: false, private: false, access: { has: (obj) => "locateNodes" in obj, get: (obj) => obj.locateNodes }, metadata: _metadata }, null, _instanceExtraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        static from(parent, browsingContext) {
          const frame = new BidiFrame2(parent, browsingContext);
          frame.#initialize();
          return frame;
        }
        #parent = __runInitializers2(this, _instanceExtraInitializers);
        browsingContext;
        #frames = /* @__PURE__ */ new WeakMap();
        realms;
        _id;
        client;
        accessibility;
        constructor(parent, browsingContext) {
          super();
          this.#parent = parent;
          this.browsingContext = browsingContext;
          this._id = browsingContext.id;
          this.client = new CDPSession_js_1.BidiCdpSession(this);
          this.realms = {
            default: Realm_js_1.BidiFrameRealm.from(this.browsingContext.defaultRealm, this),
            internal: Realm_js_1.BidiFrameRealm.from(this.browsingContext.createWindowRealm(`__puppeteer_internal_${Math.ceil(Math.random() * 1e4)}`), this)
          };
          this.accessibility = new Accessibility_js_1.Accessibility(this.realms.default, this._id);
        }
        #initialize() {
          for (const browsingContext of this.browsingContext.children) {
            this.#createFrameTarget(browsingContext);
          }
          this.browsingContext.on("browsingcontext", ({ browsingContext }) => {
            this.#createFrameTarget(browsingContext);
          });
          this.browsingContext.on("closed", () => {
            for (const session of CDPSession_js_1.BidiCdpSession.sessions.values()) {
              if (session.frame === this) {
                session.onClose();
              }
            }
            this.page().trustedEmitter.emit("framedetached", this);
          });
          this.browsingContext.on("request", ({ request }) => {
            const httpRequest = HTTPRequest_js_1.BidiHTTPRequest.from(request, this, this.page().isNetworkInterceptionEnabled);
            request.once("success", () => {
              this.page().trustedEmitter.emit("requestfinished", httpRequest);
            });
            request.once("error", () => {
              this.page().trustedEmitter.emit("requestfailed", httpRequest);
            });
            void httpRequest.finalizeInterceptions();
          });
          this.browsingContext.on("navigation", ({ navigation }) => {
            navigation.once("fragment", () => {
              this.page().trustedEmitter.emit("framenavigated", this);
            });
          });
          this.browsingContext.on("load", () => {
            this.page().trustedEmitter.emit("load", void 0);
          });
          this.browsingContext.on("DOMContentLoaded", () => {
            this._hasStartedLoading = true;
            this.page().trustedEmitter.emit("domcontentloaded", void 0);
            this.page().trustedEmitter.emit("framenavigated", this);
          });
          this.browsingContext.on("userprompt", ({ userPrompt }) => {
            this.page().trustedEmitter.emit("dialog", Dialog_js_1.BidiDialog.from(userPrompt));
          });
          this.browsingContext.on("log", ({ entry }) => {
            if (this._id !== entry.source.context) {
              return;
            }
            if (isConsoleLogEntry(entry)) {
              const args2 = entry.args.map((arg) => {
                return this.mainRealm().createHandle(arg);
              });
              const text = args2.reduce((value, arg) => {
                const parsedValue = arg instanceof JSHandle_js_1.BidiJSHandle && arg.isPrimitiveValue ? Deserializer_js_1.BidiDeserializer.deserialize(arg.remoteValue()) : arg.toString();
                return `${value} ${parsedValue}`;
              }, "").slice(1);
              this.page().trustedEmitter.emit("console", new ConsoleMessage_js_1.ConsoleMessage(convertConsoleMessageLevel(entry.method), text, args2, getStackTraceLocations(entry.stackTrace), this, void 0));
            } else if (isJavaScriptLogEntry(entry)) {
              const error = new Error(entry.text ?? "");
              const messageHeight = error.message.split("\n").length;
              const messageLines = error.stack.split("\n").splice(0, messageHeight);
              const stackLines = [];
              if (entry.stackTrace) {
                for (const frame of entry.stackTrace.callFrames) {
                  stackLines.push(`    at ${frame.functionName || "<anonymous>"} (${frame.url}:${frame.lineNumber + 1}:${frame.columnNumber + 1})`);
                  if (stackLines.length >= Error.stackTraceLimit) {
                    break;
                  }
                }
              }
              error.stack = [...messageLines, ...stackLines].join("\n");
              this.page().trustedEmitter.emit("pageerror", error);
            } else {
              (0, util_js_1.debugError)(`Unhandled LogEntry with type "${entry.type}", text "${entry.text}" and level "${entry.level}"`);
            }
          });
          this.browsingContext.on("worker", ({ realm }) => {
            const worker = WebWorker_js_1.BidiWebWorker.from(this, realm);
            realm.on("destroyed", () => {
              this.page().trustedEmitter.emit("workerdestroyed", worker);
            });
            this.page().trustedEmitter.emit("workercreated", worker);
          });
        }
        #createFrameTarget(browsingContext) {
          const frame = BidiFrame2.from(this, browsingContext);
          this.#frames.set(browsingContext, frame);
          this.page().trustedEmitter.emit("frameattached", frame);
          browsingContext.on("closed", () => {
            this.#frames.delete(browsingContext);
          });
          return frame;
        }
        get timeoutSettings() {
          return this.page()._timeoutSettings;
        }
        mainRealm() {
          return this.realms.default;
        }
        isolatedRealm() {
          return this.realms.internal;
        }
        realm(id) {
          for (const realm of Object.values(this.realms)) {
            if (realm.realm.id === id) {
              return realm;
            }
          }
          return;
        }
        page() {
          let parent = this.#parent;
          while (parent instanceof BidiFrame2) {
            parent = parent.#parent;
          }
          return parent;
        }
        url() {
          return this.browsingContext.url;
        }
        parentFrame() {
          if (this.#parent instanceof BidiFrame2) {
            return this.#parent;
          }
          return null;
        }
        childFrames() {
          return [...this.browsingContext.children].map((child) => {
            return this.#frames.get(child);
          });
        }
        #detached$() {
          return (0, rxjs_js_1.defer)(() => {
            if (this.detached) {
              return (0, rxjs_js_1.of)(this);
            }
            return (0, util_js_1.fromEmitterEvent)(
              this.page().trustedEmitter,
              "framedetached"
              /* PageEvent.FrameDetached */
            ).pipe((0, rxjs_js_1.filter)((detachedFrame) => {
              return detachedFrame === this;
            }));
          });
        }
        async goto(url, options = {}) {
          const [response] = await Promise.all([
            this.waitForNavigation(options),
            // Some implementations currently only report errors when the
            // readiness=interactive.
            //
            // Related: https://bugzilla.mozilla.org/show_bug.cgi?id=1846601
            this.browsingContext.navigate(
              url,
              "interactive"
              /* Bidi.BrowsingContext.ReadinessState.Interactive */
            ).catch((error) => {
              if ((0, ErrorLike_js_1.isErrorLike)(error) && error.message.includes("net::ERR_HTTP_RESPONSE_CODE_FAILURE")) {
                return;
              }
              if (error.message.includes("navigation canceled")) {
                return;
              }
              if (error.message.includes("Navigation was aborted by another navigation")) {
                return;
              }
              throw error;
            })
          ]).catch((0, util_js_2.rewriteNavigationError)(url, options.timeout ?? this.timeoutSettings.navigationTimeout()));
          return response;
        }
        async setContent(html, options = {}) {
          await Promise.all([
            this.setFrameContent(html),
            (0, rxjs_js_1.firstValueFrom)((0, rxjs_js_1.combineLatest)([
              this.#waitForLoad$(options),
              this.#waitForNetworkIdle$(options)
            ]))
          ]);
        }
        async waitForNavigation(options = {}) {
          const { timeout: ms = this.timeoutSettings.navigationTimeout(), signal } = options;
          const frames = this.childFrames().map((frame) => {
            return frame.#detached$();
          });
          return await (0, rxjs_js_1.firstValueFrom)((0, rxjs_js_1.combineLatest)([
            (0, rxjs_js_1.race)((0, util_js_1.fromEmitterEvent)(this.browsingContext, "navigation"), (0, util_js_1.fromEmitterEvent)(this.browsingContext, "historyUpdated").pipe((0, rxjs_js_1.map)(() => {
              return { navigation: null };
            }))).pipe((0, rxjs_js_1.first)()).pipe((0, rxjs_js_1.switchMap)(({ navigation }) => {
              if (navigation === null) {
                return (0, rxjs_js_1.of)(null);
              }
              return this.#waitForLoad$(options).pipe((0, rxjs_js_1.delayWhen)(() => {
                if (frames.length === 0) {
                  return (0, rxjs_js_1.of)(void 0);
                }
                return (0, rxjs_js_1.combineLatest)(frames);
              }), (0, rxjs_js_1.raceWith)((0, util_js_1.fromEmitterEvent)(navigation, "fragment"), (0, util_js_1.fromEmitterEvent)(navigation, "failed"), (0, util_js_1.fromEmitterEvent)(navigation, "aborted")), (0, rxjs_js_1.switchMap)(() => {
                if (navigation.request) {
                  let requestFinished$ = function(request) {
                    if (navigation === null) {
                      return (0, rxjs_js_1.of)(null);
                    }
                    if (request.response || request.error) {
                      return (0, rxjs_js_1.of)(navigation);
                    }
                    if (request.redirect) {
                      return requestFinished$(request.redirect);
                    }
                    return (0, util_js_1.fromEmitterEvent)(request, "success").pipe((0, rxjs_js_1.raceWith)((0, util_js_1.fromEmitterEvent)(request, "error")), (0, rxjs_js_1.raceWith)((0, util_js_1.fromEmitterEvent)(request, "redirect"))).pipe((0, rxjs_js_1.switchMap)(() => {
                      return requestFinished$(request);
                    }));
                  };
                  return requestFinished$(navigation.request);
                }
                return (0, rxjs_js_1.of)(navigation);
              }));
            })),
            this.#waitForNetworkIdle$(options)
          ]).pipe((0, rxjs_js_1.map)(([navigation]) => {
            if (!navigation) {
              return null;
            }
            const request = navigation.request;
            if (!request) {
              return null;
            }
            const lastRequest = request.lastRedirect ?? request;
            const httpRequest = HTTPRequest_js_1.requests.get(lastRequest);
            return httpRequest.response();
          }), (0, rxjs_js_1.raceWith)((0, util_js_1.timeout)(ms), (0, util_js_1.fromAbortSignal)(signal), this.#detached$().pipe((0, rxjs_js_1.map)(() => {
            throw new Errors_js_1.TargetCloseError("Frame detached.");
          })))));
        }
        waitForDevicePrompt(options = {}) {
          const { timeout = this.timeoutSettings.timeout(), signal } = options;
          return this.browsingContext.waitForDevicePrompt(timeout, signal);
        }
        get detached() {
          return this.browsingContext.closed;
        }
        #exposedFunctions = /* @__PURE__ */ new Map();
        async exposeFunction(name, apply) {
          if (this.#exposedFunctions.has(name)) {
            throw new Error(`Failed to add page binding with name ${name}: globalThis['${name}'] already exists!`);
          }
          const exposable = await ExposedFunction_js_1.ExposableFunction.from(this, name, apply);
          this.#exposedFunctions.set(name, exposable);
        }
        async removeExposedFunction(name) {
          const exposedFunction = this.#exposedFunctions.get(name);
          if (!exposedFunction) {
            throw new Error(`Failed to remove page binding with name ${name}: window['${name}'] does not exists!`);
          }
          this.#exposedFunctions.delete(name);
          await exposedFunction[Symbol.asyncDispose]();
        }
        async createCDPSession() {
          if (!this.page().browser().cdpSupported) {
            throw new Errors_js_1.UnsupportedOperation();
          }
          const cdpConnection = this.page().browser().cdpConnection;
          return await cdpConnection._createSession({ targetId: this._id });
        }
        get #waitForLoad$() {
          return _private_waitForLoad$_descriptor.value;
        }
        get #waitForNetworkIdle$() {
          return _private_waitForNetworkIdle$_descriptor.value;
        }
        async setFiles(element, files) {
          await this.browsingContext.setFiles(
            // SAFETY: ElementHandles are always remote references.
            element.remoteValue(),
            files
          );
        }
        async frameElement() {
          const parentFrame = this.parentFrame();
          if (!parentFrame) {
            return null;
          }
          const [node] = await parentFrame.browsingContext.locateNodes({
            type: "context",
            value: {
              context: this._id
            }
          });
          if (!node) {
            return null;
          }
          return ElementHandle_js_1.BidiElementHandle.from(node, parentFrame.mainRealm());
        }
        async locateNodes(element, locator) {
          return await this.browsingContext.locateNodes(
            locator,
            // SAFETY: ElementHandles are always remote references.
            [element.remoteValue()]
          );
        }
      };
    })();
    exports2.BidiFrame = BidiFrame;
    function isConsoleLogEntry(event) {
      return event.type === "console";
    }
    function isJavaScriptLogEntry(event) {
      return event.type === "javascript";
    }
    function getStackTraceLocations(stackTrace) {
      const stackTraceLocations = [];
      if (stackTrace) {
        for (const callFrame of stackTrace.callFrames) {
          stackTraceLocations.push({
            url: callFrame.url,
            lineNumber: callFrame.lineNumber,
            columnNumber: callFrame.columnNumber
          });
        }
      }
      return stackTraceLocations;
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Input.js
var require_Input3 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Input.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiTouchscreen = exports2.BidiMouse = exports2.BidiKeyboard = void 0;
    var Input_js_1 = require_Input();
    var Errors_js_1 = require_Errors();
    var Errors_js_2 = require_Errors();
    var SourceActionsType;
    (function(SourceActionsType2) {
      SourceActionsType2["None"] = "none";
      SourceActionsType2["Key"] = "key";
      SourceActionsType2["Pointer"] = "pointer";
      SourceActionsType2["Wheel"] = "wheel";
    })(SourceActionsType || (SourceActionsType = {}));
    var ActionType;
    (function(ActionType2) {
      ActionType2["Pause"] = "pause";
      ActionType2["KeyDown"] = "keyDown";
      ActionType2["KeyUp"] = "keyUp";
      ActionType2["PointerUp"] = "pointerUp";
      ActionType2["PointerDown"] = "pointerDown";
      ActionType2["PointerMove"] = "pointerMove";
      ActionType2["Scroll"] = "scroll";
    })(ActionType || (ActionType = {}));
    var getBidiKeyValue = (key) => {
      switch (key) {
        case "\r":
        case "\n":
          key = "Enter";
          break;
      }
      if ([...key].length === 1) {
        return key;
      }
      switch (key) {
        case "Cancel":
          return "\uE001";
        case "Help":
          return "\uE002";
        case "Backspace":
          return "\uE003";
        case "Tab":
          return "\uE004";
        case "Clear":
          return "\uE005";
        case "Enter":
          return "\uE007";
        case "Shift":
        case "ShiftLeft":
          return "\uE008";
        case "Control":
        case "ControlLeft":
          return "\uE009";
        case "Alt":
        case "AltLeft":
          return "\uE00A";
        case "Pause":
          return "\uE00B";
        case "Escape":
          return "\uE00C";
        case "PageUp":
          return "\uE00E";
        case "PageDown":
          return "\uE00F";
        case "End":
          return "\uE010";
        case "Home":
          return "\uE011";
        case "ArrowLeft":
          return "\uE012";
        case "ArrowUp":
          return "\uE013";
        case "ArrowRight":
          return "\uE014";
        case "ArrowDown":
          return "\uE015";
        case "Insert":
          return "\uE016";
        case "Delete":
          return "\uE017";
        case "NumpadEqual":
          return "\uE019";
        case "Numpad0":
          return "\uE01A";
        case "Numpad1":
          return "\uE01B";
        case "Numpad2":
          return "\uE01C";
        case "Numpad3":
          return "\uE01D";
        case "Numpad4":
          return "\uE01E";
        case "Numpad5":
          return "\uE01F";
        case "Numpad6":
          return "\uE020";
        case "Numpad7":
          return "\uE021";
        case "Numpad8":
          return "\uE022";
        case "Numpad9":
          return "\uE023";
        case "NumpadMultiply":
          return "\uE024";
        case "NumpadAdd":
          return "\uE025";
        case "NumpadSubtract":
          return "\uE027";
        case "NumpadDecimal":
          return "\uE028";
        case "NumpadDivide":
          return "\uE029";
        case "F1":
          return "\uE031";
        case "F2":
          return "\uE032";
        case "F3":
          return "\uE033";
        case "F4":
          return "\uE034";
        case "F5":
          return "\uE035";
        case "F6":
          return "\uE036";
        case "F7":
          return "\uE037";
        case "F8":
          return "\uE038";
        case "F9":
          return "\uE039";
        case "F10":
          return "\uE03A";
        case "F11":
          return "\uE03B";
        case "F12":
          return "\uE03C";
        case "Meta":
        case "MetaLeft":
          return "\uE03D";
        case "ShiftRight":
          return "\uE050";
        case "ControlRight":
          return "\uE051";
        case "AltRight":
          return "\uE052";
        case "MetaRight":
          return "\uE053";
        case "Digit0":
          return "0";
        case "Digit1":
          return "1";
        case "Digit2":
          return "2";
        case "Digit3":
          return "3";
        case "Digit4":
          return "4";
        case "Digit5":
          return "5";
        case "Digit6":
          return "6";
        case "Digit7":
          return "7";
        case "Digit8":
          return "8";
        case "Digit9":
          return "9";
        case "KeyA":
          return "a";
        case "KeyB":
          return "b";
        case "KeyC":
          return "c";
        case "KeyD":
          return "d";
        case "KeyE":
          return "e";
        case "KeyF":
          return "f";
        case "KeyG":
          return "g";
        case "KeyH":
          return "h";
        case "KeyI":
          return "i";
        case "KeyJ":
          return "j";
        case "KeyK":
          return "k";
        case "KeyL":
          return "l";
        case "KeyM":
          return "m";
        case "KeyN":
          return "n";
        case "KeyO":
          return "o";
        case "KeyP":
          return "p";
        case "KeyQ":
          return "q";
        case "KeyR":
          return "r";
        case "KeyS":
          return "s";
        case "KeyT":
          return "t";
        case "KeyU":
          return "u";
        case "KeyV":
          return "v";
        case "KeyW":
          return "w";
        case "KeyX":
          return "x";
        case "KeyY":
          return "y";
        case "KeyZ":
          return "z";
        case "Semicolon":
          return ";";
        case "Equal":
          return "=";
        case "Comma":
          return ",";
        case "Minus":
          return "-";
        case "Period":
          return ".";
        case "Slash":
          return "/";
        case "Backquote":
          return "`";
        case "BracketLeft":
          return "[";
        case "Backslash":
          return "\\";
        case "BracketRight":
          return "]";
        case "Quote":
          return '"';
        default:
          throw new Error(`Unknown key: "${key}"`);
      }
    };
    var BidiKeyboard = class extends Input_js_1.Keyboard {
      #page;
      constructor(page2) {
        super();
        this.#page = page2;
      }
      async down(key, _options) {
        await this.#page.mainFrame().browsingContext.performActions([
          {
            type: SourceActionsType.Key,
            id: "__puppeteer_keyboard",
            actions: [
              {
                type: ActionType.KeyDown,
                value: getBidiKeyValue(key)
              }
            ]
          }
        ]);
      }
      async up(key) {
        await this.#page.mainFrame().browsingContext.performActions([
          {
            type: SourceActionsType.Key,
            id: "__puppeteer_keyboard",
            actions: [
              {
                type: ActionType.KeyUp,
                value: getBidiKeyValue(key)
              }
            ]
          }
        ]);
      }
      async press(key, options = {}) {
        const { delay = 0 } = options;
        const actions = [
          {
            type: ActionType.KeyDown,
            value: getBidiKeyValue(key)
          }
        ];
        if (delay > 0) {
          actions.push({
            type: ActionType.Pause,
            duration: delay
          });
        }
        actions.push({
          type: ActionType.KeyUp,
          value: getBidiKeyValue(key)
        });
        await this.#page.mainFrame().browsingContext.performActions([
          {
            type: SourceActionsType.Key,
            id: "__puppeteer_keyboard",
            actions
          }
        ]);
      }
      async type(text, options = {}) {
        const { delay = 0 } = options;
        const values = [...text].map(getBidiKeyValue);
        const actions = [];
        if (delay <= 0) {
          for (const value of values) {
            actions.push({
              type: ActionType.KeyDown,
              value
            }, {
              type: ActionType.KeyUp,
              value
            });
          }
        } else {
          for (const value of values) {
            actions.push({
              type: ActionType.KeyDown,
              value
            }, {
              type: ActionType.Pause,
              duration: delay
            }, {
              type: ActionType.KeyUp,
              value
            });
          }
        }
        await this.#page.mainFrame().browsingContext.performActions([
          {
            type: SourceActionsType.Key,
            id: "__puppeteer_keyboard",
            actions
          }
        ]);
      }
      async sendCharacter(char) {
        if ([...char].length > 1) {
          throw new Error("Cannot send more than 1 character.");
        }
        const frame = await this.#page.focusedFrame();
        await frame.isolatedRealm().evaluate(async (char2) => {
          document.execCommand("insertText", false, char2);
        }, char);
      }
    };
    exports2.BidiKeyboard = BidiKeyboard;
    var getBidiButton = (button) => {
      switch (button) {
        case Input_js_1.MouseButton.Left:
          return 0;
        case Input_js_1.MouseButton.Middle:
          return 1;
        case Input_js_1.MouseButton.Right:
          return 2;
        case Input_js_1.MouseButton.Back:
          return 3;
        case Input_js_1.MouseButton.Forward:
          return 4;
      }
    };
    var BidiMouse = class extends Input_js_1.Mouse {
      #page;
      #lastMovePoint = { x: 0, y: 0 };
      constructor(page2) {
        super();
        this.#page = page2;
      }
      async reset() {
        this.#lastMovePoint = { x: 0, y: 0 };
        await this.#page.mainFrame().browsingContext.releaseActions();
      }
      async move(x, y, options = {}) {
        const from = this.#lastMovePoint;
        const to = {
          x: Math.round(x),
          y: Math.round(y)
        };
        const actions = [];
        const steps = options.steps ?? 0;
        for (let i = 0; i < steps; ++i) {
          actions.push({
            type: ActionType.PointerMove,
            x: from.x + (to.x - from.x) * (i / steps),
            y: from.y + (to.y - from.y) * (i / steps),
            origin: options.origin
          });
        }
        actions.push({
          type: ActionType.PointerMove,
          ...to,
          origin: options.origin
        });
        this.#lastMovePoint = to;
        await this.#page.mainFrame().browsingContext.performActions([
          {
            type: SourceActionsType.Pointer,
            id: "__puppeteer_mouse",
            actions
          }
        ]);
      }
      async down(options = {}) {
        await this.#page.mainFrame().browsingContext.performActions([
          {
            type: SourceActionsType.Pointer,
            id: "__puppeteer_mouse",
            actions: [
              {
                type: ActionType.PointerDown,
                button: getBidiButton(options.button ?? Input_js_1.MouseButton.Left)
              }
            ]
          }
        ]);
      }
      async up(options = {}) {
        await this.#page.mainFrame().browsingContext.performActions([
          {
            type: SourceActionsType.Pointer,
            id: "__puppeteer_mouse",
            actions: [
              {
                type: ActionType.PointerUp,
                button: getBidiButton(options.button ?? Input_js_1.MouseButton.Left)
              }
            ]
          }
        ]);
      }
      async click(x, y, options = {}) {
        const actions = [
          {
            type: ActionType.PointerMove,
            x: Math.round(x),
            y: Math.round(y),
            origin: options.origin
          }
        ];
        const pointerDownAction = {
          type: ActionType.PointerDown,
          button: getBidiButton(options.button ?? Input_js_1.MouseButton.Left)
        };
        const pointerUpAction = {
          type: ActionType.PointerUp,
          button: pointerDownAction.button
        };
        for (let i = 1; i < (options.count ?? 1); ++i) {
          actions.push(pointerDownAction, pointerUpAction);
        }
        actions.push(pointerDownAction);
        if (options.delay) {
          actions.push({
            type: ActionType.Pause,
            duration: options.delay
          });
        }
        actions.push(pointerUpAction);
        await this.#page.mainFrame().browsingContext.performActions([
          {
            type: SourceActionsType.Pointer,
            id: "__puppeteer_mouse",
            actions
          }
        ]);
      }
      async wheel(options = {}) {
        await this.#page.mainFrame().browsingContext.performActions([
          {
            type: SourceActionsType.Wheel,
            id: "__puppeteer_wheel",
            actions: [
              {
                type: ActionType.Scroll,
                ...this.#lastMovePoint ?? {
                  x: 0,
                  y: 0
                },
                deltaX: options.deltaX ?? 0,
                deltaY: options.deltaY ?? 0
              }
            ]
          }
        ]);
      }
      drag() {
        throw new Errors_js_1.UnsupportedOperation();
      }
      dragOver() {
        throw new Errors_js_1.UnsupportedOperation();
      }
      dragEnter() {
        throw new Errors_js_1.UnsupportedOperation();
      }
      drop() {
        throw new Errors_js_1.UnsupportedOperation();
      }
      dragAndDrop() {
        throw new Errors_js_1.UnsupportedOperation();
      }
    };
    exports2.BidiMouse = BidiMouse;
    var BidiTouchHandle = class {
      #started = false;
      #x;
      #y;
      #bidiId;
      #page;
      #touchScreen;
      #properties;
      constructor(page2, touchScreen, id, x, y, properties) {
        this.#page = page2;
        this.#touchScreen = touchScreen;
        this.#x = Math.round(x);
        this.#y = Math.round(y);
        this.#properties = properties;
        this.#bidiId = `${"__puppeteer_finger"}_${id}`;
      }
      async start(options = {}) {
        if (this.#started) {
          throw new Errors_js_2.TouchError("Touch has already started");
        }
        await this.#page.mainFrame().browsingContext.performActions([
          {
            type: SourceActionsType.Pointer,
            id: this.#bidiId,
            parameters: {
              pointerType: "touch"
            },
            actions: [
              {
                type: ActionType.PointerMove,
                x: this.#x,
                y: this.#y,
                origin: options.origin
              },
              {
                ...this.#properties,
                type: ActionType.PointerDown,
                button: 0
              }
            ]
          }
        ]);
        this.#started = true;
      }
      move(x, y) {
        const newX = Math.round(x);
        const newY = Math.round(y);
        return this.#page.mainFrame().browsingContext.performActions([
          {
            type: SourceActionsType.Pointer,
            id: this.#bidiId,
            parameters: {
              pointerType: "touch"
            },
            actions: [
              {
                ...this.#properties,
                type: ActionType.PointerMove,
                x: newX,
                y: newY
              }
            ]
          }
        ]);
      }
      async end() {
        await this.#page.mainFrame().browsingContext.performActions([
          {
            type: SourceActionsType.Pointer,
            id: this.#bidiId,
            parameters: {
              pointerType: "touch"
            },
            actions: [
              {
                type: ActionType.PointerUp,
                button: 0
              }
            ]
          }
        ]);
        this.#touchScreen.removeHandle(this);
      }
    };
    var BidiTouchscreen = class extends Input_js_1.Touchscreen {
      #page;
      constructor(page2) {
        super();
        this.#page = page2;
      }
      async touchStart(x, y, options = {}) {
        const id = this.idGenerator();
        const properties = {
          width: 0.5 * 2,
          // 2 times default touch radius.
          height: 0.5 * 2,
          // 2 times default touch radius.
          pressure: 0.5,
          altitudeAngle: Math.PI / 2
        };
        const touch = new BidiTouchHandle(this.#page, this, id, x, y, properties);
        await touch.start(options);
        this.touches.push(touch);
        return touch;
      }
    };
    exports2.BidiTouchscreen = BidiTouchscreen;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Page.js
var require_Page3 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Page.js"(exports2) {
    "use strict";
    init_prefix();
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiPage = void 0;
    exports2.bidiToPuppeteerCookie = bidiToPuppeteerCookie;
    exports2.cdpSpecificCookiePropertiesFromPuppeteerToBidi = cdpSpecificCookiePropertiesFromPuppeteerToBidi;
    exports2.convertCookiesSameSiteCdpToBiDi = convertCookiesSameSiteCdpToBiDi;
    exports2.convertCookiesExpiryCdpToBiDi = convertCookiesExpiryCdpToBiDi;
    exports2.convertCookiesPartitionKeyFromPuppeteerToBiDi = convertCookiesPartitionKeyFromPuppeteerToBiDi;
    var rxjs_js_1 = require_rxjs();
    var Page_js_1 = require_Page();
    var Coverage_js_1 = require_Coverage();
    var EmulationManager_js_1 = require_EmulationManager();
    var Tracing_js_1 = require_Tracing();
    var Errors_js_1 = require_Errors();
    var EventEmitter_js_1 = require_EventEmitter();
    var FileChooser_js_1 = require_FileChooser();
    var util_js_1 = require_util();
    var assert_js_1 = require_assert();
    var decorators_js_1 = require_decorators();
    var Deferred_js_1 = require_Deferred();
    var encoding_js_1 = require_encoding();
    var ElementHandle_js_1 = require_ElementHandle3();
    var Frame_js_1 = require_Frame3();
    var Input_js_1 = require_Input3();
    var util_js_2 = require_util2();
    var BidiPage = (() => {
      let _classSuper = Page_js_1.Page;
      let _trustedEmitter_decorators;
      let _trustedEmitter_initializers = [];
      let _trustedEmitter_extraInitializers = [];
      return class BidiPage2 extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          _trustedEmitter_decorators = [(0, decorators_js_1.bubble)()];
          __esDecorate2(this, null, _trustedEmitter_decorators, { kind: "accessor", name: "trustedEmitter", static: false, private: false, access: { has: (obj) => "trustedEmitter" in obj, get: (obj) => obj.trustedEmitter, set: (obj, value) => {
            obj.trustedEmitter = value;
          } }, metadata: _metadata }, _trustedEmitter_initializers, _trustedEmitter_extraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        static from(browserContext, browsingContext) {
          const page2 = new BidiPage2(browserContext, browsingContext);
          page2.#initialize();
          return page2;
        }
        #trustedEmitter_accessor_storage = __runInitializers2(this, _trustedEmitter_initializers, new EventEmitter_js_1.EventEmitter());
        get trustedEmitter() {
          return this.#trustedEmitter_accessor_storage;
        }
        set trustedEmitter(value) {
          this.#trustedEmitter_accessor_storage = value;
        }
        #browserContext = __runInitializers2(this, _trustedEmitter_extraInitializers);
        #frame;
        #viewport = null;
        #workers = /* @__PURE__ */ new Set();
        keyboard;
        mouse;
        touchscreen;
        tracing;
        coverage;
        #cdpEmulationManager;
        #emulatedNetworkConditions;
        #fileChooserDeferreds = /* @__PURE__ */ new Set();
        _client() {
          return this.#frame.client;
        }
        constructor(browserContext, browsingContext) {
          super();
          this.#browserContext = browserContext;
          this.#frame = Frame_js_1.BidiFrame.from(this, browsingContext);
          this.#cdpEmulationManager = new EmulationManager_js_1.EmulationManager(this.#frame.client);
          this.tracing = new Tracing_js_1.Tracing(this.#frame.client);
          this.coverage = new Coverage_js_1.Coverage(this.#frame.client);
          this.keyboard = new Input_js_1.BidiKeyboard(this);
          this.mouse = new Input_js_1.BidiMouse(this);
          this.touchscreen = new Input_js_1.BidiTouchscreen(this);
        }
        #initialize() {
          this.#frame.browsingContext.on("closed", () => {
            this.trustedEmitter.emit("close", void 0);
            this.trustedEmitter.removeAllListeners();
          });
          this.trustedEmitter.on("workercreated", (worker) => {
            this.#workers.add(worker);
          });
          this.trustedEmitter.on("workerdestroyed", (worker) => {
            this.#workers.delete(worker);
          });
        }
        /**
         * @internal
         */
        async setUserAgent(userAgentOrOptions, userAgentMetadata) {
          let userAgent;
          let clientHints;
          let platform;
          if (typeof userAgentOrOptions === "string") {
            userAgent = userAgentOrOptions;
            clientHints = userAgentMetadata;
          } else {
            userAgent = userAgentOrOptions.userAgent ?? null;
            clientHints = userAgentOrOptions.userAgentMetadata;
            platform = userAgentOrOptions.platform === "" ? void 0 : userAgentOrOptions.platform;
          }
          if (userAgent === "") {
            userAgent = null;
          }
          await this.#frame.browsingContext.setUserAgent(userAgent);
          if (platform && platform !== "") {
            clientHints = clientHints ?? {};
            clientHints.platform = platform;
          }
          await this.#frame.browsingContext.setClientHintsOverride(clientHints ?? null);
        }
        async setBypassCSP(enabled) {
          await this._client().send("Page.setBypassCSP", { enabled });
        }
        async queryObjects(prototypeHandle) {
          (0, assert_js_1.assert)(!prototypeHandle.disposed, "Prototype JSHandle is disposed!");
          (0, assert_js_1.assert)(prototypeHandle.id, "Prototype JSHandle must not be referencing primitive value");
          const response = await this.#frame.client.send("Runtime.queryObjects", {
            prototypeObjectId: prototypeHandle.id
          });
          return this.#frame.mainRealm().createHandle({
            type: "array",
            handle: response.objects.objectId
          });
        }
        browser() {
          return this.browserContext().browser();
        }
        browserContext() {
          return this.#browserContext;
        }
        mainFrame() {
          return this.#frame;
        }
        async emulateFocusedPage(enabled) {
          return await this.#cdpEmulationManager.emulateFocus(enabled);
        }
        resize(_params) {
          throw new Errors_js_1.UnsupportedOperation();
        }
        async windowId() {
          return this.#frame.browsingContext.windowId;
        }
        openDevTools() {
          throw new Errors_js_1.UnsupportedOperation();
        }
        hasDevTools() {
          throw new Errors_js_1.UnsupportedOperation();
        }
        async focusedFrame() {
          const env_1 = { stack: [], error: void 0, hasError: false };
          try {
            const handle = __addDisposableResource2(env_1, await this.mainFrame().isolatedRealm().evaluateHandle(() => {
              let win = window;
              while (win.document.activeElement instanceof win.HTMLIFrameElement || win.document.activeElement instanceof win.HTMLFrameElement) {
                if (win.document.activeElement.contentWindow === null) {
                  break;
                }
                win = win.document.activeElement.contentWindow;
              }
              return win;
            }), false);
            const value = handle.remoteValue();
            (0, assert_js_1.assert)(value.type === "window");
            const frame = this.frames().find((frame2) => {
              return frame2._id === value.value.context;
            });
            (0, assert_js_1.assert)(frame);
            return frame;
          } catch (e_1) {
            env_1.error = e_1;
            env_1.hasError = true;
          } finally {
            __disposeResources2(env_1);
          }
        }
        frames() {
          const frames = [this.#frame];
          for (const frame of frames) {
            frames.push(...frame.childFrames());
          }
          return frames;
        }
        isClosed() {
          return this.#frame.detached;
        }
        async close(options) {
          const env_2 = { stack: [], error: void 0, hasError: false };
          try {
            const _guard = __addDisposableResource2(env_2, await this.#browserContext.waitForScreenshotOperations(), false);
            try {
              await this.#frame.browsingContext.close(options?.runBeforeUnload);
            } catch {
              return;
            }
          } catch (e_2) {
            env_2.error = e_2;
            env_2.hasError = true;
          } finally {
            __disposeResources2(env_2);
          }
        }
        async reload(options = {}) {
          const [response] = await Promise.all([
            this.#frame.waitForNavigation(options),
            this.#frame.browsingContext.reload({
              ignoreCache: options.ignoreCache ? true : void 0
            })
          ]).catch((0, util_js_2.rewriteNavigationError)(this.url(), options.timeout ?? this._timeoutSettings.navigationTimeout()));
          return response;
        }
        setDefaultNavigationTimeout(timeout) {
          this._timeoutSettings.setDefaultNavigationTimeout(timeout);
        }
        setDefaultTimeout(timeout) {
          this._timeoutSettings.setDefaultTimeout(timeout);
        }
        getDefaultTimeout() {
          return this._timeoutSettings.timeout();
        }
        getDefaultNavigationTimeout() {
          return this._timeoutSettings.navigationTimeout();
        }
        isJavaScriptEnabled() {
          return this.#frame.browsingContext.isJavaScriptEnabled();
        }
        async setGeolocation(options) {
          const { longitude, latitude, accuracy = 0 } = options;
          if (longitude < -180 || longitude > 180) {
            throw new Error(`Invalid longitude "${longitude}": precondition -180 <= LONGITUDE <= 180 failed.`);
          }
          if (latitude < -90 || latitude > 90) {
            throw new Error(`Invalid latitude "${latitude}": precondition -90 <= LATITUDE <= 90 failed.`);
          }
          if (accuracy < 0) {
            throw new Error(`Invalid accuracy "${accuracy}": precondition 0 <= ACCURACY failed.`);
          }
          return await this.#frame.browsingContext.setGeolocationOverride({
            coordinates: {
              latitude: options.latitude,
              longitude: options.longitude,
              accuracy: options.accuracy
            }
          });
        }
        async setJavaScriptEnabled(enabled) {
          return await this.#frame.browsingContext.setJavaScriptEnabled(enabled);
        }
        async emulateMediaType(type) {
          return await this.#cdpEmulationManager.emulateMediaType(type);
        }
        async emulateCPUThrottling(factor) {
          return await this.#cdpEmulationManager.emulateCPUThrottling(factor);
        }
        async emulateMediaFeatures(features) {
          return await this.#cdpEmulationManager.emulateMediaFeatures(features);
        }
        async emulateTimezone(timezoneId) {
          return await this.#frame.browsingContext.setTimezoneOverride(timezoneId);
        }
        async emulateIdleState(overrides) {
          return await this.#cdpEmulationManager.emulateIdleState(overrides);
        }
        async emulateVisionDeficiency(type) {
          return await this.#cdpEmulationManager.emulateVisionDeficiency(type);
        }
        async setViewport(viewport) {
          let needsReload = false;
          if (!this.browser().cdpSupported) {
            const viewportSize = viewport?.width && viewport?.height ? {
              width: viewport.width,
              height: viewport.height
            } : null;
            const devicePixelRatio = viewport?.deviceScaleFactor ? viewport.deviceScaleFactor : null;
            const screenOrientation = viewport ? viewport.isLandscape ? {
              natural: "landscape",
              type: "landscape-primary"
            } : {
              natural: "portrait",
              type: "portrait-primary"
            } : null;
            const commands = [
              this.#frame.browsingContext.setViewport({
                viewport: viewportSize,
                devicePixelRatio
              }),
              this.#frame.browsingContext.setScreenOrientationOverride(screenOrientation)
            ];
            if ((this.#viewport?.hasTouch ?? false) !== (viewport?.hasTouch ?? false)) {
              needsReload = true;
              const maxTouchPoints = viewport?.hasTouch ? 1 : null;
              commands.push(this.#frame.browsingContext.setTouchOverride(maxTouchPoints).catch((error) => {
                if (error instanceof Errors_js_1.ProtocolError && (error.message.includes("unknown command") || error.message.includes("unsupported operation"))) {
                  return;
                }
                throw error;
              }));
            }
            await Promise.all(commands);
          } else {
            needsReload = await this.#cdpEmulationManager.emulateViewport(viewport);
          }
          this.#viewport = viewport;
          if (needsReload) {
            await this.reload();
          }
        }
        viewport() {
          return this.#viewport;
        }
        async pdf(options = {}) {
          const { timeout: ms = this._timeoutSettings.timeout(), path: path2 = void 0 } = options;
          const { printBackground: background, margin, landscape, width, height, pageRanges: ranges, scale, preferCSSPageSize } = (0, util_js_1.parsePDFOptions)(options, "cm");
          const pageRanges = ranges ? ranges.split(", ") : [];
          await (0, rxjs_js_1.firstValueFrom)((0, rxjs_js_1.from)(this.mainFrame().isolatedRealm().evaluate(() => {
            return document.fonts.ready;
          })).pipe((0, rxjs_js_1.raceWith)((0, util_js_1.timeout)(ms))));
          const data = await (0, rxjs_js_1.firstValueFrom)((0, rxjs_js_1.from)(this.#frame.browsingContext.print({
            background,
            margin,
            orientation: landscape ? "landscape" : "portrait",
            page: {
              width,
              height
            },
            pageRanges,
            scale,
            shrinkToFit: !preferCSSPageSize
          })).pipe((0, rxjs_js_1.raceWith)((0, util_js_1.timeout)(ms))));
          const typedArray = (0, encoding_js_1.stringToTypedArray)(data, true);
          await this._maybeWriteTypedArrayToFile(path2, typedArray);
          return typedArray;
        }
        async createPDFStream(options) {
          const typedArray = await this.pdf(options);
          return new ReadableStream({
            start(controller) {
              controller.enqueue(typedArray);
              controller.close();
            }
          });
        }
        async _screenshot(options) {
          const { clip, type, captureBeyondViewport, quality } = options;
          if (options.omitBackground !== void 0 && options.omitBackground) {
            throw new Errors_js_1.UnsupportedOperation(`BiDi does not support 'omitBackground'.`);
          }
          if (options.optimizeForSpeed !== void 0 && options.optimizeForSpeed) {
            throw new Errors_js_1.UnsupportedOperation(`BiDi does not support 'optimizeForSpeed'.`);
          }
          if (options.fromSurface !== void 0 && !options.fromSurface) {
            throw new Errors_js_1.UnsupportedOperation(`BiDi does not support 'fromSurface'.`);
          }
          if (clip !== void 0 && clip.scale !== void 0 && clip.scale !== 1) {
            throw new Errors_js_1.UnsupportedOperation(`BiDi does not support 'scale' in 'clip'.`);
          }
          let box;
          if (clip) {
            if (captureBeyondViewport) {
              box = clip;
            } else {
              const [pageLeft, pageTop] = await this.evaluate(() => {
                if (!window.visualViewport) {
                  throw new Error("window.visualViewport is not supported.");
                }
                return [
                  window.visualViewport.pageLeft,
                  window.visualViewport.pageTop
                ];
              });
              box = {
                ...clip,
                x: clip.x - pageLeft,
                y: clip.y - pageTop
              };
            }
          }
          const data = await this.#frame.browsingContext.captureScreenshot({
            origin: captureBeyondViewport ? "document" : "viewport",
            format: {
              type: `image/${type}`,
              ...quality !== void 0 ? { quality: quality / 100 } : {}
            },
            ...box ? { clip: { type: "box", ...box } } : {}
          });
          return data;
        }
        async createCDPSession() {
          return await this.#frame.createCDPSession();
        }
        async bringToFront() {
          await this.#frame.browsingContext.activate();
        }
        async evaluateOnNewDocument(pageFunction, ...args2) {
          const expression = evaluationExpression(pageFunction, ...args2);
          const script = await this.#frame.browsingContext.addPreloadScript(expression);
          return { identifier: script };
        }
        async removeScriptToEvaluateOnNewDocument(id) {
          await this.#frame.browsingContext.removePreloadScript(id);
        }
        async exposeFunction(name, pptrFunction) {
          return await this.mainFrame().exposeFunction(name, "default" in pptrFunction ? pptrFunction.default : pptrFunction);
        }
        isDragInterceptionEnabled() {
          return false;
        }
        async setCacheEnabled(enabled) {
          if (!this.#browserContext.browser().cdpSupported) {
            await this.#frame.browsingContext.setCacheBehavior(enabled ? "default" : "bypass");
            return;
          }
          await this._client().send("Network.setCacheDisabled", {
            cacheDisabled: !enabled
          });
        }
        async cookies(...urls) {
          const normalizedUrls = (urls.length ? urls : [this.url()]).map((url) => {
            return new URL(url);
          });
          const cookies = await this.#frame.browsingContext.getCookies();
          return cookies.map((cookie) => {
            return bidiToPuppeteerCookie(cookie);
          }).filter((cookie) => {
            return normalizedUrls.some((url) => {
              return testUrlMatchCookie(cookie, url);
            });
          });
        }
        isServiceWorkerBypassed() {
          throw new Errors_js_1.UnsupportedOperation();
        }
        target() {
          throw new Errors_js_1.UnsupportedOperation();
        }
        async waitForFileChooser(options = {}) {
          const { timeout = this._timeoutSettings.timeout() } = options;
          const deferred = Deferred_js_1.Deferred.create({
            message: `Waiting for \`FileChooser\` failed: ${timeout}ms exceeded`,
            timeout
          });
          this.#fileChooserDeferreds.add(deferred);
          if (options.signal) {
            options.signal.addEventListener("abort", () => {
              deferred.reject(options.signal?.reason);
            }, { once: true });
          }
          this.#frame.browsingContext.once("filedialogopened", (info) => {
            if (!info.element) {
              return;
            }
            const chooser = new FileChooser_js_1.FileChooser(ElementHandle_js_1.BidiElementHandle.from({
              sharedId: info.element.sharedId,
              handle: info.element.handle,
              type: "node"
            }, this.#frame.mainRealm()), info.multiple);
            for (const deferred2 of this.#fileChooserDeferreds) {
              deferred2.resolve(chooser);
              this.#fileChooserDeferreds.delete(deferred2);
            }
          });
          try {
            return await deferred.valueOrThrow();
          } catch (error) {
            this.#fileChooserDeferreds.delete(deferred);
            throw error;
          }
        }
        workers() {
          return [...this.#workers];
        }
        get isNetworkInterceptionEnabled() {
          return Boolean(this.#requestInterception) || Boolean(this.#authInterception);
        }
        #requestInterception;
        async setRequestInterception(enable) {
          this.#requestInterception = await this.#toggleInterception([
            "beforeRequestSent"
            /* Bidi.Network.InterceptPhase.BeforeRequestSent */
          ], this.#requestInterception, enable);
        }
        /**
         * @internal
         */
        async setExtraHTTPHeaders(headers) {
          await this.#frame.browsingContext.setExtraHTTPHeaders(headers);
        }
        /**
         * @internal
         */
        _credentials = null;
        #authInterception;
        async authenticate(credentials) {
          this.#authInterception = await this.#toggleInterception([
            "authRequired"
            /* Bidi.Network.InterceptPhase.AuthRequired */
          ], this.#authInterception, Boolean(credentials));
          this._credentials = credentials;
        }
        async #toggleInterception(phases, interception, expected) {
          if (expected && !interception) {
            return await this.#frame.browsingContext.addIntercept({
              phases
            });
          } else if (!expected && interception) {
            await this.#frame.browsingContext.userContext.browser.removeIntercept(interception);
            return;
          }
          return interception;
        }
        setDragInterception() {
          throw new Errors_js_1.UnsupportedOperation();
        }
        setBypassServiceWorker() {
          throw new Errors_js_1.UnsupportedOperation();
        }
        async setOfflineMode(enabled) {
          if (!this.#browserContext.browser().cdpSupported) {
            return await this.#frame.browsingContext.setOfflineMode(enabled);
          }
          if (!this.#emulatedNetworkConditions) {
            this.#emulatedNetworkConditions = {
              offline: false,
              upload: -1,
              download: -1,
              latency: 0
            };
          }
          this.#emulatedNetworkConditions.offline = enabled;
          return await this.#applyNetworkConditions();
        }
        async emulateNetworkConditions(networkConditions) {
          if (!this.#browserContext.browser().cdpSupported) {
            if (!networkConditions?.offline && ((networkConditions?.upload ?? -1) >= 0 || (networkConditions?.download ?? -1) >= 0 || (networkConditions?.latency ?? 0) > 0)) {
              throw new Errors_js_1.UnsupportedOperation();
            }
            return await this.#frame.browsingContext.setOfflineMode(networkConditions?.offline ?? false);
          }
          if (!this.#emulatedNetworkConditions) {
            this.#emulatedNetworkConditions = {
              offline: networkConditions?.offline ?? false,
              upload: -1,
              download: -1,
              latency: 0
            };
          }
          this.#emulatedNetworkConditions.upload = networkConditions ? networkConditions.upload : -1;
          this.#emulatedNetworkConditions.download = networkConditions ? networkConditions.download : -1;
          this.#emulatedNetworkConditions.latency = networkConditions ? networkConditions.latency : 0;
          this.#emulatedNetworkConditions.offline = networkConditions?.offline ?? false;
          return await this.#applyNetworkConditions();
        }
        async #applyNetworkConditions() {
          if (!this.#emulatedNetworkConditions) {
            return;
          }
          await this._client().send("Network.emulateNetworkConditions", {
            offline: this.#emulatedNetworkConditions.offline,
            latency: this.#emulatedNetworkConditions.latency,
            uploadThroughput: this.#emulatedNetworkConditions.upload,
            downloadThroughput: this.#emulatedNetworkConditions.download
          });
        }
        async setCookie(...cookies) {
          const pageURL = this.url();
          const pageUrlStartsWithHTTP = pageURL.startsWith("http");
          for (const cookie of cookies) {
            let cookieUrl = cookie.url || "";
            if (!cookieUrl && pageUrlStartsWithHTTP) {
              cookieUrl = pageURL;
            }
            (0, assert_js_1.assert)(cookieUrl !== "about:blank", `Blank page can not have cookie "${cookie.name}"`);
            (0, assert_js_1.assert)(!String.prototype.startsWith.call(cookieUrl || "", "data:"), `Data URL page can not have cookie "${cookie.name}"`);
            (0, assert_js_1.assert)(cookie.partitionKey === void 0 || typeof cookie.partitionKey === "string", "BiDi only allows domain partition keys");
            const normalizedUrl = URL.canParse(cookieUrl) ? new URL(cookieUrl) : void 0;
            const domain = cookie.domain ?? normalizedUrl?.hostname;
            (0, assert_js_1.assert)(domain !== void 0, `At least one of the url and domain needs to be specified`);
            const bidiCookie = {
              domain,
              name: cookie.name,
              value: {
                type: "string",
                value: cookie.value
              },
              ...cookie.path !== void 0 ? { path: cookie.path } : {},
              ...cookie.httpOnly !== void 0 ? { httpOnly: cookie.httpOnly } : {},
              ...cookie.secure !== void 0 ? { secure: cookie.secure } : {},
              ...cookie.sameSite !== void 0 ? { sameSite: convertCookiesSameSiteCdpToBiDi(cookie.sameSite) } : {},
              ...{ expiry: convertCookiesExpiryCdpToBiDi(cookie.expires) },
              // Chrome-specific properties.
              ...cdpSpecificCookiePropertiesFromPuppeteerToBidi(cookie, "sameParty", "sourceScheme", "priority", "url")
            };
            if (cookie.partitionKey !== void 0) {
              await this.browserContext().userContext.setCookie(bidiCookie, cookie.partitionKey);
            } else {
              await this.#frame.browsingContext.setCookie(bidiCookie);
            }
          }
        }
        async deleteCookie(...cookies) {
          await Promise.all(cookies.map(async (deleteCookieRequest) => {
            const cookieUrl = deleteCookieRequest.url ?? this.url();
            const normalizedUrl = URL.canParse(cookieUrl) ? new URL(cookieUrl) : void 0;
            const domain = deleteCookieRequest.domain ?? normalizedUrl?.hostname;
            (0, assert_js_1.assert)(domain !== void 0, `At least one of the url and domain needs to be specified`);
            const filter = {
              domain,
              name: deleteCookieRequest.name,
              ...deleteCookieRequest.path !== void 0 ? { path: deleteCookieRequest.path } : {}
            };
            await this.#frame.browsingContext.deleteCookie(filter);
          }));
        }
        async removeExposedFunction(name) {
          await this.#frame.removeExposedFunction(name);
        }
        metrics() {
          throw new Errors_js_1.UnsupportedOperation();
        }
        async captureHeapSnapshot(_options) {
          throw new Errors_js_1.UnsupportedOperation();
        }
        async goBack(options = {}) {
          return await this.#go(-1, options);
        }
        async goForward(options = {}) {
          return await this.#go(1, options);
        }
        async #go(delta, options) {
          const controller = new AbortController();
          try {
            const [response] = await Promise.all([
              this.waitForNavigation({
                ...options,
                signal: controller.signal
              }),
              this.#frame.browsingContext.traverseHistory(delta)
            ]);
            return response;
          } catch (error) {
            controller.abort();
            throw error;
          }
        }
        async waitForDevicePrompt(options = {}) {
          return await this.mainFrame().waitForDevicePrompt(options);
        }
        get bluetooth() {
          return this.mainFrame().browsingContext.bluetooth;
        }
      };
    })();
    exports2.BidiPage = BidiPage;
    function evaluationExpression(fun, ...args2) {
      return `() => {${(0, util_js_1.evaluationString)(fun, ...args2)}}`;
    }
    function testUrlMatchCookieHostname(cookie, normalizedUrl) {
      const cookieDomain = cookie.domain.toLowerCase();
      const urlHostname = normalizedUrl.hostname.toLowerCase();
      if (cookieDomain === urlHostname) {
        return true;
      }
      return cookieDomain.startsWith(".") && urlHostname.endsWith(cookieDomain);
    }
    function testUrlMatchCookiePath(cookie, normalizedUrl) {
      const uriPath = normalizedUrl.pathname;
      const cookiePath = cookie.path;
      if (uriPath === cookiePath) {
        return true;
      }
      if (uriPath.startsWith(cookiePath)) {
        if (cookiePath.endsWith("/")) {
          return true;
        }
        if (uriPath[cookiePath.length] === "/") {
          return true;
        }
      }
      return false;
    }
    function testUrlMatchCookie(cookie, url) {
      const normalizedUrl = new URL(url);
      (0, assert_js_1.assert)(cookie !== void 0);
      if (!testUrlMatchCookieHostname(cookie, normalizedUrl)) {
        return false;
      }
      return testUrlMatchCookiePath(cookie, normalizedUrl);
    }
    function bidiToPuppeteerCookie(bidiCookie, returnCompositePartitionKey = false) {
      const partitionKey = bidiCookie[CDP_SPECIFIC_PREFIX + "partitionKey"];
      function getPartitionKey() {
        if (typeof partitionKey === "string") {
          return { partitionKey };
        }
        if (typeof partitionKey === "object" && partitionKey !== null) {
          if (returnCompositePartitionKey) {
            return {
              partitionKey: {
                sourceOrigin: partitionKey.topLevelSite,
                hasCrossSiteAncestor: partitionKey.hasCrossSiteAncestor ?? false
              }
            };
          }
          return {
            // TODO: a breaking change in Puppeteer is required to change
            // partitionKey type and report the composite partition key.
            partitionKey: partitionKey.topLevelSite
          };
        }
        return {};
      }
      return {
        name: bidiCookie.name,
        // Presents binary value as base64 string.
        value: bidiCookie.value.value,
        domain: bidiCookie.domain,
        path: bidiCookie.path,
        size: bidiCookie.size,
        httpOnly: bidiCookie.httpOnly,
        secure: bidiCookie.secure,
        sameSite: convertCookiesSameSiteBiDiToCdp(bidiCookie.sameSite),
        expires: bidiCookie.expiry ?? -1,
        session: bidiCookie.expiry === void 0 || bidiCookie.expiry <= 0,
        // Extending with CDP-specific properties with `goog:` prefix.
        ...cdpSpecificCookiePropertiesFromBidiToPuppeteer(bidiCookie, "sameParty", "sourceScheme", "partitionKeyOpaque", "priority"),
        ...getPartitionKey()
      };
    }
    var CDP_SPECIFIC_PREFIX = "goog:";
    function cdpSpecificCookiePropertiesFromBidiToPuppeteer(bidiCookie, ...propertyNames) {
      const result = {};
      for (const property of propertyNames) {
        if (bidiCookie[CDP_SPECIFIC_PREFIX + property] !== void 0) {
          result[property] = bidiCookie[CDP_SPECIFIC_PREFIX + property];
        }
      }
      if (!result.sameParty) {
        result.sameParty = false;
      }
      return result;
    }
    function cdpSpecificCookiePropertiesFromPuppeteerToBidi(cookieParam, ...propertyNames) {
      const result = {};
      for (const property of propertyNames) {
        if (cookieParam[property] !== void 0) {
          result[CDP_SPECIFIC_PREFIX + property] = cookieParam[property];
        }
      }
      return result;
    }
    function convertCookiesSameSiteBiDiToCdp(sameSite) {
      switch (sameSite) {
        case "strict":
          return "Strict";
        case "lax":
          return "Lax";
        case "none":
          return "None";
        default:
          return "Default";
      }
    }
    function convertCookiesSameSiteCdpToBiDi(sameSite) {
      switch (sameSite) {
        case "Strict":
          return "strict";
        case "Lax":
          return "lax";
        case "None":
          return "none";
        default:
          return "default";
      }
    }
    function convertCookiesExpiryCdpToBiDi(expiry) {
      return [void 0, -1].includes(expiry) ? void 0 : expiry;
    }
    function convertCookiesPartitionKeyFromPuppeteerToBiDi(partitionKey) {
      if (partitionKey === void 0 || typeof partitionKey === "string") {
        return partitionKey;
      }
      if (partitionKey.hasCrossSiteAncestor) {
        throw new Errors_js_1.UnsupportedOperation("WebDriver BiDi does not support `hasCrossSiteAncestor` yet.");
      }
      return partitionKey.sourceOrigin;
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Target.js
var require_Target3 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Target.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiWorkerTarget = exports2.BidiFrameTarget = exports2.BidiPageTarget = exports2.BidiBrowserTarget = void 0;
    var Target_js_1 = require_Target();
    var Errors_js_1 = require_Errors();
    var Page_js_1 = require_Page3();
    var BidiBrowserTarget = class extends Target_js_1.Target {
      #browser;
      constructor(browser) {
        super();
        this.#browser = browser;
      }
      asPage() {
        throw new Errors_js_1.UnsupportedOperation();
      }
      url() {
        return "";
      }
      createCDPSession() {
        throw new Errors_js_1.UnsupportedOperation();
      }
      type() {
        return Target_js_1.TargetType.BROWSER;
      }
      browser() {
        return this.#browser;
      }
      browserContext() {
        return this.#browser.defaultBrowserContext();
      }
      opener() {
        throw new Errors_js_1.UnsupportedOperation();
      }
    };
    exports2.BidiBrowserTarget = BidiBrowserTarget;
    var BidiPageTarget = class extends Target_js_1.Target {
      #page;
      constructor(page2) {
        super();
        this.#page = page2;
      }
      async page() {
        return this.#page;
      }
      async asPage() {
        return Page_js_1.BidiPage.from(this.browserContext(), this.#page.mainFrame().browsingContext);
      }
      url() {
        return this.#page.url();
      }
      createCDPSession() {
        return this.#page.createCDPSession();
      }
      type() {
        return Target_js_1.TargetType.PAGE;
      }
      browser() {
        return this.browserContext().browser();
      }
      browserContext() {
        return this.#page.browserContext();
      }
      opener() {
        throw new Errors_js_1.UnsupportedOperation();
      }
    };
    exports2.BidiPageTarget = BidiPageTarget;
    var BidiFrameTarget = class extends Target_js_1.Target {
      #frame;
      #page;
      constructor(frame) {
        super();
        this.#frame = frame;
      }
      async page() {
        if (this.#page === void 0) {
          this.#page = Page_js_1.BidiPage.from(this.browserContext(), this.#frame.browsingContext);
        }
        return this.#page;
      }
      async asPage() {
        return Page_js_1.BidiPage.from(this.browserContext(), this.#frame.browsingContext);
      }
      url() {
        return this.#frame.url();
      }
      createCDPSession() {
        return this.#frame.createCDPSession();
      }
      type() {
        return Target_js_1.TargetType.PAGE;
      }
      browser() {
        return this.browserContext().browser();
      }
      browserContext() {
        return this.#frame.page().browserContext();
      }
      opener() {
        throw new Errors_js_1.UnsupportedOperation();
      }
    };
    exports2.BidiFrameTarget = BidiFrameTarget;
    var BidiWorkerTarget = class extends Target_js_1.Target {
      #worker;
      constructor(worker) {
        super();
        this.#worker = worker;
      }
      async page() {
        throw new Errors_js_1.UnsupportedOperation();
      }
      async asPage() {
        throw new Errors_js_1.UnsupportedOperation();
      }
      url() {
        return this.#worker.url();
      }
      createCDPSession() {
        throw new Errors_js_1.UnsupportedOperation();
      }
      type() {
        return Target_js_1.TargetType.OTHER;
      }
      browser() {
        return this.browserContext().browser();
      }
      browserContext() {
        return this.#worker.frame.page().browserContext();
      }
      opener() {
        throw new Errors_js_1.UnsupportedOperation();
      }
    };
    exports2.BidiWorkerTarget = BidiWorkerTarget;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/BrowserContext.js
var require_BrowserContext3 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/BrowserContext.js"(exports2) {
    "use strict";
    init_prefix();
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiBrowserContext = void 0;
    var Browser_js_1 = require_Browser();
    var BrowserContext_js_1 = require_BrowserContext();
    var Errors_js_1 = require_Errors();
    var EventEmitter_js_1 = require_EventEmitter();
    var util_js_1 = require_util();
    var assert_js_1 = require_assert();
    var decorators_js_1 = require_decorators();
    var UserContext_js_1 = require_UserContext();
    var Page_js_1 = require_Page3();
    var Target_js_1 = require_Target3();
    var Target_js_2 = require_Target3();
    var BidiBrowserContext = (() => {
      let _classSuper = BrowserContext_js_1.BrowserContext;
      let _trustedEmitter_decorators;
      let _trustedEmitter_initializers = [];
      let _trustedEmitter_extraInitializers = [];
      return class BidiBrowserContext2 extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          _trustedEmitter_decorators = [(0, decorators_js_1.bubble)()];
          __esDecorate2(this, null, _trustedEmitter_decorators, { kind: "accessor", name: "trustedEmitter", static: false, private: false, access: { has: (obj) => "trustedEmitter" in obj, get: (obj) => obj.trustedEmitter, set: (obj, value) => {
            obj.trustedEmitter = value;
          } }, metadata: _metadata }, _trustedEmitter_initializers, _trustedEmitter_extraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        static from(browser, userContext, options) {
          const context = new BidiBrowserContext2(browser, userContext, options);
          context.#initialize();
          return context;
        }
        #trustedEmitter_accessor_storage = __runInitializers2(this, _trustedEmitter_initializers, new EventEmitter_js_1.EventEmitter());
        get trustedEmitter() {
          return this.#trustedEmitter_accessor_storage;
        }
        set trustedEmitter(value) {
          this.#trustedEmitter_accessor_storage = value;
        }
        #browser = __runInitializers2(this, _trustedEmitter_extraInitializers);
        #defaultViewport;
        // This is public because of cookies.
        userContext;
        #pages = /* @__PURE__ */ new WeakMap();
        #targets = /* @__PURE__ */ new Map();
        #overrides = [];
        constructor(browser, userContext, options) {
          super();
          this.#browser = browser;
          this.userContext = userContext;
          this.#defaultViewport = options.defaultViewport;
        }
        #initialize() {
          for (const browsingContext of this.userContext.browsingContexts) {
            this.#createPage(browsingContext);
          }
          this.userContext.on("browsingcontext", ({ browsingContext }) => {
            const page2 = this.#createPage(browsingContext);
            if (browsingContext.originalOpener) {
              for (const context of this.userContext.browsingContexts) {
                if (context.id === browsingContext.originalOpener) {
                  this.#pages.get(context).trustedEmitter.emit("popup", page2);
                }
              }
            }
          });
          this.userContext.on("closed", () => {
            this.trustedEmitter.removeAllListeners();
          });
        }
        #createPage(browsingContext) {
          const page2 = Page_js_1.BidiPage.from(this, browsingContext);
          this.#pages.set(browsingContext, page2);
          page2.trustedEmitter.on("close", () => {
            this.#pages.delete(browsingContext);
          });
          const pageTarget = new Target_js_2.BidiPageTarget(page2);
          const pageTargets = /* @__PURE__ */ new Map();
          this.#targets.set(page2, [pageTarget, pageTargets]);
          page2.trustedEmitter.on("frameattached", (frame) => {
            const bidiFrame = frame;
            const target = new Target_js_2.BidiFrameTarget(bidiFrame);
            pageTargets.set(bidiFrame, target);
            this.trustedEmitter.emit("targetcreated", target);
          });
          page2.trustedEmitter.on("framenavigated", (frame) => {
            const bidiFrame = frame;
            const target = pageTargets.get(bidiFrame);
            if (target === void 0) {
              this.trustedEmitter.emit("targetchanged", pageTarget);
            } else {
              this.trustedEmitter.emit("targetchanged", target);
            }
          });
          page2.trustedEmitter.on("framedetached", (frame) => {
            const bidiFrame = frame;
            const target = pageTargets.get(bidiFrame);
            if (target === void 0) {
              return;
            }
            pageTargets.delete(bidiFrame);
            this.trustedEmitter.emit("targetdestroyed", target);
          });
          page2.trustedEmitter.on("workercreated", (worker) => {
            const bidiWorker = worker;
            const target = new Target_js_1.BidiWorkerTarget(bidiWorker);
            pageTargets.set(bidiWorker, target);
            this.trustedEmitter.emit("targetcreated", target);
          });
          page2.trustedEmitter.on("workerdestroyed", (worker) => {
            const bidiWorker = worker;
            const target = pageTargets.get(bidiWorker);
            if (target === void 0) {
              return;
            }
            pageTargets.delete(worker);
            this.trustedEmitter.emit("targetdestroyed", target);
          });
          page2.trustedEmitter.on("close", () => {
            this.#targets.delete(page2);
            this.trustedEmitter.emit("targetdestroyed", pageTarget);
          });
          this.trustedEmitter.emit("targetcreated", pageTarget);
          return page2;
        }
        targets() {
          return [...this.#targets.values()].flatMap(([target, frames]) => {
            return [target, ...frames.values()];
          });
        }
        async newPage(options) {
          const env_1 = { stack: [], error: void 0, hasError: false };
          try {
            const _guard = __addDisposableResource2(env_1, await this.waitForScreenshotOperations(), false);
            const type = options?.type === "window" ? "window" : "tab";
            const context = await this.userContext.createBrowsingContext(type, {
              background: options?.background
            });
            const page2 = this.#pages.get(context);
            if (!page2) {
              throw new Error("Page is not found");
            }
            if (this.#defaultViewport) {
              try {
                await page2.setViewport(this.#defaultViewport);
              } catch (error) {
                (0, util_js_1.debugError)(error);
              }
            }
            if (options?.type === "window" && options?.windowBounds !== void 0) {
              try {
                await this.browser().setWindowBounds(context.windowId, options.windowBounds);
              } catch (error) {
                (0, util_js_1.debugError)(error);
              }
            }
            return page2;
          } catch (e_1) {
            env_1.error = e_1;
            env_1.hasError = true;
          } finally {
            __disposeResources2(env_1);
          }
        }
        async close() {
          (0, assert_js_1.assert)(this.userContext.id !== UserContext_js_1.UserContext.DEFAULT, "Default BrowserContext cannot be closed!");
          try {
            await this.userContext.remove();
          } catch (error) {
            (0, util_js_1.debugError)(error);
          }
          this.#targets.clear();
        }
        browser() {
          return this.#browser;
        }
        async pages(_includeAll = false) {
          return [...this.userContext.browsingContexts].map((context) => {
            return this.#pages.get(context);
          });
        }
        async overridePermissions(origin, permissions) {
          const permissionsSet = new Set(permissions.map((permission) => {
            const protocolPermission = Browser_js_1.WEB_PERMISSION_TO_PROTOCOL_PERMISSION.get(permission);
            if (!protocolPermission) {
              throw new Error("Unknown permission: " + permission);
            }
            return permission;
          }));
          await Promise.all(Array.from(Browser_js_1.WEB_PERMISSION_TO_PROTOCOL_PERMISSION.keys()).map((permission) => {
            const result = this.userContext.setPermissions(
              origin,
              {
                name: permission
              },
              permissionsSet.has(permission) ? "granted" : "denied"
              /* Bidi.Permissions.PermissionState.Denied */
            );
            this.#overrides.push({ origin, permission });
            if (!permissionsSet.has(permission)) {
              return result.catch(util_js_1.debugError);
            }
            return result;
          }));
        }
        async setPermission(origin, ...permissions) {
          if (origin === "*") {
            throw new Errors_js_1.UnsupportedOperation("Origin (*) is not supported by WebDriver BiDi");
          }
          await Promise.all(permissions.map((permission) => {
            if (permission.permission.allowWithoutSanitization) {
              throw new Errors_js_1.UnsupportedOperation("allowWithoutSanitization is not supported by WebDriver BiDi");
            }
            if (permission.permission.panTiltZoom) {
              throw new Errors_js_1.UnsupportedOperation("panTiltZoom is not supported by WebDriver BiDi");
            }
            if (permission.permission.userVisibleOnly) {
              throw new Errors_js_1.UnsupportedOperation("userVisibleOnly is not supported by WebDriver BiDi");
            }
            return this.userContext.setPermissions(origin, {
              name: permission.permission.name
            }, permission.state);
          }));
        }
        async clearPermissionOverrides() {
          const promises = this.#overrides.map(({ permission, origin }) => {
            return this.userContext.setPermissions(
              origin,
              {
                name: permission
              },
              "prompt"
              /* Bidi.Permissions.PermissionState.Prompt */
            ).catch(util_js_1.debugError);
          });
          this.#overrides = [];
          await Promise.all(promises);
        }
        get id() {
          if (this.userContext.id === UserContext_js_1.UserContext.DEFAULT) {
            return void 0;
          }
          return this.userContext.id;
        }
        async cookies() {
          const cookies = await this.userContext.getCookies();
          return cookies.map((cookie) => {
            return (0, Page_js_1.bidiToPuppeteerCookie)(cookie, true);
          });
        }
        async setCookie(...cookies) {
          await Promise.all(cookies.map(async (cookie) => {
            const bidiCookie = {
              domain: cookie.domain,
              name: cookie.name,
              value: {
                type: "string",
                value: cookie.value
              },
              ...cookie.path !== void 0 ? { path: cookie.path } : {},
              ...cookie.httpOnly !== void 0 ? { httpOnly: cookie.httpOnly } : {},
              ...cookie.secure !== void 0 ? { secure: cookie.secure } : {},
              ...cookie.sameSite !== void 0 ? { sameSite: (0, Page_js_1.convertCookiesSameSiteCdpToBiDi)(cookie.sameSite) } : {},
              ...{ expiry: (0, Page_js_1.convertCookiesExpiryCdpToBiDi)(cookie.expires) },
              // Chrome-specific properties.
              ...(0, Page_js_1.cdpSpecificCookiePropertiesFromPuppeteerToBidi)(cookie, "sameParty", "sourceScheme", "priority", "url")
            };
            return await this.userContext.setCookie(bidiCookie, (0, Page_js_1.convertCookiesPartitionKeyFromPuppeteerToBiDi)(cookie.partitionKey));
          }));
        }
      };
    })();
    exports2.BidiBrowserContext = BidiBrowserContext;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/core/Browser.js
var require_Browser3 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/core/Browser.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    var __addDisposableResource2 = exports2 && exports2.__addDisposableResource || function(env2, 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);
          }
        };
        env2.stack.push({ value, dispose, async });
      } else if (async) {
        env2.stack.push({ async: true });
      }
      return value;
    };
    var __disposeResources2 = exports2 && exports2.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
      return function(env2) {
        function fail(e) {
          env2.error = env2.hasError ? new SuppressedError2(e, env2.error, "An error was suppressed during disposal.") : e;
          env2.hasError = true;
        }
        var r, s = 0;
        function next() {
          while (r = env2.stack.pop()) {
            try {
              if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
              if (r.dispose) {
                var result = r.dispose.call(r.value);
                if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
                  fail(e);
                  return next();
                });
              } else s |= 1;
            } catch (e) {
              fail(e);
            }
          }
          if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
          if (env2.hasError) throw env2.error;
        }
        return next();
      };
    })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    });
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Browser = void 0;
    var Errors_js_1 = require_Errors();
    var EventEmitter_js_1 = require_EventEmitter();
    var decorators_js_1 = require_decorators();
    var disposable_js_1 = require_disposable();
    var Realm_js_1 = require_Realm3();
    var UserContext_js_1 = require_UserContext();
    var Browser = (() => {
      let _classSuper = EventEmitter_js_1.EventEmitter;
      let _instanceExtraInitializers = [];
      let _dispose_decorators;
      let _close_decorators;
      let _addPreloadScript_decorators;
      let _removeIntercept_decorators;
      let _removePreloadScript_decorators;
      let _createUserContext_decorators;
      let _installExtension_decorators;
      let _uninstallExtension_decorators;
      let _setClientWindowState_decorators;
      let _getClientWindowInfo_decorators;
      return class Browser2 extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          __esDecorate2(this, null, _dispose_decorators, { kind: "method", name: "dispose", static: false, private: false, access: { has: (obj) => "dispose" in obj, get: (obj) => obj.dispose }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _close_decorators, { kind: "method", name: "close", static: false, private: false, access: { has: (obj) => "close" in obj, get: (obj) => obj.close }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _addPreloadScript_decorators, { kind: "method", name: "addPreloadScript", static: false, private: false, access: { has: (obj) => "addPreloadScript" in obj, get: (obj) => obj.addPreloadScript }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _removeIntercept_decorators, { kind: "method", name: "removeIntercept", static: false, private: false, access: { has: (obj) => "removeIntercept" in obj, get: (obj) => obj.removeIntercept }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _removePreloadScript_decorators, { kind: "method", name: "removePreloadScript", static: false, private: false, access: { has: (obj) => "removePreloadScript" in obj, get: (obj) => obj.removePreloadScript }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _createUserContext_decorators, { kind: "method", name: "createUserContext", static: false, private: false, access: { has: (obj) => "createUserContext" in obj, get: (obj) => obj.createUserContext }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _installExtension_decorators, { kind: "method", name: "installExtension", static: false, private: false, access: { has: (obj) => "installExtension" in obj, get: (obj) => obj.installExtension }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _uninstallExtension_decorators, { kind: "method", name: "uninstallExtension", static: false, private: false, access: { has: (obj) => "uninstallExtension" in obj, get: (obj) => obj.uninstallExtension }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _setClientWindowState_decorators, { kind: "method", name: "setClientWindowState", static: false, private: false, access: { has: (obj) => "setClientWindowState" in obj, get: (obj) => obj.setClientWindowState }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _getClientWindowInfo_decorators, { kind: "method", name: "getClientWindowInfo", static: false, private: false, access: { has: (obj) => "getClientWindowInfo" in obj, get: (obj) => obj.getClientWindowInfo }, metadata: _metadata }, null, _instanceExtraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        static async from(session) {
          const browser = new Browser2(session);
          await browser.#initialize();
          return browser;
        }
        #closed = (__runInitializers2(this, _instanceExtraInitializers), false);
        #reason;
        #disposables = new disposable_js_1.DisposableStack();
        #userContexts = /* @__PURE__ */ new Map();
        session;
        #sharedWorkers = /* @__PURE__ */ new Map();
        constructor(session) {
          super();
          this.session = session;
        }
        async #initialize() {
          const sessionEmitter = this.#disposables.use(new EventEmitter_js_1.EventEmitter(this.session));
          sessionEmitter.once("ended", ({ reason }) => {
            this.dispose(reason);
          });
          sessionEmitter.on("script.realmCreated", (info) => {
            if (info.type !== "shared-worker") {
              return;
            }
            this.#sharedWorkers.set(info.realm, Realm_js_1.SharedWorkerRealm.from(this, info.realm, info.origin));
          });
          await this.#syncUserContexts();
          await this.#syncBrowsingContexts();
        }
        async #syncUserContexts() {
          const { result: { userContexts } } = await this.session.send("browser.getUserContexts", {});
          for (const context of userContexts) {
            this.#createUserContext(context.userContext);
          }
        }
        async #syncBrowsingContexts() {
          const contextIds = /* @__PURE__ */ new Set();
          let contexts;
          {
            const env_1 = { stack: [], error: void 0, hasError: false };
            try {
              const sessionEmitter = __addDisposableResource2(env_1, new EventEmitter_js_1.EventEmitter(this.session), false);
              sessionEmitter.on("browsingContext.contextCreated", (info) => {
                contextIds.add(info.context);
              });
              const { result } = await this.session.send("browsingContext.getTree", {});
              contexts = result.contexts;
            } catch (e_1) {
              env_1.error = e_1;
              env_1.hasError = true;
            } finally {
              __disposeResources2(env_1);
            }
          }
          for (const info of contexts) {
            if (!contextIds.has(info.context)) {
              this.session.emit("browsingContext.contextCreated", info);
            }
            if (info.children) {
              contexts.push(...info.children);
            }
          }
        }
        #createUserContext(id) {
          const userContext = UserContext_js_1.UserContext.create(this, id);
          this.#userContexts.set(userContext.id, userContext);
          const userContextEmitter = this.#disposables.use(new EventEmitter_js_1.EventEmitter(userContext));
          userContextEmitter.once("closed", () => {
            userContextEmitter.removeAllListeners();
            this.#userContexts.delete(userContext.id);
          });
          return userContext;
        }
        get closed() {
          return this.#closed;
        }
        get defaultUserContext() {
          return this.#userContexts.get(UserContext_js_1.UserContext.DEFAULT);
        }
        get disconnected() {
          return this.#reason !== void 0;
        }
        get disposed() {
          return this.disconnected;
        }
        get userContexts() {
          return this.#userContexts.values();
        }
        dispose(reason, closed = false) {
          this.#closed = closed;
          this.#reason = reason;
          this[disposable_js_1.disposeSymbol]();
        }
        async close() {
          try {
            await this.session.send("browser.close", {});
          } finally {
            this.dispose("Browser already closed.", true);
          }
        }
        async addPreloadScript(functionDeclaration, options = {}) {
          const { result: { script } } = await this.session.send("script.addPreloadScript", {
            functionDeclaration,
            ...options,
            contexts: options.contexts?.map((context) => {
              return context.id;
            })
          });
          return script;
        }
        async removeIntercept(intercept) {
          await this.session.send("network.removeIntercept", {
            intercept
          });
        }
        async removePreloadScript(script) {
          await this.session.send("script.removePreloadScript", {
            script
          });
        }
        async createUserContext(options) {
          const proxyConfig = options.proxyServer === void 0 ? void 0 : {
            proxyType: "manual",
            httpProxy: options.proxyServer,
            sslProxy: options.proxyServer,
            noProxy: options.proxyBypassList
          };
          const { result: { userContext } } = await this.session.send("browser.createUserContext", {
            proxy: proxyConfig
          });
          if (options.downloadBehavior?.policy === "allowAndName") {
            throw new Errors_js_1.UnsupportedOperation("`allowAndName` is not supported in WebDriver BiDi");
          }
          if (options.downloadBehavior?.policy === "allow") {
            if (options.downloadBehavior.downloadPath === void 0) {
              throw new Errors_js_1.UnsupportedOperation("`downloadPath` is required in `allow` download behavior");
            }
            await this.session.send("browser.setDownloadBehavior", {
              downloadBehavior: {
                type: "allowed",
                destinationFolder: options.downloadBehavior.downloadPath
              },
              userContexts: [userContext]
            });
          }
          if (options.downloadBehavior?.policy === "deny") {
            await this.session.send("browser.setDownloadBehavior", {
              downloadBehavior: { type: "denied" },
              userContexts: [userContext]
            });
          }
          return this.#createUserContext(userContext);
        }
        async installExtension(path2) {
          const { result: { extension } } = await this.session.send("webExtension.install", {
            extensionData: { type: "path", path: path2 }
          });
          return extension;
        }
        async uninstallExtension(id) {
          await this.session.send("webExtension.uninstall", { extension: id });
        }
        async setClientWindowState(params) {
          await this.session.send("browser.setClientWindowState", params);
        }
        async getClientWindowInfo(windowId) {
          const { result: { clientWindows } } = await this.session.send("browser.getClientWindows", {});
          const window2 = clientWindows.find((window3) => {
            return window3.clientWindow === windowId;
          });
          if (!window2) {
            throw new Error("Window not found");
          }
          return window2;
        }
        [(_dispose_decorators = [decorators_js_1.inertIfDisposed], _close_decorators = [(0, decorators_js_1.throwIfDisposed)((browser) => {
          return browser.#reason;
        })], _addPreloadScript_decorators = [(0, decorators_js_1.throwIfDisposed)((browser) => {
          return browser.#reason;
        })], _removeIntercept_decorators = [(0, decorators_js_1.throwIfDisposed)((browser) => {
          return browser.#reason;
        })], _removePreloadScript_decorators = [(0, decorators_js_1.throwIfDisposed)((browser) => {
          return browser.#reason;
        })], _createUserContext_decorators = [(0, decorators_js_1.throwIfDisposed)((browser) => {
          return browser.#reason;
        })], _installExtension_decorators = [(0, decorators_js_1.throwIfDisposed)((browser) => {
          return browser.#reason;
        })], _uninstallExtension_decorators = [(0, decorators_js_1.throwIfDisposed)((browser) => {
          return browser.#reason;
        })], _setClientWindowState_decorators = [(0, decorators_js_1.throwIfDisposed)((browser) => {
          return browser.#reason;
        })], _getClientWindowInfo_decorators = [(0, decorators_js_1.throwIfDisposed)((browser) => {
          return browser.#reason;
        })], disposable_js_1.disposeSymbol)]() {
          this.#reason ??= "Browser was disconnected, probably because the session ended.";
          if (this.closed) {
            this.emit("closed", { reason: this.#reason });
          }
          this.emit("disconnected", { reason: this.#reason });
          this.#disposables.dispose();
          super[disposable_js_1.disposeSymbol]();
        }
      };
    })();
    exports2.Browser = Browser;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/core/Session.js
var require_Session = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/core/Session.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Session = void 0;
    var EventEmitter_js_1 = require_EventEmitter();
    var decorators_js_1 = require_decorators();
    var disposable_js_1 = require_disposable();
    var Browser_js_1 = require_Browser3();
    var Session = (() => {
      let _classSuper = EventEmitter_js_1.EventEmitter;
      let _instanceExtraInitializers = [];
      let _connection_decorators;
      let _connection_initializers = [];
      let _connection_extraInitializers = [];
      let _dispose_decorators;
      let _send_decorators;
      let _subscribe_decorators;
      let _addIntercepts_decorators;
      let _end_decorators;
      return class Session2 extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          __esDecorate2(this, null, _connection_decorators, { kind: "accessor", name: "connection", static: false, private: false, access: { has: (obj) => "connection" in obj, get: (obj) => obj.connection, set: (obj, value) => {
            obj.connection = value;
          } }, metadata: _metadata }, _connection_initializers, _connection_extraInitializers);
          __esDecorate2(this, null, _dispose_decorators, { kind: "method", name: "dispose", static: false, private: false, access: { has: (obj) => "dispose" in obj, get: (obj) => obj.dispose }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _send_decorators, { kind: "method", name: "send", static: false, private: false, access: { has: (obj) => "send" in obj, get: (obj) => obj.send }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _subscribe_decorators, { kind: "method", name: "subscribe", static: false, private: false, access: { has: (obj) => "subscribe" in obj, get: (obj) => obj.subscribe }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _addIntercepts_decorators, { kind: "method", name: "addIntercepts", static: false, private: false, access: { has: (obj) => "addIntercepts" in obj, get: (obj) => obj.addIntercepts }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _end_decorators, { kind: "method", name: "end", static: false, private: false, access: { has: (obj) => "end" in obj, get: (obj) => obj.end }, metadata: _metadata }, null, _instanceExtraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        static async from(connection, capabilities) {
          const { result } = await connection.send("session.new", {
            capabilities
          });
          const session = new Session2(connection, result);
          await session.#initialize();
          return session;
        }
        #reason = __runInitializers2(this, _instanceExtraInitializers);
        #disposables = new disposable_js_1.DisposableStack();
        #info;
        browser;
        #connection_accessor_storage = __runInitializers2(this, _connection_initializers, void 0);
        get connection() {
          return this.#connection_accessor_storage;
        }
        set connection(value) {
          this.#connection_accessor_storage = value;
        }
        constructor(connection, info) {
          super();
          __runInitializers2(this, _connection_extraInitializers);
          this.#info = info;
          this.connection = connection;
        }
        async #initialize() {
          this.browser = await Browser_js_1.Browser.from(this);
          const browserEmitter = this.#disposables.use(this.browser);
          browserEmitter.once("closed", ({ reason }) => {
            this.dispose(reason);
          });
          const seen = /* @__PURE__ */ new WeakSet();
          this.on("browsingContext.fragmentNavigated", (info) => {
            if (seen.has(info)) {
              return;
            }
            seen.add(info);
            this.emit("browsingContext.navigationStarted", info);
            this.emit("browsingContext.fragmentNavigated", info);
          });
        }
        get capabilities() {
          return this.#info.capabilities;
        }
        get disposed() {
          return this.ended;
        }
        get ended() {
          return this.#reason !== void 0;
        }
        get id() {
          return this.#info.sessionId;
        }
        dispose(reason) {
          this.#reason = reason;
          this[disposable_js_1.disposeSymbol]();
        }
        /**
         * Currently, there is a 1:1 relationship between the session and the
         * session. In the future, we might support multiple sessions and in that
         * case we always needs to make sure that the session for the right session
         * object is used, so we implement this method here, although it's not defined
         * in the spec.
         */
        async send(method, params) {
          return await this.connection.send(method, params);
        }
        async subscribe(events, contexts) {
          await this.send("session.subscribe", {
            events,
            contexts
          });
        }
        async addIntercepts(events, contexts) {
          await this.send("session.subscribe", {
            events,
            contexts
          });
        }
        async end() {
          try {
            await this.send("session.end", {});
          } finally {
            this.dispose(`Session already ended.`);
          }
        }
        [(_connection_decorators = [(0, decorators_js_1.bubble)()], _dispose_decorators = [decorators_js_1.inertIfDisposed], _send_decorators = [(0, decorators_js_1.throwIfDisposed)((session) => {
          return session.#reason;
        })], _subscribe_decorators = [(0, decorators_js_1.throwIfDisposed)((session) => {
          return session.#reason;
        })], _addIntercepts_decorators = [(0, decorators_js_1.throwIfDisposed)((session) => {
          return session.#reason;
        })], _end_decorators = [(0, decorators_js_1.throwIfDisposed)((session) => {
          return session.#reason;
        })], disposable_js_1.disposeSymbol)]() {
          this.#reason ??= "Session already destroyed, probably because the connection broke.";
          this.emit("ended", { reason: this.#reason });
          this.#disposables.dispose();
          super[disposable_js_1.disposeSymbol]();
        }
      };
    })();
    exports2.Session = Session;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Browser.js
var require_Browser4 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/Browser.js"(exports2) {
    "use strict";
    init_prefix();
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __setFunctionName2 = exports2 && exports2.__setFunctionName || function(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 });
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BidiBrowser = void 0;
    var Browser_js_1 = require_Browser();
    var Errors_js_1 = require_Errors();
    var EventEmitter_js_1 = require_EventEmitter();
    var util_js_1 = require_util();
    var decorators_js_1 = require_decorators();
    var BrowserContext_js_1 = require_BrowserContext3();
    var Session_js_1 = require_Session();
    var Target_js_1 = require_Target3();
    var BidiBrowser = (() => {
      let _classSuper = Browser_js_1.Browser;
      let _private_trustedEmitter_decorators;
      let _private_trustedEmitter_initializers = [];
      let _private_trustedEmitter_extraInitializers = [];
      let _private_trustedEmitter_descriptor;
      return class BidiBrowser2 extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          _private_trustedEmitter_decorators = [(0, decorators_js_1.bubble)()];
          __esDecorate2(this, _private_trustedEmitter_descriptor = { get: __setFunctionName2(function() {
            return this.#trustedEmitter_accessor_storage;
          }, "#trustedEmitter", "get"), set: __setFunctionName2(function(value) {
            this.#trustedEmitter_accessor_storage = value;
          }, "#trustedEmitter", "set") }, _private_trustedEmitter_decorators, { kind: "accessor", name: "#trustedEmitter", static: false, private: true, access: { has: (obj) => #trustedEmitter in obj, get: (obj) => obj.#trustedEmitter, set: (obj, value) => {
            obj.#trustedEmitter = value;
          } }, metadata: _metadata }, _private_trustedEmitter_initializers, _private_trustedEmitter_extraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        protocol = "webDriverBiDi";
        static subscribeModules = [
          "browsingContext",
          "network",
          "log",
          "script",
          "input"
        ];
        static subscribeCdpEvents = [
          // Coverage
          "goog:cdp.Debugger.scriptParsed",
          "goog:cdp.CSS.styleSheetAdded",
          "goog:cdp.Runtime.executionContextsCleared",
          // Tracing
          "goog:cdp.Tracing.tracingComplete",
          // TODO: subscribe to all CDP events in the future.
          "goog:cdp.Network.requestWillBeSent",
          "goog:cdp.Debugger.scriptParsed",
          "goog:cdp.Page.screencastFrame"
        ];
        static async create(opts) {
          const session = await Session_js_1.Session.from(opts.connection, {
            firstMatch: opts.capabilities?.firstMatch,
            alwaysMatch: {
              ...opts.capabilities?.alwaysMatch,
              // Capabilities that come from Puppeteer's API take precedence.
              acceptInsecureCerts: opts.acceptInsecureCerts,
              unhandledPromptBehavior: {
                default: "ignore"
              },
              webSocketUrl: true,
              // Puppeteer with WebDriver BiDi does not support prerendering
              // yet because WebDriver BiDi behavior is not specified. See
              // https://github.com/w3c/webdriver-bidi/issues/321.
              "goog:prerenderingDisabled": true,
              // TODO: remove after Puppeteer rolled Chrome to 142 after Oct 28, 2025.
              "goog:disableNetworkDurableMessages": true
            }
          });
          await session.subscribe((opts.cdpConnection ? [...BidiBrowser2.subscribeModules, ...BidiBrowser2.subscribeCdpEvents] : BidiBrowser2.subscribeModules).filter((module3) => {
            if (!opts.networkEnabled) {
              return module3 !== "network" && module3 !== "goog:cdp.Network.requestWillBeSent";
            }
            return true;
          }));
          await Promise.all([
            "request",
            "response"
            /* Bidi.Network.DataType.Response */
          ].map(
            // Data collectors might be not implemented for specific data type, so create them
            // separately and ignore protocol errors.
            async (dataType) => {
              try {
                await session.send("network.addDataCollector", {
                  dataTypes: [dataType],
                  // Buffer size of 20 MB is equivalent to the CDP:
                  maxEncodedDataSize: 2e7
                });
              } catch (err) {
                if (err instanceof Errors_js_1.ProtocolError) {
                  (0, util_js_1.debugError)(err);
                } else {
                  throw err;
                }
              }
            }
          ));
          const browser = new BidiBrowser2(session.browser, opts);
          browser.#initialize();
          return browser;
        }
        #trustedEmitter_accessor_storage = __runInitializers2(this, _private_trustedEmitter_initializers, new EventEmitter_js_1.EventEmitter());
        get #trustedEmitter() {
          return _private_trustedEmitter_descriptor.get.call(this);
        }
        set #trustedEmitter(value) {
          return _private_trustedEmitter_descriptor.set.call(this, value);
        }
        #process = __runInitializers2(this, _private_trustedEmitter_extraInitializers);
        #closeCallback;
        #browserCore;
        #defaultViewport;
        #browserContexts = /* @__PURE__ */ new WeakMap();
        #target = new Target_js_1.BidiBrowserTarget(this);
        #cdpConnection;
        #networkEnabled;
        constructor(browserCore, opts) {
          super();
          this.#process = opts.process;
          this.#closeCallback = opts.closeCallback;
          this.#browserCore = browserCore;
          this.#defaultViewport = opts.defaultViewport;
          this.#cdpConnection = opts.cdpConnection;
          this.#networkEnabled = opts.networkEnabled;
        }
        #initialize() {
          for (const userContext of this.#browserCore.userContexts) {
            this.#createBrowserContext(userContext);
          }
          this.#browserCore.once("disconnected", () => {
            this.#trustedEmitter.emit("disconnected", void 0);
            this.#trustedEmitter.removeAllListeners();
          });
          this.#process?.once("close", () => {
            this.#browserCore.dispose("Browser process exited.", true);
            this.connection.dispose();
          });
        }
        get #browserName() {
          return this.#browserCore.session.capabilities.browserName;
        }
        get #browserVersion() {
          return this.#browserCore.session.capabilities.browserVersion;
        }
        get cdpSupported() {
          return this.#cdpConnection !== void 0;
        }
        get cdpConnection() {
          return this.#cdpConnection;
        }
        async userAgent() {
          return this.#browserCore.session.capabilities.userAgent;
        }
        #createBrowserContext(userContext) {
          const browserContext = BrowserContext_js_1.BidiBrowserContext.from(this, userContext, {
            defaultViewport: this.#defaultViewport
          });
          this.#browserContexts.set(userContext, browserContext);
          browserContext.trustedEmitter.on("targetcreated", (target) => {
            this.#trustedEmitter.emit("targetcreated", target);
          });
          browserContext.trustedEmitter.on("targetchanged", (target) => {
            this.#trustedEmitter.emit("targetchanged", target);
          });
          browserContext.trustedEmitter.on("targetdestroyed", (target) => {
            this.#trustedEmitter.emit("targetdestroyed", target);
          });
          return browserContext;
        }
        get connection() {
          return this.#browserCore.session.connection;
        }
        wsEndpoint() {
          return this.connection.url;
        }
        async close() {
          if (this.connection.closed) {
            return;
          }
          try {
            await this.#browserCore.close();
            await this.#closeCallback?.call(null);
          } catch (error) {
            (0, util_js_1.debugError)(error);
          } finally {
            this.connection.dispose();
          }
        }
        get connected() {
          return !this.#browserCore.disconnected;
        }
        process() {
          return this.#process ?? null;
        }
        async createBrowserContext(options = {}) {
          const userContext = await this.#browserCore.createUserContext(options);
          return this.#createBrowserContext(userContext);
        }
        async version() {
          return `${this.#browserName}/${this.#browserVersion}`;
        }
        browserContexts() {
          return [...this.#browserCore.userContexts].map((context) => {
            return this.#browserContexts.get(context);
          });
        }
        defaultBrowserContext() {
          return this.#browserContexts.get(this.#browserCore.defaultUserContext);
        }
        newPage(options) {
          return this.defaultBrowserContext().newPage(options);
        }
        installExtension(path2) {
          return this.#browserCore.installExtension(path2);
        }
        async uninstallExtension(id) {
          await this.#browserCore.uninstallExtension(id);
        }
        screens() {
          throw new Errors_js_1.UnsupportedOperation();
        }
        addScreen(_params) {
          throw new Errors_js_1.UnsupportedOperation();
        }
        removeScreen(_screenId) {
          throw new Errors_js_1.UnsupportedOperation();
        }
        async getWindowBounds(windowId) {
          const clientWindowInfo = await this.#browserCore.getClientWindowInfo(windowId);
          return {
            left: clientWindowInfo.x,
            top: clientWindowInfo.y,
            width: clientWindowInfo.width,
            height: clientWindowInfo.height,
            windowState: clientWindowInfo.state
          };
        }
        async setWindowBounds(windowId, windowBounds) {
          let params;
          const windowState = windowBounds.windowState ?? "normal";
          if (windowState === "normal") {
            params = {
              clientWindow: windowId,
              state: "normal",
              x: windowBounds.left,
              y: windowBounds.top,
              width: windowBounds.width,
              height: windowBounds.height
            };
          } else {
            params = {
              clientWindow: windowId,
              state: windowState
            };
          }
          await this.#browserCore.setClientWindowState(params);
        }
        targets() {
          return [
            this.#target,
            ...this.browserContexts().flatMap((context) => {
              return context.targets();
            })
          ];
        }
        target() {
          return this.#target;
        }
        async disconnect() {
          try {
            await this.#browserCore.session.end();
          } catch (error) {
            (0, util_js_1.debugError)(error);
          } finally {
            this.connection.dispose();
          }
        }
        get debugInfo() {
          return {
            pendingProtocolErrors: this.connection.getPendingProtocolErrors()
          };
        }
        isNetworkEnabled() {
          return this.#networkEnabled;
        }
      };
    })();
    exports2.BidiBrowser = BidiBrowser;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/bidi.js
var require_bidi = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/bidi.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    __exportStar2(require_BidiOverCdp(), exports2);
    __exportStar2(require_Browser4(), exports2);
    __exportStar2(require_BrowserContext3(), exports2);
    __exportStar2(require_Connection2(), exports2);
    __exportStar2(require_ElementHandle3(), exports2);
    __exportStar2(require_Frame3(), exports2);
    __exportStar2(require_HTTPRequest3(), exports2);
    __exportStar2(require_HTTPResponse3(), exports2);
    __exportStar2(require_Input3(), exports2);
    __exportStar2(require_JSHandle3(), exports2);
    __exportStar2(require_Page3(), exports2);
    __exportStar2(require_Realm4(), exports2);
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/BrowserConnector.js
var require_BrowserConnector2 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/bidi/BrowserConnector.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
      var ownKeys2 = function(o) {
        ownKeys2 = 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 ownKeys2(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]);
        }
        __setModuleDefault2(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2._connectToBiDiBrowser = _connectToBiDiBrowser;
    var Connection_js_1 = require_Connection();
    var Errors_js_1 = require_Errors();
    var util_js_1 = require_util();
    var incremental_id_generator_js_1 = require_incremental_id_generator();
    async function _connectToBiDiBrowser(connectionTransport, url, options) {
      const { acceptInsecureCerts = false, networkEnabled = true, defaultViewport = util_js_1.DEFAULT_VIEWPORT } = options;
      const { bidiConnection, cdpConnection, closeCallback } = await getBiDiConnection(connectionTransport, url, options);
      const BiDi = await Promise.resolve().then(() => __importStar2(require_bidi()));
      const bidiBrowser = await BiDi.BidiBrowser.create({
        connection: bidiConnection,
        cdpConnection,
        closeCallback,
        process: void 0,
        defaultViewport,
        acceptInsecureCerts,
        networkEnabled,
        capabilities: options.capabilities
      });
      return bidiBrowser;
    }
    async function getBiDiConnection(connectionTransport, url, options) {
      const BiDi = await Promise.resolve().then(() => __importStar2(require_bidi()));
      const { slowMo = 0, protocolTimeout, idGenerator = (0, incremental_id_generator_js_1.createIncrementalIdGenerator)() } = options;
      const pureBidiConnection = new BiDi.BidiConnection(url, connectionTransport, idGenerator, slowMo, protocolTimeout);
      try {
        const result = await pureBidiConnection.send("session.status", {});
        if ("type" in result && result.type === "success") {
          return {
            bidiConnection: pureBidiConnection,
            closeCallback: async () => {
              await pureBidiConnection.send("browser.close", {}).catch(util_js_1.debugError);
            }
          };
        }
      } catch (e) {
        if (!(e instanceof Errors_js_1.ProtocolError)) {
          throw e;
        }
      }
      pureBidiConnection.unbind();
      const cdpConnection = new Connection_js_1.Connection(
        url,
        connectionTransport,
        slowMo,
        protocolTimeout,
        /* rawErrors= */
        true,
        idGenerator
      );
      const version = await cdpConnection.send("Browser.getVersion");
      if (version.product.toLowerCase().includes("firefox")) {
        throw new Errors_js_1.UnsupportedOperation("Firefox is not supported in BiDi over CDP mode.");
      }
      const bidiOverCdpConnection = await BiDi.connectBidiOverCdp(cdpConnection);
      return {
        cdpConnection,
        bidiConnection: bidiOverCdpConnection,
        closeCallback: async () => {
          await cdpConnection.send("Browser.close").catch(util_js_1.debugError);
        }
      };
    }
  }
});

// node_modules/ws/lib/constants.js
var require_constants = __commonJS({
  "node_modules/ws/lib/constants.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
    var hasBlob = typeof Blob !== "undefined";
    if (hasBlob) BINARY_TYPES.push("blob");
    module2.exports = {
      BINARY_TYPES,
      CLOSE_TIMEOUT: 3e4,
      EMPTY_BUFFER: Buffer.alloc(0),
      GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
      hasBlob,
      kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
      kListener: /* @__PURE__ */ Symbol("kListener"),
      kStatusCode: /* @__PURE__ */ Symbol("status-code"),
      kWebSocket: /* @__PURE__ */ Symbol("websocket"),
      NOOP: () => {
      }
    };
  }
});

// node_modules/ws/lib/buffer-util.js
var require_buffer_util = __commonJS({
  "node_modules/ws/lib/buffer-util.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var { EMPTY_BUFFER } = require_constants();
    var FastBuffer = Buffer[Symbol.species];
    function concat(list, totalLength) {
      if (list.length === 0) return EMPTY_BUFFER;
      if (list.length === 1) return list[0];
      const target = Buffer.allocUnsafe(totalLength);
      let offset = 0;
      for (let i = 0; i < list.length; i++) {
        const buf = list[i];
        target.set(buf, offset);
        offset += buf.length;
      }
      if (offset < totalLength) {
        return new FastBuffer(target.buffer, target.byteOffset, offset);
      }
      return target;
    }
    function _mask(source, mask, output, offset, length) {
      for (let i = 0; i < length; i++) {
        output[offset + i] = source[i] ^ mask[i & 3];
      }
    }
    function _unmask(buffer, mask) {
      for (let i = 0; i < buffer.length; i++) {
        buffer[i] ^= mask[i & 3];
      }
    }
    function toArrayBuffer(buf) {
      if (buf.length === buf.buffer.byteLength) {
        return buf.buffer;
      }
      return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
    }
    function toBuffer(data) {
      toBuffer.readOnly = true;
      if (Buffer.isBuffer(data)) return data;
      let buf;
      if (data instanceof ArrayBuffer) {
        buf = new FastBuffer(data);
      } else if (ArrayBuffer.isView(data)) {
        buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
      } else {
        buf = Buffer.from(data);
        toBuffer.readOnly = false;
      }
      return buf;
    }
    module2.exports = {
      concat,
      mask: _mask,
      toArrayBuffer,
      toBuffer,
      unmask: _unmask
    };
    if (!process.env.WS_NO_BUFFER_UTIL) {
      try {
        const bufferUtil = require("bufferutil");
        module2.exports.mask = function(source, mask, output, offset, length) {
          if (length < 48) _mask(source, mask, output, offset, length);
          else bufferUtil.mask(source, mask, output, offset, length);
        };
        module2.exports.unmask = function(buffer, mask) {
          if (buffer.length < 32) _unmask(buffer, mask);
          else bufferUtil.unmask(buffer, mask);
        };
      } catch (e) {
      }
    }
  }
});

// node_modules/ws/lib/limiter.js
var require_limiter = __commonJS({
  "node_modules/ws/lib/limiter.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var kDone = /* @__PURE__ */ Symbol("kDone");
    var kRun = /* @__PURE__ */ Symbol("kRun");
    var Limiter = class {
      /**
       * Creates a new `Limiter`.
       *
       * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
       *     to run concurrently
       */
      constructor(concurrency) {
        this[kDone] = () => {
          this.pending--;
          this[kRun]();
        };
        this.concurrency = concurrency || Infinity;
        this.jobs = [];
        this.pending = 0;
      }
      /**
       * Adds a job to the queue.
       *
       * @param {Function} job The job to run
       * @public
       */
      add(job) {
        this.jobs.push(job);
        this[kRun]();
      }
      /**
       * Removes a job from the queue and runs it if possible.
       *
       * @private
       */
      [kRun]() {
        if (this.pending === this.concurrency) return;
        if (this.jobs.length) {
          const job = this.jobs.shift();
          this.pending++;
          job(this[kDone]);
        }
      }
    };
    module2.exports = Limiter;
  }
});

// node_modules/ws/lib/permessage-deflate.js
var require_permessage_deflate = __commonJS({
  "node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var zlib = require("zlib");
    var bufferUtil = require_buffer_util();
    var Limiter = require_limiter();
    var { kStatusCode } = require_constants();
    var FastBuffer = Buffer[Symbol.species];
    var TRAILER = Buffer.from([0, 0, 255, 255]);
    var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
    var kTotalLength = /* @__PURE__ */ Symbol("total-length");
    var kCallback = /* @__PURE__ */ Symbol("callback");
    var kBuffers = /* @__PURE__ */ Symbol("buffers");
    var kError = /* @__PURE__ */ Symbol("error");
    var zlibLimiter;
    var PerMessageDeflate = class {
      /**
       * Creates a PerMessageDeflate instance.
       *
       * @param {Object} [options] Configuration options
       * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
       *     for, or request, a custom client window size
       * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
       *     acknowledge disabling of client context takeover
       * @param {Number} [options.concurrencyLimit=10] The number of concurrent
       *     calls to zlib
       * @param {Boolean} [options.isServer=false] Create the instance in either
       *     server or client mode
       * @param {Number} [options.maxPayload=0] The maximum allowed message length
       * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
       *     use of a custom server window size
       * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
       *     disabling of server context takeover
       * @param {Number} [options.threshold=1024] Size (in bytes) below which
       *     messages should not be compressed if context takeover is disabled
       * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
       *     deflate
       * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
       *     inflate
       */
      constructor(options) {
        this._options = options || {};
        this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
        this._maxPayload = this._options.maxPayload | 0;
        this._isServer = !!this._options.isServer;
        this._deflate = null;
        this._inflate = null;
        this.params = null;
        if (!zlibLimiter) {
          const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
          zlibLimiter = new Limiter(concurrency);
        }
      }
      /**
       * @type {String}
       */
      static get extensionName() {
        return "permessage-deflate";
      }
      /**
       * Create an extension negotiation offer.
       *
       * @return {Object} Extension parameters
       * @public
       */
      offer() {
        const params = {};
        if (this._options.serverNoContextTakeover) {
          params.server_no_context_takeover = true;
        }
        if (this._options.clientNoContextTakeover) {
          params.client_no_context_takeover = true;
        }
        if (this._options.serverMaxWindowBits) {
          params.server_max_window_bits = this._options.serverMaxWindowBits;
        }
        if (this._options.clientMaxWindowBits) {
          params.client_max_window_bits = this._options.clientMaxWindowBits;
        } else if (this._options.clientMaxWindowBits == null) {
          params.client_max_window_bits = true;
        }
        return params;
      }
      /**
       * Accept an extension negotiation offer/response.
       *
       * @param {Array} configurations The extension negotiation offers/reponse
       * @return {Object} Accepted configuration
       * @public
       */
      accept(configurations) {
        configurations = this.normalizeParams(configurations);
        this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
        return this.params;
      }
      /**
       * Releases all resources used by the extension.
       *
       * @public
       */
      cleanup() {
        if (this._inflate) {
          this._inflate.close();
          this._inflate = null;
        }
        if (this._deflate) {
          const callback = this._deflate[kCallback];
          this._deflate.close();
          this._deflate = null;
          if (callback) {
            callback(
              new Error(
                "The deflate stream was closed while data was being processed"
              )
            );
          }
        }
      }
      /**
       *  Accept an extension negotiation offer.
       *
       * @param {Array} offers The extension negotiation offers
       * @return {Object} Accepted configuration
       * @private
       */
      acceptAsServer(offers) {
        const opts = this._options;
        const accepted = offers.find((params) => {
          if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
            return false;
          }
          return true;
        });
        if (!accepted) {
          throw new Error("None of the extension offers can be accepted");
        }
        if (opts.serverNoContextTakeover) {
          accepted.server_no_context_takeover = true;
        }
        if (opts.clientNoContextTakeover) {
          accepted.client_no_context_takeover = true;
        }
        if (typeof opts.serverMaxWindowBits === "number") {
          accepted.server_max_window_bits = opts.serverMaxWindowBits;
        }
        if (typeof opts.clientMaxWindowBits === "number") {
          accepted.client_max_window_bits = opts.clientMaxWindowBits;
        } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
          delete accepted.client_max_window_bits;
        }
        return accepted;
      }
      /**
       * Accept the extension negotiation response.
       *
       * @param {Array} response The extension negotiation response
       * @return {Object} Accepted configuration
       * @private
       */
      acceptAsClient(response) {
        const params = response[0];
        if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
          throw new Error('Unexpected parameter "client_no_context_takeover"');
        }
        if (!params.client_max_window_bits) {
          if (typeof this._options.clientMaxWindowBits === "number") {
            params.client_max_window_bits = this._options.clientMaxWindowBits;
          }
        } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
          throw new Error(
            'Unexpected or invalid parameter "client_max_window_bits"'
          );
        }
        return params;
      }
      /**
       * Normalize parameters.
       *
       * @param {Array} configurations The extension negotiation offers/reponse
       * @return {Array} The offers/response with normalized parameters
       * @private
       */
      normalizeParams(configurations) {
        configurations.forEach((params) => {
          Object.keys(params).forEach((key) => {
            let value = params[key];
            if (value.length > 1) {
              throw new Error(`Parameter "${key}" must have only a single value`);
            }
            value = value[0];
            if (key === "client_max_window_bits") {
              if (value !== true) {
                const num = +value;
                if (!Number.isInteger(num) || num < 8 || num > 15) {
                  throw new TypeError(
                    `Invalid value for parameter "${key}": ${value}`
                  );
                }
                value = num;
              } else if (!this._isServer) {
                throw new TypeError(
                  `Invalid value for parameter "${key}": ${value}`
                );
              }
            } else if (key === "server_max_window_bits") {
              const num = +value;
              if (!Number.isInteger(num) || num < 8 || num > 15) {
                throw new TypeError(
                  `Invalid value for parameter "${key}": ${value}`
                );
              }
              value = num;
            } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
              if (value !== true) {
                throw new TypeError(
                  `Invalid value for parameter "${key}": ${value}`
                );
              }
            } else {
              throw new Error(`Unknown parameter "${key}"`);
            }
            params[key] = value;
          });
        });
        return configurations;
      }
      /**
       * Decompress data. Concurrency limited.
       *
       * @param {Buffer} data Compressed data
       * @param {Boolean} fin Specifies whether or not this is the last fragment
       * @param {Function} callback Callback
       * @public
       */
      decompress(data, fin, callback) {
        zlibLimiter.add((done) => {
          this._decompress(data, fin, (err, result) => {
            done();
            callback(err, result);
          });
        });
      }
      /**
       * Compress data. Concurrency limited.
       *
       * @param {(Buffer|String)} data Data to compress
       * @param {Boolean} fin Specifies whether or not this is the last fragment
       * @param {Function} callback Callback
       * @public
       */
      compress(data, fin, callback) {
        zlibLimiter.add((done) => {
          this._compress(data, fin, (err, result) => {
            done();
            callback(err, result);
          });
        });
      }
      /**
       * Decompress data.
       *
       * @param {Buffer} data Compressed data
       * @param {Boolean} fin Specifies whether or not this is the last fragment
       * @param {Function} callback Callback
       * @private
       */
      _decompress(data, fin, callback) {
        const endpoint = this._isServer ? "client" : "server";
        if (!this._inflate) {
          const key = `${endpoint}_max_window_bits`;
          const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
          this._inflate = zlib.createInflateRaw({
            ...this._options.zlibInflateOptions,
            windowBits
          });
          this._inflate[kPerMessageDeflate] = this;
          this._inflate[kTotalLength] = 0;
          this._inflate[kBuffers] = [];
          this._inflate.on("error", inflateOnError);
          this._inflate.on("data", inflateOnData);
        }
        this._inflate[kCallback] = callback;
        this._inflate.write(data);
        if (fin) this._inflate.write(TRAILER);
        this._inflate.flush(() => {
          const err = this._inflate[kError];
          if (err) {
            this._inflate.close();
            this._inflate = null;
            callback(err);
            return;
          }
          const data2 = bufferUtil.concat(
            this._inflate[kBuffers],
            this._inflate[kTotalLength]
          );
          if (this._inflate._readableState.endEmitted) {
            this._inflate.close();
            this._inflate = null;
          } else {
            this._inflate[kTotalLength] = 0;
            this._inflate[kBuffers] = [];
            if (fin && this.params[`${endpoint}_no_context_takeover`]) {
              this._inflate.reset();
            }
          }
          callback(null, data2);
        });
      }
      /**
       * Compress data.
       *
       * @param {(Buffer|String)} data Data to compress
       * @param {Boolean} fin Specifies whether or not this is the last fragment
       * @param {Function} callback Callback
       * @private
       */
      _compress(data, fin, callback) {
        const endpoint = this._isServer ? "server" : "client";
        if (!this._deflate) {
          const key = `${endpoint}_max_window_bits`;
          const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
          this._deflate = zlib.createDeflateRaw({
            ...this._options.zlibDeflateOptions,
            windowBits
          });
          this._deflate[kTotalLength] = 0;
          this._deflate[kBuffers] = [];
          this._deflate.on("data", deflateOnData);
        }
        this._deflate[kCallback] = callback;
        this._deflate.write(data);
        this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
          if (!this._deflate) {
            return;
          }
          let data2 = bufferUtil.concat(
            this._deflate[kBuffers],
            this._deflate[kTotalLength]
          );
          if (fin) {
            data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
          }
          this._deflate[kCallback] = null;
          this._deflate[kTotalLength] = 0;
          this._deflate[kBuffers] = [];
          if (fin && this.params[`${endpoint}_no_context_takeover`]) {
            this._deflate.reset();
          }
          callback(null, data2);
        });
      }
    };
    module2.exports = PerMessageDeflate;
    function deflateOnData(chunk) {
      this[kBuffers].push(chunk);
      this[kTotalLength] += chunk.length;
    }
    function inflateOnData(chunk) {
      this[kTotalLength] += chunk.length;
      if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
        this[kBuffers].push(chunk);
        return;
      }
      this[kError] = new RangeError("Max payload size exceeded");
      this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
      this[kError][kStatusCode] = 1009;
      this.removeListener("data", inflateOnData);
      this.reset();
    }
    function inflateOnError(err) {
      this[kPerMessageDeflate]._inflate = null;
      if (this[kError]) {
        this[kCallback](this[kError]);
        return;
      }
      err[kStatusCode] = 1007;
      this[kCallback](err);
    }
  }
});

// node_modules/ws/lib/validation.js
var require_validation = __commonJS({
  "node_modules/ws/lib/validation.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var { isUtf8 } = require("buffer");
    var { hasBlob } = require_constants();
    var tokenChars = [
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 0 - 15
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 16 - 31
      0,
      1,
      0,
      1,
      1,
      1,
      1,
      1,
      0,
      0,
      1,
      1,
      0,
      1,
      1,
      0,
      // 32 - 47
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      0,
      0,
      0,
      0,
      0,
      0,
      // 48 - 63
      0,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      // 64 - 79
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      0,
      0,
      0,
      1,
      1,
      // 80 - 95
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      // 96 - 111
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      0,
      1,
      0,
      1,
      0
      // 112 - 127
    ];
    function isValidStatusCode(code) {
      return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
    }
    function _isValidUTF8(buf) {
      const len = buf.length;
      let i = 0;
      while (i < len) {
        if ((buf[i] & 128) === 0) {
          i++;
        } else if ((buf[i] & 224) === 192) {
          if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
            return false;
          }
          i += 2;
        } else if ((buf[i] & 240) === 224) {
          if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
          buf[i] === 237 && (buf[i + 1] & 224) === 160) {
            return false;
          }
          i += 3;
        } else if ((buf[i] & 248) === 240) {
          if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
          buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
            return false;
          }
          i += 4;
        } else {
          return false;
        }
      }
      return true;
    }
    function isBlob(value) {
      return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
    }
    module2.exports = {
      isBlob,
      isValidStatusCode,
      isValidUTF8: _isValidUTF8,
      tokenChars
    };
    if (isUtf8) {
      module2.exports.isValidUTF8 = function(buf) {
        return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
      };
    } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
      try {
        const isValidUTF8 = require("utf-8-validate");
        module2.exports.isValidUTF8 = function(buf) {
          return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
        };
      } catch (e) {
      }
    }
  }
});

// node_modules/ws/lib/receiver.js
var require_receiver = __commonJS({
  "node_modules/ws/lib/receiver.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var { Writable } = require("stream");
    var PerMessageDeflate = require_permessage_deflate();
    var {
      BINARY_TYPES,
      EMPTY_BUFFER,
      kStatusCode,
      kWebSocket
    } = require_constants();
    var { concat, toArrayBuffer, unmask } = require_buffer_util();
    var { isValidStatusCode, isValidUTF8 } = require_validation();
    var FastBuffer = Buffer[Symbol.species];
    var GET_INFO = 0;
    var GET_PAYLOAD_LENGTH_16 = 1;
    var GET_PAYLOAD_LENGTH_64 = 2;
    var GET_MASK = 3;
    var GET_DATA = 4;
    var INFLATING = 5;
    var DEFER_EVENT = 6;
    var Receiver = class extends Writable {
      /**
       * Creates a Receiver instance.
       *
       * @param {Object} [options] Options object
       * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
       *     any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
       *     multiple times in the same tick
       * @param {String} [options.binaryType=nodebuffer] The type for binary data
       * @param {Object} [options.extensions] An object containing the negotiated
       *     extensions
       * @param {Boolean} [options.isServer=false] Specifies whether to operate in
       *     client or server mode
       * @param {Number} [options.maxPayload=0] The maximum allowed message length
       * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
       *     not to skip UTF-8 validation for text and close messages
       */
      constructor(options = {}) {
        super();
        this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
        this._binaryType = options.binaryType || BINARY_TYPES[0];
        this._extensions = options.extensions || {};
        this._isServer = !!options.isServer;
        this._maxPayload = options.maxPayload | 0;
        this._skipUTF8Validation = !!options.skipUTF8Validation;
        this[kWebSocket] = void 0;
        this._bufferedBytes = 0;
        this._buffers = [];
        this._compressed = false;
        this._payloadLength = 0;
        this._mask = void 0;
        this._fragmented = 0;
        this._masked = false;
        this._fin = false;
        this._opcode = 0;
        this._totalPayloadLength = 0;
        this._messageLength = 0;
        this._fragments = [];
        this._errored = false;
        this._loop = false;
        this._state = GET_INFO;
      }
      /**
       * Implements `Writable.prototype._write()`.
       *
       * @param {Buffer} chunk The chunk of data to write
       * @param {String} encoding The character encoding of `chunk`
       * @param {Function} cb Callback
       * @private
       */
      _write(chunk, encoding, cb) {
        if (this._opcode === 8 && this._state == GET_INFO) return cb();
        this._bufferedBytes += chunk.length;
        this._buffers.push(chunk);
        this.startLoop(cb);
      }
      /**
       * Consumes `n` bytes from the buffered data.
       *
       * @param {Number} n The number of bytes to consume
       * @return {Buffer} The consumed bytes
       * @private
       */
      consume(n) {
        this._bufferedBytes -= n;
        if (n === this._buffers[0].length) return this._buffers.shift();
        if (n < this._buffers[0].length) {
          const buf = this._buffers[0];
          this._buffers[0] = new FastBuffer(
            buf.buffer,
            buf.byteOffset + n,
            buf.length - n
          );
          return new FastBuffer(buf.buffer, buf.byteOffset, n);
        }
        const dst = Buffer.allocUnsafe(n);
        do {
          const buf = this._buffers[0];
          const offset = dst.length - n;
          if (n >= buf.length) {
            dst.set(this._buffers.shift(), offset);
          } else {
            dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
            this._buffers[0] = new FastBuffer(
              buf.buffer,
              buf.byteOffset + n,
              buf.length - n
            );
          }
          n -= buf.length;
        } while (n > 0);
        return dst;
      }
      /**
       * Starts the parsing loop.
       *
       * @param {Function} cb Callback
       * @private
       */
      startLoop(cb) {
        this._loop = true;
        do {
          switch (this._state) {
            case GET_INFO:
              this.getInfo(cb);
              break;
            case GET_PAYLOAD_LENGTH_16:
              this.getPayloadLength16(cb);
              break;
            case GET_PAYLOAD_LENGTH_64:
              this.getPayloadLength64(cb);
              break;
            case GET_MASK:
              this.getMask();
              break;
            case GET_DATA:
              this.getData(cb);
              break;
            case INFLATING:
            case DEFER_EVENT:
              this._loop = false;
              return;
          }
        } while (this._loop);
        if (!this._errored) cb();
      }
      /**
       * Reads the first two bytes of a frame.
       *
       * @param {Function} cb Callback
       * @private
       */
      getInfo(cb) {
        if (this._bufferedBytes < 2) {
          this._loop = false;
          return;
        }
        const buf = this.consume(2);
        if ((buf[0] & 48) !== 0) {
          const error = this.createError(
            RangeError,
            "RSV2 and RSV3 must be clear",
            true,
            1002,
            "WS_ERR_UNEXPECTED_RSV_2_3"
          );
          cb(error);
          return;
        }
        const compressed = (buf[0] & 64) === 64;
        if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
          const error = this.createError(
            RangeError,
            "RSV1 must be clear",
            true,
            1002,
            "WS_ERR_UNEXPECTED_RSV_1"
          );
          cb(error);
          return;
        }
        this._fin = (buf[0] & 128) === 128;
        this._opcode = buf[0] & 15;
        this._payloadLength = buf[1] & 127;
        if (this._opcode === 0) {
          if (compressed) {
            const error = this.createError(
              RangeError,
              "RSV1 must be clear",
              true,
              1002,
              "WS_ERR_UNEXPECTED_RSV_1"
            );
            cb(error);
            return;
          }
          if (!this._fragmented) {
            const error = this.createError(
              RangeError,
              "invalid opcode 0",
              true,
              1002,
              "WS_ERR_INVALID_OPCODE"
            );
            cb(error);
            return;
          }
          this._opcode = this._fragmented;
        } else if (this._opcode === 1 || this._opcode === 2) {
          if (this._fragmented) {
            const error = this.createError(
              RangeError,
              `invalid opcode ${this._opcode}`,
              true,
              1002,
              "WS_ERR_INVALID_OPCODE"
            );
            cb(error);
            return;
          }
          this._compressed = compressed;
        } else if (this._opcode > 7 && this._opcode < 11) {
          if (!this._fin) {
            const error = this.createError(
              RangeError,
              "FIN must be set",
              true,
              1002,
              "WS_ERR_EXPECTED_FIN"
            );
            cb(error);
            return;
          }
          if (compressed) {
            const error = this.createError(
              RangeError,
              "RSV1 must be clear",
              true,
              1002,
              "WS_ERR_UNEXPECTED_RSV_1"
            );
            cb(error);
            return;
          }
          if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
            const error = this.createError(
              RangeError,
              `invalid payload length ${this._payloadLength}`,
              true,
              1002,
              "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
            );
            cb(error);
            return;
          }
        } else {
          const error = this.createError(
            RangeError,
            `invalid opcode ${this._opcode}`,
            true,
            1002,
            "WS_ERR_INVALID_OPCODE"
          );
          cb(error);
          return;
        }
        if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
        this._masked = (buf[1] & 128) === 128;
        if (this._isServer) {
          if (!this._masked) {
            const error = this.createError(
              RangeError,
              "MASK must be set",
              true,
              1002,
              "WS_ERR_EXPECTED_MASK"
            );
            cb(error);
            return;
          }
        } else if (this._masked) {
          const error = this.createError(
            RangeError,
            "MASK must be clear",
            true,
            1002,
            "WS_ERR_UNEXPECTED_MASK"
          );
          cb(error);
          return;
        }
        if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
        else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
        else this.haveLength(cb);
      }
      /**
       * Gets extended payload length (7+16).
       *
       * @param {Function} cb Callback
       * @private
       */
      getPayloadLength16(cb) {
        if (this._bufferedBytes < 2) {
          this._loop = false;
          return;
        }
        this._payloadLength = this.consume(2).readUInt16BE(0);
        this.haveLength(cb);
      }
      /**
       * Gets extended payload length (7+64).
       *
       * @param {Function} cb Callback
       * @private
       */
      getPayloadLength64(cb) {
        if (this._bufferedBytes < 8) {
          this._loop = false;
          return;
        }
        const buf = this.consume(8);
        const num = buf.readUInt32BE(0);
        if (num > Math.pow(2, 53 - 32) - 1) {
          const error = this.createError(
            RangeError,
            "Unsupported WebSocket frame: payload length > 2^53 - 1",
            false,
            1009,
            "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
          );
          cb(error);
          return;
        }
        this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
        this.haveLength(cb);
      }
      /**
       * Payload length has been read.
       *
       * @param {Function} cb Callback
       * @private
       */
      haveLength(cb) {
        if (this._payloadLength && this._opcode < 8) {
          this._totalPayloadLength += this._payloadLength;
          if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
            const error = this.createError(
              RangeError,
              "Max payload size exceeded",
              false,
              1009,
              "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
            );
            cb(error);
            return;
          }
        }
        if (this._masked) this._state = GET_MASK;
        else this._state = GET_DATA;
      }
      /**
       * Reads mask bytes.
       *
       * @private
       */
      getMask() {
        if (this._bufferedBytes < 4) {
          this._loop = false;
          return;
        }
        this._mask = this.consume(4);
        this._state = GET_DATA;
      }
      /**
       * Reads data bytes.
       *
       * @param {Function} cb Callback
       * @private
       */
      getData(cb) {
        let data = EMPTY_BUFFER;
        if (this._payloadLength) {
          if (this._bufferedBytes < this._payloadLength) {
            this._loop = false;
            return;
          }
          data = this.consume(this._payloadLength);
          if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
            unmask(data, this._mask);
          }
        }
        if (this._opcode > 7) {
          this.controlMessage(data, cb);
          return;
        }
        if (this._compressed) {
          this._state = INFLATING;
          this.decompress(data, cb);
          return;
        }
        if (data.length) {
          this._messageLength = this._totalPayloadLength;
          this._fragments.push(data);
        }
        this.dataMessage(cb);
      }
      /**
       * Decompresses data.
       *
       * @param {Buffer} data Compressed data
       * @param {Function} cb Callback
       * @private
       */
      decompress(data, cb) {
        const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
        perMessageDeflate.decompress(data, this._fin, (err, buf) => {
          if (err) return cb(err);
          if (buf.length) {
            this._messageLength += buf.length;
            if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
              const error = this.createError(
                RangeError,
                "Max payload size exceeded",
                false,
                1009,
                "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
              );
              cb(error);
              return;
            }
            this._fragments.push(buf);
          }
          this.dataMessage(cb);
          if (this._state === GET_INFO) this.startLoop(cb);
        });
      }
      /**
       * Handles a data message.
       *
       * @param {Function} cb Callback
       * @private
       */
      dataMessage(cb) {
        if (!this._fin) {
          this._state = GET_INFO;
          return;
        }
        const messageLength = this._messageLength;
        const fragments = this._fragments;
        this._totalPayloadLength = 0;
        this._messageLength = 0;
        this._fragmented = 0;
        this._fragments = [];
        if (this._opcode === 2) {
          let data;
          if (this._binaryType === "nodebuffer") {
            data = concat(fragments, messageLength);
          } else if (this._binaryType === "arraybuffer") {
            data = toArrayBuffer(concat(fragments, messageLength));
          } else if (this._binaryType === "blob") {
            data = new Blob(fragments);
          } else {
            data = fragments;
          }
          if (this._allowSynchronousEvents) {
            this.emit("message", data, true);
            this._state = GET_INFO;
          } else {
            this._state = DEFER_EVENT;
            setImmediate(() => {
              this.emit("message", data, true);
              this._state = GET_INFO;
              this.startLoop(cb);
            });
          }
        } else {
          const buf = concat(fragments, messageLength);
          if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
            const error = this.createError(
              Error,
              "invalid UTF-8 sequence",
              true,
              1007,
              "WS_ERR_INVALID_UTF8"
            );
            cb(error);
            return;
          }
          if (this._state === INFLATING || this._allowSynchronousEvents) {
            this.emit("message", buf, false);
            this._state = GET_INFO;
          } else {
            this._state = DEFER_EVENT;
            setImmediate(() => {
              this.emit("message", buf, false);
              this._state = GET_INFO;
              this.startLoop(cb);
            });
          }
        }
      }
      /**
       * Handles a control message.
       *
       * @param {Buffer} data Data to handle
       * @return {(Error|RangeError|undefined)} A possible error
       * @private
       */
      controlMessage(data, cb) {
        if (this._opcode === 8) {
          if (data.length === 0) {
            this._loop = false;
            this.emit("conclude", 1005, EMPTY_BUFFER);
            this.end();
          } else {
            const code = data.readUInt16BE(0);
            if (!isValidStatusCode(code)) {
              const error = this.createError(
                RangeError,
                `invalid status code ${code}`,
                true,
                1002,
                "WS_ERR_INVALID_CLOSE_CODE"
              );
              cb(error);
              return;
            }
            const buf = new FastBuffer(
              data.buffer,
              data.byteOffset + 2,
              data.length - 2
            );
            if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
              const error = this.createError(
                Error,
                "invalid UTF-8 sequence",
                true,
                1007,
                "WS_ERR_INVALID_UTF8"
              );
              cb(error);
              return;
            }
            this._loop = false;
            this.emit("conclude", code, buf);
            this.end();
          }
          this._state = GET_INFO;
          return;
        }
        if (this._allowSynchronousEvents) {
          this.emit(this._opcode === 9 ? "ping" : "pong", data);
          this._state = GET_INFO;
        } else {
          this._state = DEFER_EVENT;
          setImmediate(() => {
            this.emit(this._opcode === 9 ? "ping" : "pong", data);
            this._state = GET_INFO;
            this.startLoop(cb);
          });
        }
      }
      /**
       * Builds an error object.
       *
       * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
       * @param {String} message The error message
       * @param {Boolean} prefix Specifies whether or not to add a default prefix to
       *     `message`
       * @param {Number} statusCode The status code
       * @param {String} errorCode The exposed error code
       * @return {(Error|RangeError)} The error
       * @private
       */
      createError(ErrorCtor, message, prefix, statusCode, errorCode) {
        this._loop = false;
        this._errored = true;
        const err = new ErrorCtor(
          prefix ? `Invalid WebSocket frame: ${message}` : message
        );
        Error.captureStackTrace(err, this.createError);
        err.code = errorCode;
        err[kStatusCode] = statusCode;
        return err;
      }
    };
    module2.exports = Receiver;
  }
});

// node_modules/ws/lib/sender.js
var require_sender = __commonJS({
  "node_modules/ws/lib/sender.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var { Duplex } = require("stream");
    var { randomFillSync } = require("crypto");
    var PerMessageDeflate = require_permessage_deflate();
    var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
    var { isBlob, isValidStatusCode } = require_validation();
    var { mask: applyMask, toBuffer } = require_buffer_util();
    var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
    var maskBuffer = Buffer.alloc(4);
    var RANDOM_POOL_SIZE = 8 * 1024;
    var randomPool;
    var randomPoolPointer = RANDOM_POOL_SIZE;
    var DEFAULT = 0;
    var DEFLATING = 1;
    var GET_BLOB_DATA = 2;
    var Sender = class _Sender {
      /**
       * Creates a Sender instance.
       *
       * @param {Duplex} socket The connection socket
       * @param {Object} [extensions] An object containing the negotiated extensions
       * @param {Function} [generateMask] The function used to generate the masking
       *     key
       */
      constructor(socket, extensions, generateMask) {
        this._extensions = extensions || {};
        if (generateMask) {
          this._generateMask = generateMask;
          this._maskBuffer = Buffer.alloc(4);
        }
        this._socket = socket;
        this._firstFragment = true;
        this._compress = false;
        this._bufferedBytes = 0;
        this._queue = [];
        this._state = DEFAULT;
        this.onerror = NOOP;
        this[kWebSocket] = void 0;
      }
      /**
       * Frames a piece of data according to the HyBi WebSocket protocol.
       *
       * @param {(Buffer|String)} data The data to frame
       * @param {Object} options Options object
       * @param {Boolean} [options.fin=false] Specifies whether or not to set the
       *     FIN bit
       * @param {Function} [options.generateMask] The function used to generate the
       *     masking key
       * @param {Boolean} [options.mask=false] Specifies whether or not to mask
       *     `data`
       * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
       *     key
       * @param {Number} options.opcode The opcode
       * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
       *     modified
       * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
       *     RSV1 bit
       * @return {(Buffer|String)[]} The framed data
       * @public
       */
      static frame(data, options) {
        let mask;
        let merge = false;
        let offset = 2;
        let skipMasking = false;
        if (options.mask) {
          mask = options.maskBuffer || maskBuffer;
          if (options.generateMask) {
            options.generateMask(mask);
          } else {
            if (randomPoolPointer === RANDOM_POOL_SIZE) {
              if (randomPool === void 0) {
                randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
              }
              randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
              randomPoolPointer = 0;
            }
            mask[0] = randomPool[randomPoolPointer++];
            mask[1] = randomPool[randomPoolPointer++];
            mask[2] = randomPool[randomPoolPointer++];
            mask[3] = randomPool[randomPoolPointer++];
          }
          skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
          offset = 6;
        }
        let dataLength;
        if (typeof data === "string") {
          if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
            dataLength = options[kByteLength];
          } else {
            data = Buffer.from(data);
            dataLength = data.length;
          }
        } else {
          dataLength = data.length;
          merge = options.mask && options.readOnly && !skipMasking;
        }
        let payloadLength = dataLength;
        if (dataLength >= 65536) {
          offset += 8;
          payloadLength = 127;
        } else if (dataLength > 125) {
          offset += 2;
          payloadLength = 126;
        }
        const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
        target[0] = options.fin ? options.opcode | 128 : options.opcode;
        if (options.rsv1) target[0] |= 64;
        target[1] = payloadLength;
        if (payloadLength === 126) {
          target.writeUInt16BE(dataLength, 2);
        } else if (payloadLength === 127) {
          target[2] = target[3] = 0;
          target.writeUIntBE(dataLength, 4, 6);
        }
        if (!options.mask) return [target, data];
        target[1] |= 128;
        target[offset - 4] = mask[0];
        target[offset - 3] = mask[1];
        target[offset - 2] = mask[2];
        target[offset - 1] = mask[3];
        if (skipMasking) return [target, data];
        if (merge) {
          applyMask(data, mask, target, offset, dataLength);
          return [target];
        }
        applyMask(data, mask, data, 0, dataLength);
        return [target, data];
      }
      /**
       * Sends a close message to the other peer.
       *
       * @param {Number} [code] The status code component of the body
       * @param {(String|Buffer)} [data] The message component of the body
       * @param {Boolean} [mask=false] Specifies whether or not to mask the message
       * @param {Function} [cb] Callback
       * @public
       */
      close(code, data, mask, cb) {
        let buf;
        if (code === void 0) {
          buf = EMPTY_BUFFER;
        } else if (typeof code !== "number" || !isValidStatusCode(code)) {
          throw new TypeError("First argument must be a valid error code number");
        } else if (data === void 0 || !data.length) {
          buf = Buffer.allocUnsafe(2);
          buf.writeUInt16BE(code, 0);
        } else {
          const length = Buffer.byteLength(data);
          if (length > 123) {
            throw new RangeError("The message must not be greater than 123 bytes");
          }
          buf = Buffer.allocUnsafe(2 + length);
          buf.writeUInt16BE(code, 0);
          if (typeof data === "string") {
            buf.write(data, 2);
          } else {
            buf.set(data, 2);
          }
        }
        const options = {
          [kByteLength]: buf.length,
          fin: true,
          generateMask: this._generateMask,
          mask,
          maskBuffer: this._maskBuffer,
          opcode: 8,
          readOnly: false,
          rsv1: false
        };
        if (this._state !== DEFAULT) {
          this.enqueue([this.dispatch, buf, false, options, cb]);
        } else {
          this.sendFrame(_Sender.frame(buf, options), cb);
        }
      }
      /**
       * Sends a ping message to the other peer.
       *
       * @param {*} data The message to send
       * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
       * @param {Function} [cb] Callback
       * @public
       */
      ping(data, mask, cb) {
        let byteLength;
        let readOnly;
        if (typeof data === "string") {
          byteLength = Buffer.byteLength(data);
          readOnly = false;
        } else if (isBlob(data)) {
          byteLength = data.size;
          readOnly = false;
        } else {
          data = toBuffer(data);
          byteLength = data.length;
          readOnly = toBuffer.readOnly;
        }
        if (byteLength > 125) {
          throw new RangeError("The data size must not be greater than 125 bytes");
        }
        const options = {
          [kByteLength]: byteLength,
          fin: true,
          generateMask: this._generateMask,
          mask,
          maskBuffer: this._maskBuffer,
          opcode: 9,
          readOnly,
          rsv1: false
        };
        if (isBlob(data)) {
          if (this._state !== DEFAULT) {
            this.enqueue([this.getBlobData, data, false, options, cb]);
          } else {
            this.getBlobData(data, false, options, cb);
          }
        } else if (this._state !== DEFAULT) {
          this.enqueue([this.dispatch, data, false, options, cb]);
        } else {
          this.sendFrame(_Sender.frame(data, options), cb);
        }
      }
      /**
       * Sends a pong message to the other peer.
       *
       * @param {*} data The message to send
       * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
       * @param {Function} [cb] Callback
       * @public
       */
      pong(data, mask, cb) {
        let byteLength;
        let readOnly;
        if (typeof data === "string") {
          byteLength = Buffer.byteLength(data);
          readOnly = false;
        } else if (isBlob(data)) {
          byteLength = data.size;
          readOnly = false;
        } else {
          data = toBuffer(data);
          byteLength = data.length;
          readOnly = toBuffer.readOnly;
        }
        if (byteLength > 125) {
          throw new RangeError("The data size must not be greater than 125 bytes");
        }
        const options = {
          [kByteLength]: byteLength,
          fin: true,
          generateMask: this._generateMask,
          mask,
          maskBuffer: this._maskBuffer,
          opcode: 10,
          readOnly,
          rsv1: false
        };
        if (isBlob(data)) {
          if (this._state !== DEFAULT) {
            this.enqueue([this.getBlobData, data, false, options, cb]);
          } else {
            this.getBlobData(data, false, options, cb);
          }
        } else if (this._state !== DEFAULT) {
          this.enqueue([this.dispatch, data, false, options, cb]);
        } else {
          this.sendFrame(_Sender.frame(data, options), cb);
        }
      }
      /**
       * Sends a data message to the other peer.
       *
       * @param {*} data The message to send
       * @param {Object} options Options object
       * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
       *     or text
       * @param {Boolean} [options.compress=false] Specifies whether or not to
       *     compress `data`
       * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
       *     last one
       * @param {Boolean} [options.mask=false] Specifies whether or not to mask
       *     `data`
       * @param {Function} [cb] Callback
       * @public
       */
      send(data, options, cb) {
        const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
        let opcode = options.binary ? 2 : 1;
        let rsv1 = options.compress;
        let byteLength;
        let readOnly;
        if (typeof data === "string") {
          byteLength = Buffer.byteLength(data);
          readOnly = false;
        } else if (isBlob(data)) {
          byteLength = data.size;
          readOnly = false;
        } else {
          data = toBuffer(data);
          byteLength = data.length;
          readOnly = toBuffer.readOnly;
        }
        if (this._firstFragment) {
          this._firstFragment = false;
          if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
            rsv1 = byteLength >= perMessageDeflate._threshold;
          }
          this._compress = rsv1;
        } else {
          rsv1 = false;
          opcode = 0;
        }
        if (options.fin) this._firstFragment = true;
        const opts = {
          [kByteLength]: byteLength,
          fin: options.fin,
          generateMask: this._generateMask,
          mask: options.mask,
          maskBuffer: this._maskBuffer,
          opcode,
          readOnly,
          rsv1
        };
        if (isBlob(data)) {
          if (this._state !== DEFAULT) {
            this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
          } else {
            this.getBlobData(data, this._compress, opts, cb);
          }
        } else if (this._state !== DEFAULT) {
          this.enqueue([this.dispatch, data, this._compress, opts, cb]);
        } else {
          this.dispatch(data, this._compress, opts, cb);
        }
      }
      /**
       * Gets the contents of a blob as binary data.
       *
       * @param {Blob} blob The blob
       * @param {Boolean} [compress=false] Specifies whether or not to compress
       *     the data
       * @param {Object} options Options object
       * @param {Boolean} [options.fin=false] Specifies whether or not to set the
       *     FIN bit
       * @param {Function} [options.generateMask] The function used to generate the
       *     masking key
       * @param {Boolean} [options.mask=false] Specifies whether or not to mask
       *     `data`
       * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
       *     key
       * @param {Number} options.opcode The opcode
       * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
       *     modified
       * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
       *     RSV1 bit
       * @param {Function} [cb] Callback
       * @private
       */
      getBlobData(blob, compress, options, cb) {
        this._bufferedBytes += options[kByteLength];
        this._state = GET_BLOB_DATA;
        blob.arrayBuffer().then((arrayBuffer) => {
          if (this._socket.destroyed) {
            const err = new Error(
              "The socket was closed while the blob was being read"
            );
            process.nextTick(callCallbacks, this, err, cb);
            return;
          }
          this._bufferedBytes -= options[kByteLength];
          const data = toBuffer(arrayBuffer);
          if (!compress) {
            this._state = DEFAULT;
            this.sendFrame(_Sender.frame(data, options), cb);
            this.dequeue();
          } else {
            this.dispatch(data, compress, options, cb);
          }
        }).catch((err) => {
          process.nextTick(onError, this, err, cb);
        });
      }
      /**
       * Dispatches a message.
       *
       * @param {(Buffer|String)} data The message to send
       * @param {Boolean} [compress=false] Specifies whether or not to compress
       *     `data`
       * @param {Object} options Options object
       * @param {Boolean} [options.fin=false] Specifies whether or not to set the
       *     FIN bit
       * @param {Function} [options.generateMask] The function used to generate the
       *     masking key
       * @param {Boolean} [options.mask=false] Specifies whether or not to mask
       *     `data`
       * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
       *     key
       * @param {Number} options.opcode The opcode
       * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
       *     modified
       * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
       *     RSV1 bit
       * @param {Function} [cb] Callback
       * @private
       */
      dispatch(data, compress, options, cb) {
        if (!compress) {
          this.sendFrame(_Sender.frame(data, options), cb);
          return;
        }
        const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
        this._bufferedBytes += options[kByteLength];
        this._state = DEFLATING;
        perMessageDeflate.compress(data, options.fin, (_, buf) => {
          if (this._socket.destroyed) {
            const err = new Error(
              "The socket was closed while data was being compressed"
            );
            callCallbacks(this, err, cb);
            return;
          }
          this._bufferedBytes -= options[kByteLength];
          this._state = DEFAULT;
          options.readOnly = false;
          this.sendFrame(_Sender.frame(buf, options), cb);
          this.dequeue();
        });
      }
      /**
       * Executes queued send operations.
       *
       * @private
       */
      dequeue() {
        while (this._state === DEFAULT && this._queue.length) {
          const params = this._queue.shift();
          this._bufferedBytes -= params[3][kByteLength];
          Reflect.apply(params[0], this, params.slice(1));
        }
      }
      /**
       * Enqueues a send operation.
       *
       * @param {Array} params Send operation parameters.
       * @private
       */
      enqueue(params) {
        this._bufferedBytes += params[3][kByteLength];
        this._queue.push(params);
      }
      /**
       * Sends a frame.
       *
       * @param {(Buffer | String)[]} list The frame to send
       * @param {Function} [cb] Callback
       * @private
       */
      sendFrame(list, cb) {
        if (list.length === 2) {
          this._socket.cork();
          this._socket.write(list[0]);
          this._socket.write(list[1], cb);
          this._socket.uncork();
        } else {
          this._socket.write(list[0], cb);
        }
      }
    };
    module2.exports = Sender;
    function callCallbacks(sender, err, cb) {
      if (typeof cb === "function") cb(err);
      for (let i = 0; i < sender._queue.length; i++) {
        const params = sender._queue[i];
        const callback = params[params.length - 1];
        if (typeof callback === "function") callback(err);
      }
    }
    function onError(sender, err, cb) {
      callCallbacks(sender, err, cb);
      sender.onerror(err);
    }
  }
});

// node_modules/ws/lib/event-target.js
var require_event_target = __commonJS({
  "node_modules/ws/lib/event-target.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var { kForOnEventAttribute, kListener } = require_constants();
    var kCode = /* @__PURE__ */ Symbol("kCode");
    var kData = /* @__PURE__ */ Symbol("kData");
    var kError = /* @__PURE__ */ Symbol("kError");
    var kMessage = /* @__PURE__ */ Symbol("kMessage");
    var kReason = /* @__PURE__ */ Symbol("kReason");
    var kTarget = /* @__PURE__ */ Symbol("kTarget");
    var kType = /* @__PURE__ */ Symbol("kType");
    var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
    var Event2 = class {
      /**
       * Create a new `Event`.
       *
       * @param {String} type The name of the event
       * @throws {TypeError} If the `type` argument is not specified
       */
      constructor(type) {
        this[kTarget] = null;
        this[kType] = type;
      }
      /**
       * @type {*}
       */
      get target() {
        return this[kTarget];
      }
      /**
       * @type {String}
       */
      get type() {
        return this[kType];
      }
    };
    Object.defineProperty(Event2.prototype, "target", { enumerable: true });
    Object.defineProperty(Event2.prototype, "type", { enumerable: true });
    var CloseEvent = class extends Event2 {
      /**
       * Create a new `CloseEvent`.
       *
       * @param {String} type The name of the event
       * @param {Object} [options] A dictionary object that allows for setting
       *     attributes via object members of the same name
       * @param {Number} [options.code=0] The status code explaining why the
       *     connection was closed
       * @param {String} [options.reason=''] A human-readable string explaining why
       *     the connection was closed
       * @param {Boolean} [options.wasClean=false] Indicates whether or not the
       *     connection was cleanly closed
       */
      constructor(type, options = {}) {
        super(type);
        this[kCode] = options.code === void 0 ? 0 : options.code;
        this[kReason] = options.reason === void 0 ? "" : options.reason;
        this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
      }
      /**
       * @type {Number}
       */
      get code() {
        return this[kCode];
      }
      /**
       * @type {String}
       */
      get reason() {
        return this[kReason];
      }
      /**
       * @type {Boolean}
       */
      get wasClean() {
        return this[kWasClean];
      }
    };
    Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
    Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
    Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
    var ErrorEvent = class extends Event2 {
      /**
       * Create a new `ErrorEvent`.
       *
       * @param {String} type The name of the event
       * @param {Object} [options] A dictionary object that allows for setting
       *     attributes via object members of the same name
       * @param {*} [options.error=null] The error that generated this event
       * @param {String} [options.message=''] The error message
       */
      constructor(type, options = {}) {
        super(type);
        this[kError] = options.error === void 0 ? null : options.error;
        this[kMessage] = options.message === void 0 ? "" : options.message;
      }
      /**
       * @type {*}
       */
      get error() {
        return this[kError];
      }
      /**
       * @type {String}
       */
      get message() {
        return this[kMessage];
      }
    };
    Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
    Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
    var MessageEvent = class extends Event2 {
      /**
       * Create a new `MessageEvent`.
       *
       * @param {String} type The name of the event
       * @param {Object} [options] A dictionary object that allows for setting
       *     attributes via object members of the same name
       * @param {*} [options.data=null] The message content
       */
      constructor(type, options = {}) {
        super(type);
        this[kData] = options.data === void 0 ? null : options.data;
      }
      /**
       * @type {*}
       */
      get data() {
        return this[kData];
      }
    };
    Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
    var EventTarget = {
      /**
       * Register an event listener.
       *
       * @param {String} type A string representing the event type to listen for
       * @param {(Function|Object)} handler The listener to add
       * @param {Object} [options] An options object specifies characteristics about
       *     the event listener
       * @param {Boolean} [options.once=false] A `Boolean` indicating that the
       *     listener should be invoked at most once after being added. If `true`,
       *     the listener would be automatically removed when invoked.
       * @public
       */
      addEventListener(type, handler, options = {}) {
        for (const listener of this.listeners(type)) {
          if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
            return;
          }
        }
        let wrapper;
        if (type === "message") {
          wrapper = function onMessage(data, isBinary) {
            const event = new MessageEvent("message", {
              data: isBinary ? data : data.toString()
            });
            event[kTarget] = this;
            callListener(handler, this, event);
          };
        } else if (type === "close") {
          wrapper = function onClose(code, message) {
            const event = new CloseEvent("close", {
              code,
              reason: message.toString(),
              wasClean: this._closeFrameReceived && this._closeFrameSent
            });
            event[kTarget] = this;
            callListener(handler, this, event);
          };
        } else if (type === "error") {
          wrapper = function onError(error) {
            const event = new ErrorEvent("error", {
              error,
              message: error.message
            });
            event[kTarget] = this;
            callListener(handler, this, event);
          };
        } else if (type === "open") {
          wrapper = function onOpen() {
            const event = new Event2("open");
            event[kTarget] = this;
            callListener(handler, this, event);
          };
        } else {
          return;
        }
        wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
        wrapper[kListener] = handler;
        if (options.once) {
          this.once(type, wrapper);
        } else {
          this.on(type, wrapper);
        }
      },
      /**
       * Remove an event listener.
       *
       * @param {String} type A string representing the event type to remove
       * @param {(Function|Object)} handler The listener to remove
       * @public
       */
      removeEventListener(type, handler) {
        for (const listener of this.listeners(type)) {
          if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
            this.removeListener(type, listener);
            break;
          }
        }
      }
    };
    module2.exports = {
      CloseEvent,
      ErrorEvent,
      Event: Event2,
      EventTarget,
      MessageEvent
    };
    function callListener(listener, thisArg, event) {
      if (typeof listener === "object" && listener.handleEvent) {
        listener.handleEvent.call(listener, event);
      } else {
        listener.call(thisArg, event);
      }
    }
  }
});

// node_modules/ws/lib/extension.js
var require_extension = __commonJS({
  "node_modules/ws/lib/extension.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var { tokenChars } = require_validation();
    function push(dest, name, elem) {
      if (dest[name] === void 0) dest[name] = [elem];
      else dest[name].push(elem);
    }
    function parse(header) {
      const offers = /* @__PURE__ */ Object.create(null);
      let params = /* @__PURE__ */ Object.create(null);
      let mustUnescape = false;
      let isEscaping = false;
      let inQuotes = false;
      let extensionName;
      let paramName;
      let start = -1;
      let code = -1;
      let end = -1;
      let i = 0;
      for (; i < header.length; i++) {
        code = header.charCodeAt(i);
        if (extensionName === void 0) {
          if (end === -1 && tokenChars[code] === 1) {
            if (start === -1) start = i;
          } else if (i !== 0 && (code === 32 || code === 9)) {
            if (end === -1 && start !== -1) end = i;
          } else if (code === 59 || code === 44) {
            if (start === -1) {
              throw new SyntaxError(`Unexpected character at index ${i}`);
            }
            if (end === -1) end = i;
            const name = header.slice(start, end);
            if (code === 44) {
              push(offers, name, params);
              params = /* @__PURE__ */ Object.create(null);
            } else {
              extensionName = name;
            }
            start = end = -1;
          } else {
            throw new SyntaxError(`Unexpected character at index ${i}`);
          }
        } else if (paramName === void 0) {
          if (end === -1 && tokenChars[code] === 1) {
            if (start === -1) start = i;
          } else if (code === 32 || code === 9) {
            if (end === -1 && start !== -1) end = i;
          } else if (code === 59 || code === 44) {
            if (start === -1) {
              throw new SyntaxError(`Unexpected character at index ${i}`);
            }
            if (end === -1) end = i;
            push(params, header.slice(start, end), true);
            if (code === 44) {
              push(offers, extensionName, params);
              params = /* @__PURE__ */ Object.create(null);
              extensionName = void 0;
            }
            start = end = -1;
          } else if (code === 61 && start !== -1 && end === -1) {
            paramName = header.slice(start, i);
            start = end = -1;
          } else {
            throw new SyntaxError(`Unexpected character at index ${i}`);
          }
        } else {
          if (isEscaping) {
            if (tokenChars[code] !== 1) {
              throw new SyntaxError(`Unexpected character at index ${i}`);
            }
            if (start === -1) start = i;
            else if (!mustUnescape) mustUnescape = true;
            isEscaping = false;
          } else if (inQuotes) {
            if (tokenChars[code] === 1) {
              if (start === -1) start = i;
            } else if (code === 34 && start !== -1) {
              inQuotes = false;
              end = i;
            } else if (code === 92) {
              isEscaping = true;
            } else {
              throw new SyntaxError(`Unexpected character at index ${i}`);
            }
          } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
            inQuotes = true;
          } else if (end === -1 && tokenChars[code] === 1) {
            if (start === -1) start = i;
          } else if (start !== -1 && (code === 32 || code === 9)) {
            if (end === -1) end = i;
          } else if (code === 59 || code === 44) {
            if (start === -1) {
              throw new SyntaxError(`Unexpected character at index ${i}`);
            }
            if (end === -1) end = i;
            let value = header.slice(start, end);
            if (mustUnescape) {
              value = value.replace(/\\/g, "");
              mustUnescape = false;
            }
            push(params, paramName, value);
            if (code === 44) {
              push(offers, extensionName, params);
              params = /* @__PURE__ */ Object.create(null);
              extensionName = void 0;
            }
            paramName = void 0;
            start = end = -1;
          } else {
            throw new SyntaxError(`Unexpected character at index ${i}`);
          }
        }
      }
      if (start === -1 || inQuotes || code === 32 || code === 9) {
        throw new SyntaxError("Unexpected end of input");
      }
      if (end === -1) end = i;
      const token = header.slice(start, end);
      if (extensionName === void 0) {
        push(offers, token, params);
      } else {
        if (paramName === void 0) {
          push(params, token, true);
        } else if (mustUnescape) {
          push(params, paramName, token.replace(/\\/g, ""));
        } else {
          push(params, paramName, token);
        }
        push(offers, extensionName, params);
      }
      return offers;
    }
    function format3(extensions) {
      return Object.keys(extensions).map((extension) => {
        let configurations = extensions[extension];
        if (!Array.isArray(configurations)) configurations = [configurations];
        return configurations.map((params) => {
          return [extension].concat(
            Object.keys(params).map((k) => {
              let values = params[k];
              if (!Array.isArray(values)) values = [values];
              return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
            })
          ).join("; ");
        }).join(", ");
      }).join(", ");
    }
    module2.exports = { format: format3, parse };
  }
});

// node_modules/ws/lib/websocket.js
var require_websocket = __commonJS({
  "node_modules/ws/lib/websocket.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var EventEmitter = require("events");
    var https = require("https");
    var http = require("http");
    var net = require("net");
    var tls = require("tls");
    var { randomBytes, createHash } = require("crypto");
    var { Duplex, Readable } = require("stream");
    var { URL: URL2 } = require("url");
    var PerMessageDeflate = require_permessage_deflate();
    var Receiver = require_receiver();
    var Sender = require_sender();
    var { isBlob } = require_validation();
    var {
      BINARY_TYPES,
      CLOSE_TIMEOUT,
      EMPTY_BUFFER,
      GUID,
      kForOnEventAttribute,
      kListener,
      kStatusCode,
      kWebSocket,
      NOOP
    } = require_constants();
    var {
      EventTarget: { addEventListener, removeEventListener }
    } = require_event_target();
    var { format: format3, parse } = require_extension();
    var { toBuffer } = require_buffer_util();
    var kAborted = /* @__PURE__ */ Symbol("kAborted");
    var protocolVersions = [8, 13];
    var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
    var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
    var WebSocket2 = class _WebSocket extends EventEmitter {
      /**
       * Create a new `WebSocket`.
       *
       * @param {(String|URL)} address The URL to which to connect
       * @param {(String|String[])} [protocols] The subprotocols
       * @param {Object} [options] Connection options
       */
      constructor(address, protocols, options) {
        super();
        this._binaryType = BINARY_TYPES[0];
        this._closeCode = 1006;
        this._closeFrameReceived = false;
        this._closeFrameSent = false;
        this._closeMessage = EMPTY_BUFFER;
        this._closeTimer = null;
        this._errorEmitted = false;
        this._extensions = {};
        this._paused = false;
        this._protocol = "";
        this._readyState = _WebSocket.CONNECTING;
        this._receiver = null;
        this._sender = null;
        this._socket = null;
        if (address !== null) {
          this._bufferedAmount = 0;
          this._isServer = false;
          this._redirects = 0;
          if (protocols === void 0) {
            protocols = [];
          } else if (!Array.isArray(protocols)) {
            if (typeof protocols === "object" && protocols !== null) {
              options = protocols;
              protocols = [];
            } else {
              protocols = [protocols];
            }
          }
          initAsClient(this, address, protocols, options);
        } else {
          this._autoPong = options.autoPong;
          this._closeTimeout = options.closeTimeout;
          this._isServer = true;
        }
      }
      /**
       * For historical reasons, the custom "nodebuffer" type is used by the default
       * instead of "blob".
       *
       * @type {String}
       */
      get binaryType() {
        return this._binaryType;
      }
      set binaryType(type) {
        if (!BINARY_TYPES.includes(type)) return;
        this._binaryType = type;
        if (this._receiver) this._receiver._binaryType = type;
      }
      /**
       * @type {Number}
       */
      get bufferedAmount() {
        if (!this._socket) return this._bufferedAmount;
        return this._socket._writableState.length + this._sender._bufferedBytes;
      }
      /**
       * @type {String}
       */
      get extensions() {
        return Object.keys(this._extensions).join();
      }
      /**
       * @type {Boolean}
       */
      get isPaused() {
        return this._paused;
      }
      /**
       * @type {Function}
       */
      /* istanbul ignore next */
      get onclose() {
        return null;
      }
      /**
       * @type {Function}
       */
      /* istanbul ignore next */
      get onerror() {
        return null;
      }
      /**
       * @type {Function}
       */
      /* istanbul ignore next */
      get onopen() {
        return null;
      }
      /**
       * @type {Function}
       */
      /* istanbul ignore next */
      get onmessage() {
        return null;
      }
      /**
       * @type {String}
       */
      get protocol() {
        return this._protocol;
      }
      /**
       * @type {Number}
       */
      get readyState() {
        return this._readyState;
      }
      /**
       * @type {String}
       */
      get url() {
        return this._url;
      }
      /**
       * Set up the socket and the internal resources.
       *
       * @param {Duplex} socket The network socket between the server and client
       * @param {Buffer} head The first packet of the upgraded stream
       * @param {Object} options Options object
       * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
       *     any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
       *     multiple times in the same tick
       * @param {Function} [options.generateMask] The function used to generate the
       *     masking key
       * @param {Number} [options.maxPayload=0] The maximum allowed message size
       * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
       *     not to skip UTF-8 validation for text and close messages
       * @private
       */
      setSocket(socket, head, options) {
        const receiver = new Receiver({
          allowSynchronousEvents: options.allowSynchronousEvents,
          binaryType: this.binaryType,
          extensions: this._extensions,
          isServer: this._isServer,
          maxPayload: options.maxPayload,
          skipUTF8Validation: options.skipUTF8Validation
        });
        const sender = new Sender(socket, this._extensions, options.generateMask);
        this._receiver = receiver;
        this._sender = sender;
        this._socket = socket;
        receiver[kWebSocket] = this;
        sender[kWebSocket] = this;
        socket[kWebSocket] = this;
        receiver.on("conclude", receiverOnConclude);
        receiver.on("drain", receiverOnDrain);
        receiver.on("error", receiverOnError);
        receiver.on("message", receiverOnMessage);
        receiver.on("ping", receiverOnPing);
        receiver.on("pong", receiverOnPong);
        sender.onerror = senderOnError;
        if (socket.setTimeout) socket.setTimeout(0);
        if (socket.setNoDelay) socket.setNoDelay();
        if (head.length > 0) socket.unshift(head);
        socket.on("close", socketOnClose);
        socket.on("data", socketOnData);
        socket.on("end", socketOnEnd);
        socket.on("error", socketOnError);
        this._readyState = _WebSocket.OPEN;
        this.emit("open");
      }
      /**
       * Emit the `'close'` event.
       *
       * @private
       */
      emitClose() {
        if (!this._socket) {
          this._readyState = _WebSocket.CLOSED;
          this.emit("close", this._closeCode, this._closeMessage);
          return;
        }
        if (this._extensions[PerMessageDeflate.extensionName]) {
          this._extensions[PerMessageDeflate.extensionName].cleanup();
        }
        this._receiver.removeAllListeners();
        this._readyState = _WebSocket.CLOSED;
        this.emit("close", this._closeCode, this._closeMessage);
      }
      /**
       * Start a closing handshake.
       *
       *          +----------+   +-----------+   +----------+
       *     - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
       *    |     +----------+   +-----------+   +----------+     |
       *          +----------+   +-----------+         |
       * CLOSING  |ws.close()|<--|close frame|<--+-----+       CLOSING
       *          +----------+   +-----------+   |
       *    |           |                        |   +---+        |
       *                +------------------------+-->|fin| - - - -
       *    |         +---+                      |   +---+
       *     - - - - -|fin|<---------------------+
       *              +---+
       *
       * @param {Number} [code] Status code explaining why the connection is closing
       * @param {(String|Buffer)} [data] The reason why the connection is
       *     closing
       * @public
       */
      close(code, data) {
        if (this.readyState === _WebSocket.CLOSED) return;
        if (this.readyState === _WebSocket.CONNECTING) {
          const msg = "WebSocket was closed before the connection was established";
          abortHandshake(this, this._req, msg);
          return;
        }
        if (this.readyState === _WebSocket.CLOSING) {
          if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
            this._socket.end();
          }
          return;
        }
        this._readyState = _WebSocket.CLOSING;
        this._sender.close(code, data, !this._isServer, (err) => {
          if (err) return;
          this._closeFrameSent = true;
          if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
            this._socket.end();
          }
        });
        setCloseTimer(this);
      }
      /**
       * Pause the socket.
       *
       * @public
       */
      pause() {
        if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
          return;
        }
        this._paused = true;
        this._socket.pause();
      }
      /**
       * Send a ping.
       *
       * @param {*} [data] The data to send
       * @param {Boolean} [mask] Indicates whether or not to mask `data`
       * @param {Function} [cb] Callback which is executed when the ping is sent
       * @public
       */
      ping(data, mask, cb) {
        if (this.readyState === _WebSocket.CONNECTING) {
          throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
        }
        if (typeof data === "function") {
          cb = data;
          data = mask = void 0;
        } else if (typeof mask === "function") {
          cb = mask;
          mask = void 0;
        }
        if (typeof data === "number") data = data.toString();
        if (this.readyState !== _WebSocket.OPEN) {
          sendAfterClose(this, data, cb);
          return;
        }
        if (mask === void 0) mask = !this._isServer;
        this._sender.ping(data || EMPTY_BUFFER, mask, cb);
      }
      /**
       * Send a pong.
       *
       * @param {*} [data] The data to send
       * @param {Boolean} [mask] Indicates whether or not to mask `data`
       * @param {Function} [cb] Callback which is executed when the pong is sent
       * @public
       */
      pong(data, mask, cb) {
        if (this.readyState === _WebSocket.CONNECTING) {
          throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
        }
        if (typeof data === "function") {
          cb = data;
          data = mask = void 0;
        } else if (typeof mask === "function") {
          cb = mask;
          mask = void 0;
        }
        if (typeof data === "number") data = data.toString();
        if (this.readyState !== _WebSocket.OPEN) {
          sendAfterClose(this, data, cb);
          return;
        }
        if (mask === void 0) mask = !this._isServer;
        this._sender.pong(data || EMPTY_BUFFER, mask, cb);
      }
      /**
       * Resume the socket.
       *
       * @public
       */
      resume() {
        if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
          return;
        }
        this._paused = false;
        if (!this._receiver._writableState.needDrain) this._socket.resume();
      }
      /**
       * Send a data message.
       *
       * @param {*} data The message to send
       * @param {Object} [options] Options object
       * @param {Boolean} [options.binary] Specifies whether `data` is binary or
       *     text
       * @param {Boolean} [options.compress] Specifies whether or not to compress
       *     `data`
       * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
       *     last one
       * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
       * @param {Function} [cb] Callback which is executed when data is written out
       * @public
       */
      send(data, options, cb) {
        if (this.readyState === _WebSocket.CONNECTING) {
          throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
        }
        if (typeof options === "function") {
          cb = options;
          options = {};
        }
        if (typeof data === "number") data = data.toString();
        if (this.readyState !== _WebSocket.OPEN) {
          sendAfterClose(this, data, cb);
          return;
        }
        const opts = {
          binary: typeof data !== "string",
          mask: !this._isServer,
          compress: true,
          fin: true,
          ...options
        };
        if (!this._extensions[PerMessageDeflate.extensionName]) {
          opts.compress = false;
        }
        this._sender.send(data || EMPTY_BUFFER, opts, cb);
      }
      /**
       * Forcibly close the connection.
       *
       * @public
       */
      terminate() {
        if (this.readyState === _WebSocket.CLOSED) return;
        if (this.readyState === _WebSocket.CONNECTING) {
          const msg = "WebSocket was closed before the connection was established";
          abortHandshake(this, this._req, msg);
          return;
        }
        if (this._socket) {
          this._readyState = _WebSocket.CLOSING;
          this._socket.destroy();
        }
      }
    };
    Object.defineProperty(WebSocket2, "CONNECTING", {
      enumerable: true,
      value: readyStates.indexOf("CONNECTING")
    });
    Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
      enumerable: true,
      value: readyStates.indexOf("CONNECTING")
    });
    Object.defineProperty(WebSocket2, "OPEN", {
      enumerable: true,
      value: readyStates.indexOf("OPEN")
    });
    Object.defineProperty(WebSocket2.prototype, "OPEN", {
      enumerable: true,
      value: readyStates.indexOf("OPEN")
    });
    Object.defineProperty(WebSocket2, "CLOSING", {
      enumerable: true,
      value: readyStates.indexOf("CLOSING")
    });
    Object.defineProperty(WebSocket2.prototype, "CLOSING", {
      enumerable: true,
      value: readyStates.indexOf("CLOSING")
    });
    Object.defineProperty(WebSocket2, "CLOSED", {
      enumerable: true,
      value: readyStates.indexOf("CLOSED")
    });
    Object.defineProperty(WebSocket2.prototype, "CLOSED", {
      enumerable: true,
      value: readyStates.indexOf("CLOSED")
    });
    [
      "binaryType",
      "bufferedAmount",
      "extensions",
      "isPaused",
      "protocol",
      "readyState",
      "url"
    ].forEach((property) => {
      Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
    });
    ["open", "error", "close", "message"].forEach((method) => {
      Object.defineProperty(WebSocket2.prototype, `on${method}`, {
        enumerable: true,
        get() {
          for (const listener of this.listeners(method)) {
            if (listener[kForOnEventAttribute]) return listener[kListener];
          }
          return null;
        },
        set(handler) {
          for (const listener of this.listeners(method)) {
            if (listener[kForOnEventAttribute]) {
              this.removeListener(method, listener);
              break;
            }
          }
          if (typeof handler !== "function") return;
          this.addEventListener(method, handler, {
            [kForOnEventAttribute]: true
          });
        }
      });
    });
    WebSocket2.prototype.addEventListener = addEventListener;
    WebSocket2.prototype.removeEventListener = removeEventListener;
    module2.exports = WebSocket2;
    function initAsClient(websocket, address, protocols, options) {
      const opts = {
        allowSynchronousEvents: true,
        autoPong: true,
        closeTimeout: CLOSE_TIMEOUT,
        protocolVersion: protocolVersions[1],
        maxPayload: 100 * 1024 * 1024,
        skipUTF8Validation: false,
        perMessageDeflate: true,
        followRedirects: false,
        maxRedirects: 10,
        ...options,
        socketPath: void 0,
        hostname: void 0,
        protocol: void 0,
        timeout: void 0,
        method: "GET",
        host: void 0,
        path: void 0,
        port: void 0
      };
      websocket._autoPong = opts.autoPong;
      websocket._closeTimeout = opts.closeTimeout;
      if (!protocolVersions.includes(opts.protocolVersion)) {
        throw new RangeError(
          `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
        );
      }
      let parsedUrl;
      if (address instanceof URL2) {
        parsedUrl = address;
      } else {
        try {
          parsedUrl = new URL2(address);
        } catch {
          throw new SyntaxError(`Invalid URL: ${address}`);
        }
      }
      if (parsedUrl.protocol === "http:") {
        parsedUrl.protocol = "ws:";
      } else if (parsedUrl.protocol === "https:") {
        parsedUrl.protocol = "wss:";
      }
      websocket._url = parsedUrl.href;
      const isSecure = parsedUrl.protocol === "wss:";
      const isIpcUrl = parsedUrl.protocol === "ws+unix:";
      let invalidUrlMessage;
      if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
        invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
      } else if (isIpcUrl && !parsedUrl.pathname) {
        invalidUrlMessage = "The URL's pathname is empty";
      } else if (parsedUrl.hash) {
        invalidUrlMessage = "The URL contains a fragment identifier";
      }
      if (invalidUrlMessage) {
        const err = new SyntaxError(invalidUrlMessage);
        if (websocket._redirects === 0) {
          throw err;
        } else {
          emitErrorAndClose(websocket, err);
          return;
        }
      }
      const defaultPort = isSecure ? 443 : 80;
      const key = randomBytes(16).toString("base64");
      const request = isSecure ? https.request : http.request;
      const protocolSet = /* @__PURE__ */ new Set();
      let perMessageDeflate;
      opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
      opts.defaultPort = opts.defaultPort || defaultPort;
      opts.port = parsedUrl.port || defaultPort;
      opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
      opts.headers = {
        ...opts.headers,
        "Sec-WebSocket-Version": opts.protocolVersion,
        "Sec-WebSocket-Key": key,
        Connection: "Upgrade",
        Upgrade: "websocket"
      };
      opts.path = parsedUrl.pathname + parsedUrl.search;
      opts.timeout = opts.handshakeTimeout;
      if (opts.perMessageDeflate) {
        perMessageDeflate = new PerMessageDeflate({
          ...opts.perMessageDeflate,
          isServer: false,
          maxPayload: opts.maxPayload
        });
        opts.headers["Sec-WebSocket-Extensions"] = format3({
          [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
        });
      }
      if (protocols.length) {
        for (const protocol of protocols) {
          if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
            throw new SyntaxError(
              "An invalid or duplicated subprotocol was specified"
            );
          }
          protocolSet.add(protocol);
        }
        opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
      }
      if (opts.origin) {
        if (opts.protocolVersion < 13) {
          opts.headers["Sec-WebSocket-Origin"] = opts.origin;
        } else {
          opts.headers.Origin = opts.origin;
        }
      }
      if (parsedUrl.username || parsedUrl.password) {
        opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
      }
      if (isIpcUrl) {
        const parts = opts.path.split(":");
        opts.socketPath = parts[0];
        opts.path = parts[1];
      }
      let req;
      if (opts.followRedirects) {
        if (websocket._redirects === 0) {
          websocket._originalIpc = isIpcUrl;
          websocket._originalSecure = isSecure;
          websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
          const headers = options && options.headers;
          options = { ...options, headers: {} };
          if (headers) {
            for (const [key2, value] of Object.entries(headers)) {
              options.headers[key2.toLowerCase()] = value;
            }
          }
        } else if (websocket.listenerCount("redirect") === 0) {
          const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
          if (!isSameHost || websocket._originalSecure && !isSecure) {
            delete opts.headers.authorization;
            delete opts.headers.cookie;
            if (!isSameHost) delete opts.headers.host;
            opts.auth = void 0;
          }
        }
        if (opts.auth && !options.headers.authorization) {
          options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
        }
        req = websocket._req = request(opts);
        if (websocket._redirects) {
          websocket.emit("redirect", websocket.url, req);
        }
      } else {
        req = websocket._req = request(opts);
      }
      if (opts.timeout) {
        req.on("timeout", () => {
          abortHandshake(websocket, req, "Opening handshake has timed out");
        });
      }
      req.on("error", (err) => {
        if (req === null || req[kAborted]) return;
        req = websocket._req = null;
        emitErrorAndClose(websocket, err);
      });
      req.on("response", (res) => {
        const location2 = res.headers.location;
        const statusCode = res.statusCode;
        if (location2 && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
          if (++websocket._redirects > opts.maxRedirects) {
            abortHandshake(websocket, req, "Maximum redirects exceeded");
            return;
          }
          req.abort();
          let addr;
          try {
            addr = new URL2(location2, address);
          } catch (e) {
            const err = new SyntaxError(`Invalid URL: ${location2}`);
            emitErrorAndClose(websocket, err);
            return;
          }
          initAsClient(websocket, addr, protocols, options);
        } else if (!websocket.emit("unexpected-response", req, res)) {
          abortHandshake(
            websocket,
            req,
            `Unexpected server response: ${res.statusCode}`
          );
        }
      });
      req.on("upgrade", (res, socket, head) => {
        websocket.emit("upgrade", res);
        if (websocket.readyState !== WebSocket2.CONNECTING) return;
        req = websocket._req = null;
        const upgrade = res.headers.upgrade;
        if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
          abortHandshake(websocket, socket, "Invalid Upgrade header");
          return;
        }
        const digest = createHash("sha1").update(key + GUID).digest("base64");
        if (res.headers["sec-websocket-accept"] !== digest) {
          abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
          return;
        }
        const serverProt = res.headers["sec-websocket-protocol"];
        let protError;
        if (serverProt !== void 0) {
          if (!protocolSet.size) {
            protError = "Server sent a subprotocol but none was requested";
          } else if (!protocolSet.has(serverProt)) {
            protError = "Server sent an invalid subprotocol";
          }
        } else if (protocolSet.size) {
          protError = "Server sent no subprotocol";
        }
        if (protError) {
          abortHandshake(websocket, socket, protError);
          return;
        }
        if (serverProt) websocket._protocol = serverProt;
        const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
        if (secWebSocketExtensions !== void 0) {
          if (!perMessageDeflate) {
            const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
            abortHandshake(websocket, socket, message);
            return;
          }
          let extensions;
          try {
            extensions = parse(secWebSocketExtensions);
          } catch (err) {
            const message = "Invalid Sec-WebSocket-Extensions header";
            abortHandshake(websocket, socket, message);
            return;
          }
          const extensionNames = Object.keys(extensions);
          if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
            const message = "Server indicated an extension that was not requested";
            abortHandshake(websocket, socket, message);
            return;
          }
          try {
            perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
          } catch (err) {
            const message = "Invalid Sec-WebSocket-Extensions header";
            abortHandshake(websocket, socket, message);
            return;
          }
          websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
        }
        websocket.setSocket(socket, head, {
          allowSynchronousEvents: opts.allowSynchronousEvents,
          generateMask: opts.generateMask,
          maxPayload: opts.maxPayload,
          skipUTF8Validation: opts.skipUTF8Validation
        });
      });
      if (opts.finishRequest) {
        opts.finishRequest(req, websocket);
      } else {
        req.end();
      }
    }
    function emitErrorAndClose(websocket, err) {
      websocket._readyState = WebSocket2.CLOSING;
      websocket._errorEmitted = true;
      websocket.emit("error", err);
      websocket.emitClose();
    }
    function netConnect(options) {
      options.path = options.socketPath;
      return net.connect(options);
    }
    function tlsConnect(options) {
      options.path = void 0;
      if (!options.servername && options.servername !== "") {
        options.servername = net.isIP(options.host) ? "" : options.host;
      }
      return tls.connect(options);
    }
    function abortHandshake(websocket, stream, message) {
      websocket._readyState = WebSocket2.CLOSING;
      const err = new Error(message);
      Error.captureStackTrace(err, abortHandshake);
      if (stream.setHeader) {
        stream[kAborted] = true;
        stream.abort();
        if (stream.socket && !stream.socket.destroyed) {
          stream.socket.destroy();
        }
        process.nextTick(emitErrorAndClose, websocket, err);
      } else {
        stream.destroy(err);
        stream.once("error", websocket.emit.bind(websocket, "error"));
        stream.once("close", websocket.emitClose.bind(websocket));
      }
    }
    function sendAfterClose(websocket, data, cb) {
      if (data) {
        const length = isBlob(data) ? data.size : toBuffer(data).length;
        if (websocket._socket) websocket._sender._bufferedBytes += length;
        else websocket._bufferedAmount += length;
      }
      if (cb) {
        const err = new Error(
          `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
        );
        process.nextTick(cb, err);
      }
    }
    function receiverOnConclude(code, reason) {
      const websocket = this[kWebSocket];
      websocket._closeFrameReceived = true;
      websocket._closeMessage = reason;
      websocket._closeCode = code;
      if (websocket._socket[kWebSocket] === void 0) return;
      websocket._socket.removeListener("data", socketOnData);
      process.nextTick(resume, websocket._socket);
      if (code === 1005) websocket.close();
      else websocket.close(code, reason);
    }
    function receiverOnDrain() {
      const websocket = this[kWebSocket];
      if (!websocket.isPaused) websocket._socket.resume();
    }
    function receiverOnError(err) {
      const websocket = this[kWebSocket];
      if (websocket._socket[kWebSocket] !== void 0) {
        websocket._socket.removeListener("data", socketOnData);
        process.nextTick(resume, websocket._socket);
        websocket.close(err[kStatusCode]);
      }
      if (!websocket._errorEmitted) {
        websocket._errorEmitted = true;
        websocket.emit("error", err);
      }
    }
    function receiverOnFinish() {
      this[kWebSocket].emitClose();
    }
    function receiverOnMessage(data, isBinary) {
      this[kWebSocket].emit("message", data, isBinary);
    }
    function receiverOnPing(data) {
      const websocket = this[kWebSocket];
      if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
      websocket.emit("ping", data);
    }
    function receiverOnPong(data) {
      this[kWebSocket].emit("pong", data);
    }
    function resume(stream) {
      stream.resume();
    }
    function senderOnError(err) {
      const websocket = this[kWebSocket];
      if (websocket.readyState === WebSocket2.CLOSED) return;
      if (websocket.readyState === WebSocket2.OPEN) {
        websocket._readyState = WebSocket2.CLOSING;
        setCloseTimer(websocket);
      }
      this._socket.end();
      if (!websocket._errorEmitted) {
        websocket._errorEmitted = true;
        websocket.emit("error", err);
      }
    }
    function setCloseTimer(websocket) {
      websocket._closeTimer = setTimeout(
        websocket._socket.destroy.bind(websocket._socket),
        websocket._closeTimeout
      );
    }
    function socketOnClose() {
      const websocket = this[kWebSocket];
      this.removeListener("close", socketOnClose);
      this.removeListener("data", socketOnData);
      this.removeListener("end", socketOnEnd);
      websocket._readyState = WebSocket2.CLOSING;
      if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
        const chunk = this.read(this._readableState.length);
        websocket._receiver.write(chunk);
      }
      websocket._receiver.end();
      this[kWebSocket] = void 0;
      clearTimeout(websocket._closeTimer);
      if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
        websocket.emitClose();
      } else {
        websocket._receiver.on("error", receiverOnFinish);
        websocket._receiver.on("finish", receiverOnFinish);
      }
    }
    function socketOnData(chunk) {
      if (!this[kWebSocket]._receiver.write(chunk)) {
        this.pause();
      }
    }
    function socketOnEnd() {
      const websocket = this[kWebSocket];
      websocket._readyState = WebSocket2.CLOSING;
      websocket._receiver.end();
      this.end();
    }
    function socketOnError() {
      const websocket = this[kWebSocket];
      this.removeListener("error", socketOnError);
      this.on("error", NOOP);
      if (websocket) {
        websocket._readyState = WebSocket2.CLOSING;
        this.destroy();
      }
    }
  }
});

// node_modules/ws/lib/stream.js
var require_stream = __commonJS({
  "node_modules/ws/lib/stream.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var WebSocket2 = require_websocket();
    var { Duplex } = require("stream");
    function emitClose(stream) {
      stream.emit("close");
    }
    function duplexOnEnd() {
      if (!this.destroyed && this._writableState.finished) {
        this.destroy();
      }
    }
    function duplexOnError(err) {
      this.removeListener("error", duplexOnError);
      this.destroy();
      if (this.listenerCount("error") === 0) {
        this.emit("error", err);
      }
    }
    function createWebSocketStream(ws, options) {
      let terminateOnDestroy = true;
      const duplex = new Duplex({
        ...options,
        autoDestroy: false,
        emitClose: false,
        objectMode: false,
        writableObjectMode: false
      });
      ws.on("message", function message(msg, isBinary) {
        const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
        if (!duplex.push(data)) ws.pause();
      });
      ws.once("error", function error(err) {
        if (duplex.destroyed) return;
        terminateOnDestroy = false;
        duplex.destroy(err);
      });
      ws.once("close", function close() {
        if (duplex.destroyed) return;
        duplex.push(null);
      });
      duplex._destroy = function(err, callback) {
        if (ws.readyState === ws.CLOSED) {
          callback(err);
          process.nextTick(emitClose, duplex);
          return;
        }
        let called = false;
        ws.once("error", function error(err2) {
          called = true;
          callback(err2);
        });
        ws.once("close", function close() {
          if (!called) callback(err);
          process.nextTick(emitClose, duplex);
        });
        if (terminateOnDestroy) ws.terminate();
      };
      duplex._final = function(callback) {
        if (ws.readyState === ws.CONNECTING) {
          ws.once("open", function open() {
            duplex._final(callback);
          });
          return;
        }
        if (ws._socket === null) return;
        if (ws._socket._writableState.finished) {
          callback();
          if (duplex._readableState.endEmitted) duplex.destroy();
        } else {
          ws._socket.once("finish", function finish() {
            callback();
          });
          ws.close();
        }
      };
      duplex._read = function() {
        if (ws.isPaused) ws.resume();
      };
      duplex._write = function(chunk, encoding, callback) {
        if (ws.readyState === ws.CONNECTING) {
          ws.once("open", function open() {
            duplex._write(chunk, encoding, callback);
          });
          return;
        }
        ws.send(chunk, callback);
      };
      duplex.on("end", duplexOnEnd);
      duplex.on("error", duplexOnError);
      return duplex;
    }
    module2.exports = createWebSocketStream;
  }
});

// node_modules/ws/lib/subprotocol.js
var require_subprotocol = __commonJS({
  "node_modules/ws/lib/subprotocol.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var { tokenChars } = require_validation();
    function parse(header) {
      const protocols = /* @__PURE__ */ new Set();
      let start = -1;
      let end = -1;
      let i = 0;
      for (i; i < header.length; i++) {
        const code = header.charCodeAt(i);
        if (end === -1 && tokenChars[code] === 1) {
          if (start === -1) start = i;
        } else if (i !== 0 && (code === 32 || code === 9)) {
          if (end === -1 && start !== -1) end = i;
        } else if (code === 44) {
          if (start === -1) {
            throw new SyntaxError(`Unexpected character at index ${i}`);
          }
          if (end === -1) end = i;
          const protocol2 = header.slice(start, end);
          if (protocols.has(protocol2)) {
            throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
          }
          protocols.add(protocol2);
          start = end = -1;
        } else {
          throw new SyntaxError(`Unexpected character at index ${i}`);
        }
      }
      if (start === -1 || end !== -1) {
        throw new SyntaxError("Unexpected end of input");
      }
      const protocol = header.slice(start, i);
      if (protocols.has(protocol)) {
        throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
      }
      protocols.add(protocol);
      return protocols;
    }
    module2.exports = { parse };
  }
});

// node_modules/ws/lib/websocket-server.js
var require_websocket_server = __commonJS({
  "node_modules/ws/lib/websocket-server.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var EventEmitter = require("events");
    var http = require("http");
    var { Duplex } = require("stream");
    var { createHash } = require("crypto");
    var extension = require_extension();
    var PerMessageDeflate = require_permessage_deflate();
    var subprotocol = require_subprotocol();
    var WebSocket2 = require_websocket();
    var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
    var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
    var RUNNING = 0;
    var CLOSING = 1;
    var CLOSED = 2;
    var WebSocketServer = class extends EventEmitter {
      /**
       * Create a `WebSocketServer` instance.
       *
       * @param {Object} options Configuration options
       * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
       *     any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
       *     multiple times in the same tick
       * @param {Boolean} [options.autoPong=true] Specifies whether or not to
       *     automatically send a pong in response to a ping
       * @param {Number} [options.backlog=511] The maximum length of the queue of
       *     pending connections
       * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
       *     track clients
       * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
       *     wait for the closing handshake to finish after `websocket.close()` is
       *     called
       * @param {Function} [options.handleProtocols] A hook to handle protocols
       * @param {String} [options.host] The hostname where to bind the server
       * @param {Number} [options.maxPayload=104857600] The maximum allowed message
       *     size
       * @param {Boolean} [options.noServer=false] Enable no server mode
       * @param {String} [options.path] Accept only connections matching this path
       * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
       *     permessage-deflate
       * @param {Number} [options.port] The port where to bind the server
       * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
       *     server to use
       * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
       *     not to skip UTF-8 validation for text and close messages
       * @param {Function} [options.verifyClient] A hook to reject connections
       * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
       *     class to use. It must be the `WebSocket` class or class that extends it
       * @param {Function} [callback] A listener for the `listening` event
       */
      constructor(options, callback) {
        super();
        options = {
          allowSynchronousEvents: true,
          autoPong: true,
          maxPayload: 100 * 1024 * 1024,
          skipUTF8Validation: false,
          perMessageDeflate: false,
          handleProtocols: null,
          clientTracking: true,
          closeTimeout: CLOSE_TIMEOUT,
          verifyClient: null,
          noServer: false,
          backlog: null,
          // use default (511 as implemented in net.js)
          server: null,
          host: null,
          path: null,
          port: null,
          WebSocket: WebSocket2,
          ...options
        };
        if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
          throw new TypeError(
            'One and only one of the "port", "server", or "noServer" options must be specified'
          );
        }
        if (options.port != null) {
          this._server = http.createServer((req, res) => {
            const body = http.STATUS_CODES[426];
            res.writeHead(426, {
              "Content-Length": body.length,
              "Content-Type": "text/plain"
            });
            res.end(body);
          });
          this._server.listen(
            options.port,
            options.host,
            options.backlog,
            callback
          );
        } else if (options.server) {
          this._server = options.server;
        }
        if (this._server) {
          const emitConnection = this.emit.bind(this, "connection");
          this._removeListeners = addListeners(this._server, {
            listening: this.emit.bind(this, "listening"),
            error: this.emit.bind(this, "error"),
            upgrade: (req, socket, head) => {
              this.handleUpgrade(req, socket, head, emitConnection);
            }
          });
        }
        if (options.perMessageDeflate === true) options.perMessageDeflate = {};
        if (options.clientTracking) {
          this.clients = /* @__PURE__ */ new Set();
          this._shouldEmitClose = false;
        }
        this.options = options;
        this._state = RUNNING;
      }
      /**
       * Returns the bound address, the address family name, and port of the server
       * as reported by the operating system if listening on an IP socket.
       * If the server is listening on a pipe or UNIX domain socket, the name is
       * returned as a string.
       *
       * @return {(Object|String|null)} The address of the server
       * @public
       */
      address() {
        if (this.options.noServer) {
          throw new Error('The server is operating in "noServer" mode');
        }
        if (!this._server) return null;
        return this._server.address();
      }
      /**
       * Stop the server from accepting new connections and emit the `'close'` event
       * when all existing connections are closed.
       *
       * @param {Function} [cb] A one-time listener for the `'close'` event
       * @public
       */
      close(cb) {
        if (this._state === CLOSED) {
          if (cb) {
            this.once("close", () => {
              cb(new Error("The server is not running"));
            });
          }
          process.nextTick(emitClose, this);
          return;
        }
        if (cb) this.once("close", cb);
        if (this._state === CLOSING) return;
        this._state = CLOSING;
        if (this.options.noServer || this.options.server) {
          if (this._server) {
            this._removeListeners();
            this._removeListeners = this._server = null;
          }
          if (this.clients) {
            if (!this.clients.size) {
              process.nextTick(emitClose, this);
            } else {
              this._shouldEmitClose = true;
            }
          } else {
            process.nextTick(emitClose, this);
          }
        } else {
          const server = this._server;
          this._removeListeners();
          this._removeListeners = this._server = null;
          server.close(() => {
            emitClose(this);
          });
        }
      }
      /**
       * See if a given request should be handled by this server instance.
       *
       * @param {http.IncomingMessage} req Request object to inspect
       * @return {Boolean} `true` if the request is valid, else `false`
       * @public
       */
      shouldHandle(req) {
        if (this.options.path) {
          const index = req.url.indexOf("?");
          const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
          if (pathname !== this.options.path) return false;
        }
        return true;
      }
      /**
       * Handle a HTTP Upgrade request.
       *
       * @param {http.IncomingMessage} req The request object
       * @param {Duplex} socket The network socket between the server and client
       * @param {Buffer} head The first packet of the upgraded stream
       * @param {Function} cb Callback
       * @public
       */
      handleUpgrade(req, socket, head, cb) {
        socket.on("error", socketOnError);
        const key = req.headers["sec-websocket-key"];
        const upgrade = req.headers.upgrade;
        const version = +req.headers["sec-websocket-version"];
        if (req.method !== "GET") {
          const message = "Invalid HTTP method";
          abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
          return;
        }
        if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
          const message = "Invalid Upgrade header";
          abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
          return;
        }
        if (key === void 0 || !keyRegex.test(key)) {
          const message = "Missing or invalid Sec-WebSocket-Key header";
          abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
          return;
        }
        if (version !== 13 && version !== 8) {
          const message = "Missing or invalid Sec-WebSocket-Version header";
          abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
            "Sec-WebSocket-Version": "13, 8"
          });
          return;
        }
        if (!this.shouldHandle(req)) {
          abortHandshake(socket, 400);
          return;
        }
        const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
        let protocols = /* @__PURE__ */ new Set();
        if (secWebSocketProtocol !== void 0) {
          try {
            protocols = subprotocol.parse(secWebSocketProtocol);
          } catch (err) {
            const message = "Invalid Sec-WebSocket-Protocol header";
            abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
            return;
          }
        }
        const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
        const extensions = {};
        if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
          const perMessageDeflate = new PerMessageDeflate({
            ...this.options.perMessageDeflate,
            isServer: true,
            maxPayload: this.options.maxPayload
          });
          try {
            const offers = extension.parse(secWebSocketExtensions);
            if (offers[PerMessageDeflate.extensionName]) {
              perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
              extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
            }
          } catch (err) {
            const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
            abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
            return;
          }
        }
        if (this.options.verifyClient) {
          const info = {
            origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
            secure: !!(req.socket.authorized || req.socket.encrypted),
            req
          };
          if (this.options.verifyClient.length === 2) {
            this.options.verifyClient(info, (verified, code, message, headers) => {
              if (!verified) {
                return abortHandshake(socket, code || 401, message, headers);
              }
              this.completeUpgrade(
                extensions,
                key,
                protocols,
                req,
                socket,
                head,
                cb
              );
            });
            return;
          }
          if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
        }
        this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
      }
      /**
       * Upgrade the connection to WebSocket.
       *
       * @param {Object} extensions The accepted extensions
       * @param {String} key The value of the `Sec-WebSocket-Key` header
       * @param {Set} protocols The subprotocols
       * @param {http.IncomingMessage} req The request object
       * @param {Duplex} socket The network socket between the server and client
       * @param {Buffer} head The first packet of the upgraded stream
       * @param {Function} cb Callback
       * @throws {Error} If called more than once with the same socket
       * @private
       */
      completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
        if (!socket.readable || !socket.writable) return socket.destroy();
        if (socket[kWebSocket]) {
          throw new Error(
            "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
          );
        }
        if (this._state > RUNNING) return abortHandshake(socket, 503);
        const digest = createHash("sha1").update(key + GUID).digest("base64");
        const headers = [
          "HTTP/1.1 101 Switching Protocols",
          "Upgrade: websocket",
          "Connection: Upgrade",
          `Sec-WebSocket-Accept: ${digest}`
        ];
        const ws = new this.options.WebSocket(null, void 0, this.options);
        if (protocols.size) {
          const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
          if (protocol) {
            headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
            ws._protocol = protocol;
          }
        }
        if (extensions[PerMessageDeflate.extensionName]) {
          const params = extensions[PerMessageDeflate.extensionName].params;
          const value = extension.format({
            [PerMessageDeflate.extensionName]: [params]
          });
          headers.push(`Sec-WebSocket-Extensions: ${value}`);
          ws._extensions = extensions;
        }
        this.emit("headers", headers, req);
        socket.write(headers.concat("\r\n").join("\r\n"));
        socket.removeListener("error", socketOnError);
        ws.setSocket(socket, head, {
          allowSynchronousEvents: this.options.allowSynchronousEvents,
          maxPayload: this.options.maxPayload,
          skipUTF8Validation: this.options.skipUTF8Validation
        });
        if (this.clients) {
          this.clients.add(ws);
          ws.on("close", () => {
            this.clients.delete(ws);
            if (this._shouldEmitClose && !this.clients.size) {
              process.nextTick(emitClose, this);
            }
          });
        }
        cb(ws, req);
      }
    };
    module2.exports = WebSocketServer;
    function addListeners(server, map) {
      for (const event of Object.keys(map)) server.on(event, map[event]);
      return function removeListeners() {
        for (const event of Object.keys(map)) {
          server.removeListener(event, map[event]);
        }
      };
    }
    function emitClose(server) {
      server._state = CLOSED;
      server.emit("close");
    }
    function socketOnError() {
      this.destroy();
    }
    function abortHandshake(socket, code, message, headers) {
      message = message || http.STATUS_CODES[code];
      headers = {
        Connection: "close",
        "Content-Type": "text/html",
        "Content-Length": Buffer.byteLength(message),
        ...headers
      };
      socket.once("finish", socket.destroy);
      socket.end(
        `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
      );
    }
    function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
      if (server.listenerCount("wsClientError")) {
        const err = new Error(message);
        Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
        server.emit("wsClientError", err, socket, req);
      } else {
        abortHandshake(socket, code, message, headers);
      }
    }
  }
});

// node_modules/ws/index.js
var require_ws = __commonJS({
  "node_modules/ws/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var createWebSocketStream = require_stream();
    var extension = require_extension();
    var PerMessageDeflate = require_permessage_deflate();
    var Receiver = require_receiver();
    var Sender = require_sender();
    var subprotocol = require_subprotocol();
    var WebSocket2 = require_websocket();
    var WebSocketServer = require_websocket_server();
    WebSocket2.createWebSocketStream = createWebSocketStream;
    WebSocket2.extension = extension;
    WebSocket2.PerMessageDeflate = PerMessageDeflate;
    WebSocket2.Receiver = Receiver;
    WebSocket2.Sender = Sender;
    WebSocket2.Server = WebSocketServer;
    WebSocket2.subprotocol = subprotocol;
    WebSocket2.WebSocket = WebSocket2;
    WebSocket2.WebSocketServer = WebSocketServer;
    module2.exports = WebSocket2;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/node/NodeWebSocketTransport.js
var require_NodeWebSocketTransport = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/node/NodeWebSocketTransport.js"(exports2) {
    "use strict";
    init_prefix();
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.NodeWebSocketTransport = void 0;
    var ws_1 = __importDefault2(require_ws());
    var version_js_1 = require_version();
    var NodeWebSocketTransport = class _NodeWebSocketTransport {
      static create(url, headers) {
        return new Promise((resolve5, reject) => {
          const ws = new ws_1.default(url, [], {
            followRedirects: true,
            perMessageDeflate: false,
            allowSynchronousEvents: false,
            maxPayload: 256 * 1024 * 1024,
            // 256Mb
            headers: {
              "User-Agent": `Puppeteer ${version_js_1.packageVersion}`,
              ...headers
            }
          });
          ws.addEventListener("open", () => {
            return resolve5(new _NodeWebSocketTransport(ws));
          });
          ws.addEventListener("error", reject);
        });
      }
      #ws;
      onmessage;
      onclose;
      constructor(ws) {
        this.#ws = ws;
        this.#ws.addEventListener("message", (event) => {
          if (this.onmessage) {
            this.onmessage.call(null, event.data);
          }
        });
        this.#ws.addEventListener("close", () => {
          if (this.onclose) {
            this.onclose.call(null);
          }
        });
        this.#ws.addEventListener("error", () => {
        });
      }
      send(message) {
        this.#ws.send(message);
      }
      close() {
        this.#ws.close();
      }
    };
    exports2.NodeWebSocketTransport = NodeWebSocketTransport;
  }
});

// node_modules/@puppeteer/browsers/lib/cjs/browser-data/types.js
var require_types = __commonJS({
  "node_modules/@puppeteer/browsers/lib/cjs/browser-data/types.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ChromeReleaseChannel = exports2.BrowserTag = exports2.BrowserPlatform = exports2.Browser = void 0;
    var Browser;
    (function(Browser2) {
      Browser2["CHROME"] = "chrome";
      Browser2["CHROMEHEADLESSSHELL"] = "chrome-headless-shell";
      Browser2["CHROMIUM"] = "chromium";
      Browser2["FIREFOX"] = "firefox";
      Browser2["CHROMEDRIVER"] = "chromedriver";
    })(Browser || (exports2.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 || (exports2.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 || (exports2.BrowserTag = BrowserTag = {}));
    var ChromeReleaseChannel;
    (function(ChromeReleaseChannel2) {
      ChromeReleaseChannel2["STABLE"] = "stable";
      ChromeReleaseChannel2["DEV"] = "dev";
      ChromeReleaseChannel2["CANARY"] = "canary";
      ChromeReleaseChannel2["BETA"] = "beta";
    })(ChromeReleaseChannel || (exports2.ChromeReleaseChannel = ChromeReleaseChannel = {}));
  }
});

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

// node_modules/semver/internal/re.js
var require_re = __commonJS({
  "node_modules/semver/internal/re.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var {
      MAX_SAFE_COMPONENT_LENGTH,
      MAX_SAFE_BUILD_LENGTH,
      MAX_LENGTH
    } = require_constants2();
    var debug = require_debug();
    exports2 = module2.exports = {};
    var re = exports2.re = [];
    var safeRe = exports2.safeRe = [];
    var src = exports2.src = [];
    var safeSrc = exports2.safeSrc = [];
    var t = exports2.t = {};
    var R = 0;
    var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
    var safeRegexReplacements = [
      ["\\s", 1],
      ["\\d", MAX_LENGTH],
      [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
    ];
    var makeSafeRegex = (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++;
      debug(name, index, value);
      t[name] = index;
      src[index] = value;
      safeSrc[index] = safe;
      re[index] = new RegExp(value, isGlobal ? "g" : void 0);
      safeRe[index] = new RegExp(safe, isGlobal ? "g" : void 0);
    };
    createToken("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/semver/internal/parse-options.js
var require_parse_options = __commonJS({
  "node_modules/semver/internal/parse-options.js"(exports2, module2) {
    "use strict";
    init_prefix();
    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/semver/internal/identifiers.js
var require_identifiers = __commonJS({
  "node_modules/semver/internal/identifiers.js"(exports2, module2) {
    "use strict";
    init_prefix();
    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/semver/classes/semver.js
var require_semver = __commonJS({
  "node_modules/semver/classes/semver.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var debug = require_debug();
    var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants2();
    var { safeRe: re, t } = require_re();
    var parseOptions = require_parse_options();
    var { compareIdentifiers } = require_identifiers();
    var SemVer = class _SemVer {
      constructor(version, options) {
        options = parseOptions(options);
        if (version instanceof _SemVer) {
          if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
            return version;
          } else {
            version = version.version;
          }
        } else if (typeof version !== "string") {
          throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`);
        }
        if (version.length > MAX_LENGTH) {
          throw new TypeError(
            `version is longer than ${MAX_LENGTH} characters`
          );
        }
        debug("SemVer", version, options);
        this.options = options;
        this.loose = !!options.loose;
        this.includePrerelease = !!options.includePrerelease;
        const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
        if (!m) {
          throw new TypeError(`Invalid Version: ${version}`);
        }
        this.raw = version;
        this.major = +m[1];
        this.minor = +m[2];
        this.patch = +m[3];
        if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
          throw new TypeError("Invalid major version");
        }
        if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
          throw new TypeError("Invalid minor version");
        }
        if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
          throw new TypeError("Invalid patch version");
        }
        if (!m[4]) {
          this.prerelease = [];
        } else {
          this.prerelease = m[4].split(".").map((id) => {
            if (/^[0-9]+$/.test(id)) {
              const num = +id;
              if (num >= 0 && num < MAX_SAFE_INTEGER) {
                return num;
              }
            }
            return id;
          });
        }
        this.build = m[5] ? m[5].split(".") : [];
        this.format();
      }
      format() {
        this.version = `${this.major}.${this.minor}.${this.patch}`;
        if (this.prerelease.length) {
          this.version += `-${this.prerelease.join(".")}`;
        }
        return this.version;
      }
      toString() {
        return this.version;
      }
      compare(other) {
        debug("SemVer.compare", this.version, this.options, other);
        if (!(other instanceof _SemVer)) {
          if (typeof other === "string" && other === this.version) {
            return 0;
          }
          other = new _SemVer(other, this.options);
        }
        if (other.version === this.version) {
          return 0;
        }
        return this.compareMain(other) || this.comparePre(other);
      }
      compareMain(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        if (this.major < other.major) {
          return -1;
        }
        if (this.major > other.major) {
          return 1;
        }
        if (this.minor < other.minor) {
          return -1;
        }
        if (this.minor > other.minor) {
          return 1;
        }
        if (this.patch < other.patch) {
          return -1;
        }
        if (this.patch > other.patch) {
          return 1;
        }
        return 0;
      }
      comparePre(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        if (this.prerelease.length && !other.prerelease.length) {
          return -1;
        } else if (!this.prerelease.length && other.prerelease.length) {
          return 1;
        } else if (!this.prerelease.length && !other.prerelease.length) {
          return 0;
        }
        let i = 0;
        do {
          const a = this.prerelease[i];
          const b = other.prerelease[i];
          debug("prerelease compare", i, a, b);
          if (a === void 0 && b === void 0) {
            return 0;
          } else if (b === void 0) {
            return 1;
          } else if (a === void 0) {
            return -1;
          } else if (a === b) {
            continue;
          } else {
            return compareIdentifiers(a, b);
          }
        } while (++i);
      }
      compareBuild(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        let i = 0;
        do {
          const a = this.build[i];
          const b = other.build[i];
          debug("build compare", i, a, b);
          if (a === void 0 && b === void 0) {
            return 0;
          } else if (b === void 0) {
            return 1;
          } else if (a === void 0) {
            return -1;
          } else if (a === b) {
            continue;
          } else {
            return compareIdentifiers(a, b);
          }
        } while (++i);
      }
      // preminor will bump the version up to the next minor release, and immediately
      // down to pre-release. premajor and prepatch work the same way.
      inc(release, identifier, identifierBase) {
        if (release.startsWith("pre")) {
          if (!identifier && identifierBase === false) {
            throw new Error("invalid increment argument: identifier is empty");
          }
          if (identifier) {
            const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]);
            if (!match || match[1] !== identifier) {
              throw new Error(`invalid identifier: ${identifier}`);
            }
          }
        }
        switch (release) {
          case "premajor":
            this.prerelease.length = 0;
            this.patch = 0;
            this.minor = 0;
            this.major++;
            this.inc("pre", identifier, identifierBase);
            break;
          case "preminor":
            this.prerelease.length = 0;
            this.patch = 0;
            this.minor++;
            this.inc("pre", identifier, identifierBase);
            break;
          case "prepatch":
            this.prerelease.length = 0;
            this.inc("patch", identifier, identifierBase);
            this.inc("pre", identifier, identifierBase);
            break;
          // If the input is a non-prerelease version, this acts the same as
          // prepatch.
          case "prerelease":
            if (this.prerelease.length === 0) {
              this.inc("patch", identifier, identifierBase);
            }
            this.inc("pre", identifier, identifierBase);
            break;
          case "release":
            if (this.prerelease.length === 0) {
              throw new Error(`version ${this.raw} is not a prerelease`);
            }
            this.prerelease.length = 0;
            break;
          case "major":
            if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
              this.major++;
            }
            this.minor = 0;
            this.patch = 0;
            this.prerelease = [];
            break;
          case "minor":
            if (this.patch !== 0 || this.prerelease.length === 0) {
              this.minor++;
            }
            this.patch = 0;
            this.prerelease = [];
            break;
          case "patch":
            if (this.prerelease.length === 0) {
              this.patch++;
            }
            this.prerelease = [];
            break;
          // This probably shouldn't be used publicly.
          // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
          case "pre": {
            const base = Number(identifierBase) ? 1 : 0;
            if (this.prerelease.length === 0) {
              this.prerelease = [base];
            } else {
              let i = this.prerelease.length;
              while (--i >= 0) {
                if (typeof this.prerelease[i] === "number") {
                  this.prerelease[i]++;
                  i = -2;
                }
              }
              if (i === -1) {
                if (identifier === this.prerelease.join(".") && identifierBase === false) {
                  throw new Error("invalid increment argument: identifier already exists");
                }
                this.prerelease.push(base);
              }
            }
            if (identifier) {
              let prerelease = [identifier, base];
              if (identifierBase === false) {
                prerelease = [identifier];
              }
              if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
                if (isNaN(this.prerelease[1])) {
                  this.prerelease = prerelease;
                }
              } else {
                this.prerelease = prerelease;
              }
            }
            break;
          }
          default:
            throw new Error(`invalid increment argument: ${release}`);
        }
        this.raw = this.format();
        if (this.build.length) {
          this.raw += `+${this.build.join(".")}`;
        }
        return this;
      }
    };
    module2.exports = SemVer;
  }
});

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

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

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

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

// node_modules/semver/functions/diff.js
var require_diff = __commonJS({
  "node_modules/semver/functions/diff.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var parse = require_parse();
    var diff = (version1, version2) => {
      const v1 = parse(version1, null, true);
      const v2 = parse(version2, 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/semver/functions/major.js
var require_major = __commonJS({
  "node_modules/semver/functions/major.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var SemVer = require_semver();
    var major = (a, loose) => new SemVer(a, loose).major;
    module2.exports = major;
  }
});

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

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

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

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

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

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

// node_modules/semver/functions/compare-build.js
var require_compare_build = __commonJS({
  "node_modules/semver/functions/compare-build.js"(exports2, module2) {
    "use strict";
    init_prefix();
    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/semver/functions/sort.js
var require_sort = __commonJS({
  "node_modules/semver/functions/sort.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var compareBuild = require_compare_build();
    var sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose));
    module2.exports = sort;
  }
});

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

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

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

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

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

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

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

// node_modules/semver/functions/cmp.js
var require_cmp = __commonJS({
  "node_modules/semver/functions/cmp.js"(exports2, module2) {
    "use strict";
    init_prefix();
    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/semver/functions/coerce.js
var require_coerce = __commonJS({
  "node_modules/semver/functions/coerce.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var SemVer = require_semver();
    var parse = require_parse();
    var { safeRe: re, t } = require_re();
    var coerce = (version, options) => {
      if (version instanceof SemVer) {
        return version;
      }
      if (typeof version === "number") {
        version = String(version);
      }
      if (typeof version !== "string") {
        return null;
      }
      options = options || {};
      let match = null;
      if (!options.rtl) {
        match = version.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(version)) && (!match || match.index + match[0].length !== version.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 parse(`${major}.${minor}.${patch}${prerelease}${build}`, options);
    };
    module2.exports = coerce;
  }
});

// node_modules/semver/internal/lrucache.js
var require_lrucache = __commonJS({
  "node_modules/semver/internal/lrucache.js"(exports2, module2) {
    "use strict";
    init_prefix();
    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/semver/classes/range.js
var require_range = __commonJS({
  "node_modules/semver/classes/range.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var SPACE_CHARACTERS = /\s+/g;
    var Range = class _Range {
      constructor(range, options) {
        options = parseOptions(options);
        if (range instanceof _Range) {
          if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
            return range;
          } else {
            return new _Range(range.raw, options);
          }
        }
        if (range instanceof Comparator) {
          this.raw = range.value;
          this.set = [[range]];
          this.formatted = void 0;
          return this;
        }
        this.options = options;
        this.loose = !!options.loose;
        this.includePrerelease = !!options.includePrerelease;
        this.raw = range.trim().replace(SPACE_CHARACTERS, " ");
        this.set = this.raw.split("||").map((r) => this.parseRange(r.trim())).filter((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));
        debug("hyphen replace", range);
        range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
        debug("comparator trim", range);
        range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
        debug("tilde trim", range);
        range = range.replace(re[t.CARETTRIM], caretTrimReplace);
        debug("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) => {
            debug("loose invalid filter", comp, this.options);
            return !!comp.match(re[t.COMPARATORLOOSE]);
          });
        }
        debug("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(version) {
        if (!version) {
          return false;
        }
        if (typeof version === "string") {
          try {
            version = new SemVer(version, this.options);
          } catch (er) {
            return false;
          }
        }
        for (let i = 0; i < this.set.length; i++) {
          if (testSet(this.set[i], version, 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 debug = require_debug();
    var SemVer = require_semver();
    var {
      safeRe: re,
      t,
      comparatorTrimReplace,
      tildeTrimReplace,
      caretTrimReplace
    } = require_re();
    var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants2();
    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], "");
      debug("comp", comp, options);
      comp = replaceCarets(comp, options);
      debug("caret", comp);
      comp = replaceTildes(comp, options);
      debug("tildes", comp);
      comp = replaceXRanges(comp, options);
      debug("xrange", comp);
      comp = replaceStars(comp, options);
      debug("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 r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
      return comp.replace(r, (_, M, m, p, pr) => {
        debug("tilde", comp, _, M, m, p, pr);
        let ret;
        if (isX(M)) {
          ret = "";
        } else if (isX(m)) {
          ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
        } else if (isX(p)) {
          ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
        } else if (pr) {
          debug("replaceTilde pr", pr);
          ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
        } else {
          ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
        }
        debug("tilde return", ret);
        return ret;
      });
    };
    var replaceCarets = (comp, options) => {
      return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" ");
    };
    var replaceCaret = (comp, options) => {
      debug("caret", comp, options);
      const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
      const z = options.includePrerelease ? "-0" : "";
      return comp.replace(r, (_, M, m, p, pr) => {
        debug("caret", comp, _, M, m, p, pr);
        let ret;
        if (isX(M)) {
          ret = "";
        } else if (isX(m)) {
          ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
        } else if (isX(p)) {
          if (M === "0") {
            ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
          } else {
            ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
          }
        } else if (pr) {
          debug("replaceCaret pr", pr);
          if (M === "0") {
            if (m === "0") {
              ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;
            } else {
              ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
            }
          } else {
            ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;
          }
        } else {
          debug("no pr");
          if (M === "0") {
            if (m === "0") {
              ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`;
            } else {
              ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`;
            }
          } else {
            ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;
          }
        }
        debug("caret return", ret);
        return ret;
      });
    };
    var replaceXRanges = (comp, options) => {
      debug("replaceXRanges", comp, options);
      return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" ");
    };
    var replaceXRange = (comp, options) => {
      comp = comp.trim();
      const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
      return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
        debug("xRange", comp, ret, gtlt, M, m, p, pr);
        const xM = isX(M);
        const xm = xM || isX(m);
        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) {
            m = 0;
          }
          p = 0;
          if (gtlt === ">") {
            gtlt = ">=";
            if (xm) {
              M = +M + 1;
              m = 0;
              p = 0;
            } else {
              m = +m + 1;
              p = 0;
            }
          } else if (gtlt === "<=") {
            gtlt = "<";
            if (xm) {
              M = +M + 1;
            } else {
              m = +m + 1;
            }
          }
          if (gtlt === "<") {
            pr = "-0";
          }
          ret = `${gtlt + M}.${m}.${p}${pr}`;
        } else if (xm) {
          ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
        } else if (xp) {
          ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
        }
        debug("xRange return", ret);
        return ret;
      });
    };
    var replaceStars = (comp, options) => {
      debug("replaceStars", comp, options);
      return comp.trim().replace(re[t.STAR], "");
    };
    var replaceGTE0 = (comp, options) => {
      debug("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, version, options) => {
      for (let i = 0; i < set.length; i++) {
        if (!set[i].test(version)) {
          return false;
        }
      }
      if (version.prerelease.length && !options.includePrerelease) {
        for (let i = 0; i < set.length; i++) {
          debug(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 === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
              return true;
            }
          }
        }
        return false;
      }
      return true;
    };
  }
});

// node_modules/semver/classes/comparator.js
var require_comparator = __commonJS({
  "node_modules/semver/classes/comparator.js"(exports2, module2) {
    "use strict";
    init_prefix();
    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(" ");
        debug("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;
        }
        debug("comp", this);
      }
      parse(comp) {
        const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
        const m = comp.match(r);
        if (!m) {
          throw new TypeError(`Invalid comparator: ${comp}`);
        }
        this.operator = m[1] !== void 0 ? m[1] : "";
        if (this.operator === "=") {
          this.operator = "";
        }
        if (!m[2]) {
          this.semver = ANY;
        } else {
          this.semver = new SemVer(m[2], this.options.loose);
        }
      }
      toString() {
        return this.value;
      }
      test(version) {
        debug("Comparator.test", version, this.options.loose);
        if (this.semver === ANY || version === ANY) {
          return true;
        }
        if (typeof version === "string") {
          try {
            version = new SemVer(version, this.options);
          } catch (er) {
            return false;
          }
        }
        return cmp(version, 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 debug = require_debug();
    var SemVer = require_semver();
    var Range = require_range();
  }
});

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

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

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

// node_modules/semver/ranges/min-version.js
var require_min_version = __commonJS({
  "node_modules/semver/ranges/min-version.js"(exports2, module2) {
    "use strict";
    init_prefix();
    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/semver/ranges/valid.js
var require_valid2 = __commonJS({
  "node_modules/semver/ranges/valid.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var Range = require_range();
    var validRange = (range, options) => {
      try {
        return new Range(range, options).range || "*";
      } catch (er) {
        return null;
      }
    };
    module2.exports = validRange;
  }
});

// node_modules/semver/ranges/outside.js
var require_outside = __commonJS({
  "node_modules/semver/ranges/outside.js"(exports2, module2) {
    "use strict";
    init_prefix();
    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 = (version, range, hilo, options) => {
      version = new SemVer(version, 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(version, 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(version, low.semver)) {
          return false;
        } else if (low.operator === ecomp && ltfn(version, low.semver)) {
          return false;
        }
      }
      return true;
    };
    module2.exports = outside;
  }
});

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

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

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

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

// node_modules/lru-cache/index.js
var require_lru_cache = __commonJS({
  "node_modules/lru-cache/index.js"(exports2, module2) {
    init_prefix();
    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 = (status, index) => {
          if (status) {
            status.ttl = this.ttls[index];
            status.start = this.starts[index];
            status.now = cachedNow || getNow();
            status.remainingTTL = status.now + status.ttl - status.start;
          }
        };
        let cachedNow = 0;
        const getNow = () => {
          const n = perf.now();
          if (this.ttlResolution > 0) {
            cachedNow = n;
            const t = setTimeout(
              () => cachedNow = 0,
              this.ttlResolution
            );
            if (t.unref) {
              t.unref();
            }
          }
          return n;
        };
        this.getRemainingTTL = (key) => {
          const index = this.keyMap.get(key);
          if (index === void 0) {
            return 0;
          }
          return this.ttls[index] === 0 || this.starts[index] === 0 ? Infinity : this.starts[index] + this.ttls[index] - (cachedNow || getNow());
        };
        this.isStale = (index) => {
          return this.ttls[index] !== 0 && this.starts[index] !== 0 && (cachedNow || getNow()) - this.starts[index] > this.ttls[index];
        };
      }
      updateItemAge(_index) {
      }
      statusTTL(_status, _index) {
      }
      setItemTTL(_index, _ttl, _start) {
      }
      isStale(_index) {
        return false;
      }
      initializeSizeTracking() {
        this.calculatedSize = 0;
        this.sizes = new ZeroArray(this.max);
        this.removeItemSize = (index) => {
          this.calculatedSize -= this.sizes[index];
          this.sizes[index] = 0;
        };
        this.requireSize = (k, v, size, sizeCalculation) => {
          if (this.isBackgroundFetch(v)) {
            return 0;
          }
          if (!isPosInt(size)) {
            if (sizeCalculation) {
              if (typeof sizeCalculation !== "function") {
                throw new TypeError("sizeCalculation must be a function");
              }
              size = sizeCalculation(v, k);
              if (!isPosInt(size)) {
                throw new TypeError(
                  "sizeCalculation return invalid (expect positive integer)"
                );
              }
            } else {
              throw new TypeError(
                "invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set."
              );
            }
          }
          return size;
        };
        this.addItemSize = (index, size, status) => {
          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 (status) {
            status.entrySize = size;
            status.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, getOptions) {
        for (const i of this.indexes()) {
          const v = this.valList[i];
          const value = this.isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0) continue;
          if (fn(value, this.keyList[i], this)) {
            return this.get(this.keyList[i], getOptions);
          }
        }
      }
      forEach(fn, thisp = this) {
        for (const i of this.indexes()) {
          const v = this.valList[i];
          const value = this.isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0) continue;
          fn.call(thisp, value, this.keyList[i], this);
        }
      }
      rforEach(fn, thisp = this) {
        for (const i of this.rindexes()) {
          const v = this.valList[i];
          const value = this.isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0) continue;
          fn.call(thisp, value, this.keyList[i], this);
        }
      }
      get prune() {
        deprecatedMethod("prune", "purgeStale");
        return this.purgeStale;
      }
      purgeStale() {
        let deleted = false;
        for (const i of this.rindexes({ allowStale: true })) {
          if (this.isStale(i)) {
            this.delete(this.keyList[i]);
            deleted = true;
          }
        }
        return deleted;
      }
      dump() {
        const arr = [];
        for (const i of this.indexes({ allowStale: true })) {
          const key = this.keyList[i];
          const v = this.valList[i];
          const value = this.isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0) continue;
          const entry = { value };
          if (this.ttls) {
            entry.ttl = this.ttls[i];
            const age = perf.now() - this.starts[i];
            entry.start = Math.floor(Date.now() - age);
          }
          if (this.sizes) {
            entry.size = this.sizes[i];
          }
          arr.unshift([key, entry]);
        }
        return arr;
      }
      load(arr) {
        this.clear();
        for (const [key, entry] of arr) {
          if (entry.start) {
            const age = Date.now() - entry.start;
            entry.start = perf.now() - age;
          }
          this.set(key, entry.value, entry);
        }
      }
      dispose(_v, _k, _reason) {
      }
      set(k, v, {
        ttl = this.ttl,
        start,
        noDisposeOnSet = this.noDisposeOnSet,
        size = 0,
        sizeCalculation = this.sizeCalculation,
        noUpdateTTL = this.noUpdateTTL,
        status
      } = {}) {
        size = this.requireSize(k, v, size, sizeCalculation);
        if (this.maxEntrySize && size > this.maxEntrySize) {
          if (status) {
            status.set = "miss";
            status.maxEntrySizeExceeded = true;
          }
          this.delete(k);
          return this;
        }
        let index = this.size === 0 ? void 0 : this.keyMap.get(k);
        if (index === void 0) {
          index = this.newIndex();
          this.keyList[index] = k;
          this.valList[index] = v;
          this.keyMap.set(k, index);
          this.next[this.tail] = index;
          this.prev[index] = this.tail;
          this.tail = index;
          this.size++;
          this.addItemSize(index, size, status);
          if (status) {
            status.set = "add";
          }
          noUpdateTTL = false;
        } else {
          this.moveToTail(index);
          const oldVal = this.valList[index];
          if (v !== oldVal) {
            if (this.isBackgroundFetch(oldVal)) {
              oldVal.__abortController.abort(new Error("replaced"));
            } else {
              if (!noDisposeOnSet) {
                this.dispose(oldVal, k, "set");
                if (this.disposeAfter) {
                  this.disposed.push([oldVal, k, "set"]);
                }
              }
            }
            this.removeItemSize(index);
            this.valList[index] = v;
            this.addItemSize(index, size, status);
            if (status) {
              status.set = "replace";
              const oldValue = oldVal && this.isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal;
              if (oldValue !== void 0) status.oldValue = oldValue;
            }
          } else if (status) {
            status.set = "update";
          }
        }
        if (ttl !== 0 && this.ttl === 0 && !this.ttls) {
          this.initializeTTLTracking();
        }
        if (!noUpdateTTL) {
          this.setItemTTL(index, ttl, start);
        }
        this.statusTTL(status, index);
        if (this.disposeAfter) {
          while (this.disposed.length) {
            this.disposeAfter(...this.disposed.shift());
          }
        }
        return this;
      }
      newIndex() {
        if (this.size === 0) {
          return this.tail;
        }
        if (this.size === this.max && this.max !== 0) {
          return this.evict(false);
        }
        if (this.free.length !== 0) {
          return this.free.pop();
        }
        return this.initialFill++;
      }
      pop() {
        if (this.size) {
          const val = this.valList[this.head];
          this.evict(true);
          return val;
        }
      }
      evict(free) {
        const head = this.head;
        const k = this.keyList[head];
        const v = this.valList[head];
        if (this.isBackgroundFetch(v)) {
          v.__abortController.abort(new Error("evicted"));
        } else {
          this.dispose(v, k, "evict");
          if (this.disposeAfter) {
            this.disposed.push([v, k, "evict"]);
          }
        }
        this.removeItemSize(head);
        if (free) {
          this.keyList[head] = null;
          this.valList[head] = null;
          this.free.push(head);
        }
        this.head = this.next[head];
        this.keyMap.delete(k);
        this.size--;
        return head;
      }
      has(k, { updateAgeOnHas = this.updateAgeOnHas, status } = {}) {
        const index = this.keyMap.get(k);
        if (index !== void 0) {
          if (!this.isStale(index)) {
            if (updateAgeOnHas) {
              this.updateItemAge(index);
            }
            if (status) status.has = "hit";
            this.statusTTL(status, index);
            return true;
          } else if (status) {
            status.has = "stale";
            this.statusTTL(status, index);
          }
        } else if (status) {
          status.has = "miss";
        }
        return false;
      }
      // like get(), but without any LRU updating or TTL expiration
      peek(k, { allowStale = this.allowStale } = {}) {
        const index = this.keyMap.get(k);
        if (index !== void 0 && (allowStale || !this.isStale(index))) {
          const v = this.valList[index];
          return this.isBackgroundFetch(v) ? v.__staleWhileFetching : v;
        }
      }
      backgroundFetch(k, index, options, context) {
        const v = index === void 0 ? void 0 : this.valList[index];
        if (this.isBackgroundFetch(v)) {
          return v;
        }
        const ac = new AC();
        if (options.signal) {
          options.signal.addEventListener(
            "abort",
            () => ac.abort(options.signal.reason)
          );
        }
        const fetchOpts = {
          signal: ac.signal,
          options,
          context
        };
        const cb = (v2, updateCache = false) => {
          const { aborted } = ac.signal;
          const ignoreAbort = options.ignoreFetchAbort && v2 !== 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 (v2 === 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, v2, fetchOpts.options);
            }
          }
          return v2;
        };
        const eb = (er) => {
          if (options.status) {
            options.status.fetchRejected = true;
            options.status.fetchError = er;
          }
          return fetchFail(er);
        };
        const fetchFail = (er) => {
          const { aborted } = 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, v, fetchOpts).then((v2) => res(v2), rej);
          ac.signal.addEventListener("abort", () => {
            if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {
              res();
              if (options.allowStaleOnFetchAbort) {
                res = (v2) => cb(v2, true);
              }
            }
          });
        };
        if (options.status) options.status.fetchDispatched = true;
        const p = new Promise(pcall).then(cb, eb);
        p.__abortController = ac;
        p.__staleWhileFetching = v;
        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,
        signal
      } = {}) {
        if (!this.fetchMethod) {
          if (status) status.fetch = "get";
          return this.get(k, {
            allowStale,
            updateAgeOnGet,
            noDeleteOnStaleGet,
            status
          });
        }
        const options = {
          allowStale,
          updateAgeOnGet,
          noDeleteOnStaleGet,
          ttl,
          noDisposeOnSet,
          size,
          sizeCalculation,
          noUpdateTTL,
          noDeleteOnFetchRejection,
          allowStaleOnFetchRejection,
          allowStaleOnFetchAbort,
          ignoreFetchAbort,
          status,
          signal
        };
        let index = this.keyMap.get(k);
        if (index === void 0) {
          if (status) status.fetch = "miss";
          const p = this.backgroundFetch(k, index, options, fetchContext);
          return p.__returned = p;
        } else {
          const v = this.valList[index];
          if (this.isBackgroundFetch(v)) {
            const stale = allowStale && v.__staleWhileFetching !== void 0;
            if (status) {
              status.fetch = "inflight";
              if (stale) status.returnedStale = true;
            }
            return stale ? v.__staleWhileFetching : v.__returned = v;
          }
          const isStale = this.isStale(index);
          if (!forceRefresh && !isStale) {
            if (status) status.fetch = "hit";
            this.moveToTail(index);
            if (updateAgeOnGet) {
              this.updateItemAge(index);
            }
            this.statusTTL(status, index);
            return v;
          }
          const p = this.backgroundFetch(k, index, options, fetchContext);
          const hasStale = p.__staleWhileFetching !== void 0;
          const staleVal = hasStale && allowStale;
          if (status) {
            status.fetch = hasStale && isStale ? "stale" : "refresh";
            if (staleVal && isStale) status.returnedStale = true;
          }
          return staleVal ? p.__staleWhileFetching : p.__returned = p;
        }
      }
      get(k, {
        allowStale = this.allowStale,
        updateAgeOnGet = this.updateAgeOnGet,
        noDeleteOnStaleGet = this.noDeleteOnStaleGet,
        status
      } = {}) {
        const index = this.keyMap.get(k);
        if (index !== void 0) {
          const value = this.valList[index];
          const fetching = this.isBackgroundFetch(value);
          this.statusTTL(status, index);
          if (this.isStale(index)) {
            if (status) status.get = "stale";
            if (!fetching) {
              if (!noDeleteOnStaleGet) {
                this.delete(k);
              }
              if (status) status.returnedStale = allowStale;
              return allowStale ? value : void 0;
            } else {
              if (status) {
                status.returnedStale = allowStale && value.__staleWhileFetching !== void 0;
              }
              return allowStale ? value.__staleWhileFetching : void 0;
            }
          } else {
            if (status) status.get = "hit";
            if (fetching) {
              return value.__staleWhileFetching;
            }
            this.moveToTail(index);
            if (updateAgeOnGet) {
              this.updateItemAge(index);
            }
            return value;
          }
        } else if (status) {
          status.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 v = this.valList[index];
              if (this.isBackgroundFetch(v)) {
                v.__abortController.abort(new Error("deleted"));
              } else {
                this.dispose(v, k, "delete");
                if (this.disposeAfter) {
                  this.disposed.push([v, k, "delete"]);
                }
              }
              this.keyMap.delete(k);
              this.keyList[index] = null;
              this.valList[index] = null;
              if (index === this.tail) {
                this.tail = this.prev[index];
              } else if (index === this.head) {
                this.head = this.next[index];
              } else {
                this.next[this.prev[index]] = this.next[index];
                this.prev[this.next[index]] = this.prev[index];
              }
              this.size--;
              this.free.push(index);
            }
          }
        }
        if (this.disposed) {
          while (this.disposed.length) {
            this.disposeAfter(...this.disposed.shift());
          }
        }
        return deleted;
      }
      clear() {
        for (const index of this.rindexes({ allowStale: true })) {
          const v = this.valList[index];
          if (this.isBackgroundFetch(v)) {
            v.__abortController.abort(new Error("deleted"));
          } else {
            const k = this.keyList[index];
            this.dispose(v, k, "delete");
            if (this.disposeAfter) {
              this.disposed.push([v, k, "delete"]);
            }
          }
        }
        this.keyMap.clear();
        this.valList.fill(null);
        this.keyList.fill(null);
        if (this.ttls) {
          this.ttls.fill(0);
          this.starts.fill(0);
        }
        if (this.sizes) {
          this.sizes.fill(0);
        }
        this.head = 0;
        this.tail = 0;
        this.initialFill = 1;
        this.free.length = 0;
        this.calculatedSize = 0;
        this.size = 0;
        if (this.disposed) {
          while (this.disposed.length) {
            this.disposeAfter(...this.disposed.shift());
          }
        }
      }
      get reset() {
        deprecatedMethod("reset", "clear");
        return this.clear;
      }
      get length() {
        deprecatedProperty("length", "size");
        return this.size;
      }
      static get AbortController() {
        return AC;
      }
      static get AbortSignal() {
        return AS;
      }
    };
    module2.exports = LRUCache;
  }
});

// node_modules/agent-base/dist/helpers.js
var require_helpers = __commonJS({
  "node_modules/agent-base/dist/helpers.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.req = exports2.json = exports2.toBuffer = void 0;
    var http = __importStar2(require("http"));
    var https = __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(url, opts = {}) {
      const href = typeof url === "string" ? url : url.href;
      const req2 = (href.startsWith("https:") ? https : http).request(url, opts);
      const promise = new Promise((resolve5, reject) => {
        req2.once("response", resolve5).once("error", reject).end();
      });
      req2.then = promise.then.bind(promise);
      return req2;
    }
    exports2.req = req;
  }
});

// node_modules/agent-base/dist/index.js
var require_dist = __commonJS({
  "node_modules/agent-base/dist/index.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Agent = void 0;
    var net = __importStar2(require("net"));
    var http = __importStar2(require("http"));
    var https_1 = require("https");
    __exportStar2(require_helpers(), exports2);
    var INTERNAL = /* @__PURE__ */ Symbol("AgentBaseInternalState");
    var Agent = class extends http.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 net.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 = 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 http.Agent) {
            try {
              return socket.addRequest(req, connectOpts);
            } catch (err) {
              return cb(err);
            }
          }
          this[INTERNAL].currentSocket = socket;
          super.createSocket(req, options, cb);
        }, (err) => {
          this.decrementSockets(name, fakeSocket);
          cb(err);
        });
      }
      createConnection() {
        const socket = this[INTERNAL].currentSocket;
        this[INTERNAL].currentSocket = void 0;
        if (!socket) {
          throw new Error("No socket was returned in the `connect()` function");
        }
        return socket;
      }
      get defaultPort() {
        return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80);
      }
      set defaultPort(v) {
        if (this[INTERNAL]) {
          this[INTERNAL].defaultPort = v;
        }
      }
      get protocol() {
        return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:");
      }
      set protocol(v) {
        if (this[INTERNAL]) {
          this[INTERNAL].protocol = v;
        }
      }
    };
    exports2.Agent = Agent;
  }
});

// node_modules/proxy-agent/node_modules/proxy-from-env/index.js
var require_proxy_from_env = __commonJS({
  "node_modules/proxy-agent/node_modules/proxy-from-env/index.js"(exports2) {
    "use strict";
    init_prefix();
    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(url) {
      var parsedUrl = typeof url === "string" ? parseUrl(url) : url || {};
      var proto = parsedUrl.protocol;
      var hostname = parsedUrl.host;
      var port = parsedUrl.port;
      if (typeof hostname !== "string" || !hostname || typeof proto !== "string") {
        return "";
      }
      proto = proto.split(":", 1)[0];
      hostname = hostname.replace(/:\d*$/, "");
      port = parseInt(port) || DEFAULT_PORTS[proto] || 0;
      if (!shouldProxy(hostname, port)) {
        return "";
      }
      var proxy = getEnv("npm_config_" + proto + "_proxy") || getEnv(proto + "_proxy") || getEnv("npm_config_proxy") || getEnv("all_proxy");
      if (proxy && proxy.indexOf("://") === -1) {
        proxy = proto + "://" + 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/http-proxy-agent/dist/index.js
var require_dist2 = __commonJS({
  "node_modules/http-proxy-agent/dist/index.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.HttpProxyAgent = void 0;
    var net = __importStar2(require("net"));
    var tls = __importStar2(require("tls"));
    var debug_1 = __importDefault2(require_src());
    var events_1 = require("events");
    var agent_base_1 = require_dist();
    var url_1 = require("url");
    var debug = (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 ?? {};
        debug("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 base = `${protocol}//${hostname}`;
        const url = new url_1.URL(req.path, base);
        if (opts.port !== 80) {
          url.port = String(opts.port);
        }
        req.path = String(url);
        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;
        debug("Regenerating stored HTTP header string for request");
        req._implicitHeader();
        if (req.outputData && req.outputData.length > 0) {
          debug("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);
          debug("Output buffer: %o", req.outputData[0].data);
        }
        let socket;
        if (this.proxy.protocol === "https:") {
          debug("Creating `tls.Socket`: %o", this.connectOpts);
          socket = tls.connect(this.connectOpts);
        } else {
          debug("Creating `net.Socket`: %o", this.connectOpts);
          socket = net.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/https-proxy-agent/dist/parse-proxy-response.js
var require_parse_proxy_response = __commonJS({
  "node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) {
    "use strict";
    init_prefix();
    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_src());
    var debug = (0, debug_1.default)("https-proxy-agent:parse-proxy-response");
    function parseProxyResponse(socket) {
      return new Promise((resolve5, 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();
          debug("onend");
          reject(new Error("Proxy connection ended before receiving CONNECT response"));
        }
        function onerror(err) {
          cleanup();
          debug("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) {
            debug("have not received end of HTTP headers yet...");
            read();
            return;
          }
          const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split("\r\n");
          const firstLine = headerParts.shift();
          if (!firstLine) {
            socket.destroy();
            return reject(new Error("No header received from proxy CONNECT response"));
          }
          const firstLineParts = firstLine.split(" ");
          const statusCode = +firstLineParts[1];
          const statusText = firstLineParts.slice(2).join(" ");
          const headers = {};
          for (const header of headerParts) {
            if (!header)
              continue;
            const firstColon = header.indexOf(":");
            if (firstColon === -1) {
              socket.destroy();
              return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`));
            }
            const key = header.slice(0, firstColon).toLowerCase();
            const value = header.slice(firstColon + 1).trimStart();
            const current = headers[key];
            if (typeof current === "string") {
              headers[key] = [current, value];
            } else if (Array.isArray(current)) {
              current.push(value);
            } else {
              headers[key] = value;
            }
          }
          debug("got proxy server response: %o %o", firstLine, headers);
          cleanup();
          resolve5({
            connect: {
              statusCode,
              statusText,
              headers
            },
            buffered
          });
        }
        socket.on("error", onerror);
        socket.on("end", onend);
        read();
      });
    }
    exports2.parseProxyResponse = parseProxyResponse;
  }
});

// node_modules/https-proxy-agent/dist/index.js
var require_dist3 = __commonJS({
  "node_modules/https-proxy-agent/dist/index.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.HttpsProxyAgent = void 0;
    var net = __importStar2(require("net"));
    var tls = __importStar2(require("tls"));
    var assert_1 = __importDefault2(require("assert"));
    var debug_1 = __importDefault2(require_src());
    var agent_base_1 = require_dist();
    var url_1 = require("url");
    var parse_proxy_response_1 = require_parse_proxy_response();
    var debug = (0, debug_1.default)("https-proxy-agent");
    var setServernameFromNonIpHost = (options) => {
      if (options.servername === void 0 && options.host && !net.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 ?? {};
        debug("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:") {
          debug("Creating `tls.Socket`: %o", this.connectOpts);
          socket = tls.connect(setServernameFromNonIpHost(this.connectOpts));
        } else {
          debug("Creating `net.Socket`: %o", this.connectOpts);
          socket = net.connect(this.connectOpts);
        }
        const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders };
        const host = net.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) {
            debug("Upgrading socket connection to TLS");
            return tls.connect({
              ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"),
              socket
            });
          }
          return socket;
        }
        socket.destroy();
        const fakeSocket = new net.Socket({ writable: false });
        fakeSocket.readable = true;
        req.once("socket", (s) => {
          debug("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/smart-buffer/build/utils.js
var require_utils2 = __commonJS({
  "node_modules/smart-buffer/build/utils.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var buffer_1 = require("buffer");
    var ERRORS = {
      INVALID_ENCODING: "Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.",
      INVALID_SMARTBUFFER_SIZE: "Invalid size provided. Size must be a valid integer greater than zero.",
      INVALID_SMARTBUFFER_BUFFER: "Invalid Buffer provided in SmartBufferOptions.",
      INVALID_SMARTBUFFER_OBJECT: "Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.",
      INVALID_OFFSET: "An invalid offset value was provided.",
      INVALID_OFFSET_NON_NUMBER: "An invalid offset value was provided. A numeric value is required.",
      INVALID_LENGTH: "An invalid length value was provided.",
      INVALID_LENGTH_NON_NUMBER: "An invalid length value was provived. A numeric value is required.",
      INVALID_TARGET_OFFSET: "Target offset is beyond the bounds of the internal SmartBuffer data.",
      INVALID_TARGET_LENGTH: "Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.",
      INVALID_READ_BEYOND_BOUNDS: "Attempted to read beyond the bounds of the managed data.",
      INVALID_WRITE_BEYOND_BOUNDS: "Attempted to write beyond the bounds of the managed data."
    };
    exports2.ERRORS = ERRORS;
    function checkEncoding(encoding) {
      if (!buffer_1.Buffer.isEncoding(encoding)) {
        throw new Error(ERRORS.INVALID_ENCODING);
      }
    }
    exports2.checkEncoding = checkEncoding;
    function isFiniteInteger(value) {
      return typeof value === "number" && isFinite(value) && isInteger(value);
    }
    exports2.isFiniteInteger = isFiniteInteger;
    function checkOffsetOrLengthValue(value, offset) {
      if (typeof value === "number") {
        if (!isFiniteInteger(value) || value < 0) {
          throw new Error(offset ? ERRORS.INVALID_OFFSET : ERRORS.INVALID_LENGTH);
        }
      } else {
        throw new Error(offset ? ERRORS.INVALID_OFFSET_NON_NUMBER : ERRORS.INVALID_LENGTH_NON_NUMBER);
      }
    }
    function checkLengthValue(length) {
      checkOffsetOrLengthValue(length, false);
    }
    exports2.checkLengthValue = checkLengthValue;
    function checkOffsetValue(offset) {
      checkOffsetOrLengthValue(offset, true);
    }
    exports2.checkOffsetValue = checkOffsetValue;
    function checkTargetOffset(offset, buff) {
      if (offset < 0 || offset > buff.length) {
        throw new Error(ERRORS.INVALID_TARGET_OFFSET);
      }
    }
    exports2.checkTargetOffset = checkTargetOffset;
    function isInteger(value) {
      return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
    }
    function bigIntAndBufferInt64Check(bufferMethod) {
      if (typeof BigInt === "undefined") {
        throw new Error("Platform does not support JS BigInt type.");
      }
      if (typeof buffer_1.Buffer.prototype[bufferMethod] === "undefined") {
        throw new Error(`Platform does not support Buffer.prototype.${bufferMethod}.`);
      }
    }
    exports2.bigIntAndBufferInt64Check = bigIntAndBufferInt64Check;
  }
});

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

// node_modules/socks/build/common/constants.js
var require_constants3 = __commonJS({
  "node_modules/socks/build/common/constants.js"(exports2) {
    "use strict";
    init_prefix();
    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/socks/build/common/util.js
var require_util3 = __commonJS({
  "node_modules/socks/build/common/util.js"(exports2) {
    "use strict";
    init_prefix();
    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/ip-address/dist/common.js
var require_common2 = __commonJS({
  "node_modules/ip-address/dist/common.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isInSubnet = isInSubnet;
    exports2.isCorrect = isCorrect;
    exports2.numberToPaddedHex = numberToPaddedHex;
    exports2.stringToPaddedHex = stringToPaddedHex;
    exports2.testBit = testBit;
    function isInSubnet(address) {
      if (this.subnetMask < address.subnetMask) {
        return false;
      }
      if (this.mask(address.subnetMask) === address.mask()) {
        return true;
      }
      return false;
    }
    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);
      };
    }
    function numberToPaddedHex(number) {
      return number.toString(16).padStart(2, "0");
    }
    function stringToPaddedHex(numberString) {
      return numberToPaddedHex(parseInt(numberString, 10));
    }
    function testBit(binaryValue, position) {
      const { length } = binaryValue;
      if (position > length) {
        return false;
      }
      const positionInString = length - position;
      return binaryValue.substring(positionInString, positionInString + 1) === "1";
    }
  }
});

// node_modules/ip-address/dist/v4/constants.js
var require_constants4 = __commonJS({
  "node_modules/ip-address/dist/v4/constants.js"(exports2) {
    "use strict";
    init_prefix();
    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/ip-address/dist/address-error.js
var require_address_error = __commonJS({
  "node_modules/ip-address/dist/address-error.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AddressError = void 0;
    var AddressError = class extends Error {
      constructor(message, parseMessage) {
        super(message);
        this.name = "AddressError";
        this.parseMessage = parseMessage;
      }
    };
    exports2.AddressError = AddressError;
  }
});

// node_modules/ip-address/dist/ipv4.js
var require_ipv4 = __commonJS({
  "node_modules/ip-address/dist/ipv4.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Address4 = void 0;
    var common = __importStar2(require_common2());
    var constants = __importStar2(require_constants4());
    var address_error_1 = require_address_error();
    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 h = padded.slice(i, i + 2);
          groups.push(parseInt(h, 16));
        }
        return new _Address4(groups.join("."));
      }
      /**
       * Converts an integer into a IPv4 address object
       * @memberof Address4
       * @static
       * @param {integer} integer - a number to convert
       * @returns {Address4}
       */
      static fromInteger(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) => common.stringToPaddedHex(part)).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) {
          output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`);
        }
        return output.join(":");
      }
      /**
       * Returns the address as a `bigint`
       * @memberof Address4
       * @instance
       * @returns {bigint}
       */
      bigInt() {
        return BigInt(`0x${this.parsedAddress.map((n) => common.stringToPaddedHex(n)).join("")}`);
      }
      /**
       * Helper function getting start address.
       * @memberof Address4
       * @instance
       * @returns {bigint}
       */
      _startAddress() {
        return BigInt(`0b${this.mask() + "0".repeat(constants.BITS - this.subnetMask)}`);
      }
      /**
       * 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.fromBigInt(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 = BigInt("1");
        return _Address4.fromBigInt(this._startAddress() + adjust);
      }
      /**
       * Helper function getting end address.
       * @memberof Address4
       * @instance
       * @returns {bigint}
       */
      _endAddress() {
        return BigInt(`0b${this.mask() + "1".repeat(constants.BITS - this.subnetMask)}`);
      }
      /**
       * 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.fromBigInt(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 = BigInt("1");
        return _Address4.fromBigInt(this._endAddress() - adjust);
      }
      /**
       * Converts a BigInt to a v4 address object
       * @memberof Address4
       * @static
       * @param {bigint} bigInt - a BigInt to convert
       * @returns {Address4}
       */
      static fromBigInt(bigInt) {
        return _Address4.fromHex(bigInt.toString(16));
      }
      /**
       * Convert a byte array to an Address4 object
       * @memberof Address4
       * @static
       * @param {Array<number>} bytes - an array of 4 bytes (0-255)
       * @returns {Address4}
       */
      static fromByteArray(bytes) {
        if (bytes.length !== 4) {
          throw new address_error_1.AddressError("IPv4 addresses require exactly 4 bytes");
        }
        for (let i = 0; i < bytes.length; i++) {
          if (!Number.isInteger(bytes[i]) || bytes[i] < 0 || bytes[i] > 255) {
            throw new address_error_1.AddressError("All bytes must be integers between 0 and 255");
          }
        }
        return this.fromUnsignedByteArray(bytes);
      }
      /**
       * Convert an unsigned byte array to an Address4 object
       * @memberof Address4
       * @static
       * @param {Array<number>} bytes - an array of 4 unsigned bytes (0-255)
       * @returns {Address4}
       */
      static fromUnsignedByteArray(bytes) {
        if (bytes.length !== 4) {
          throw new address_error_1.AddressError("IPv4 addresses require exactly 4 bytes");
        }
        const address = bytes.join(".");
        return new _Address4(address);
      }
      /**
       * 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 `${reversed}.in-addr.arpa.`;
      }
      /**
       * 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.bigInt().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, `<span class="hover-group group-v4 group-6">${segments.slice(0, 2).join(".")}</span>.<span class="hover-group group-v4 group-7">${segments.slice(2, 4).join(".")}</span>`);
      }
    };
    exports2.Address4 = Address4;
  }
});

// node_modules/ip-address/dist/v6/constants.js
var require_constants5 = __commonJS({
  "node_modules/ip-address/dist/v6/constants.js"(exports2) {
    "use strict";
    init_prefix();
    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 = /^\[{0,1}([0-9a-f:]+)\]{0,1}/;
    exports2.RE_URL_WITH_PORT = /\[([0-9a-f:]+)\]:([0-9]{1,5})/;
  }
});

// node_modules/ip-address/dist/v6/helpers.js
var require_helpers2 = __commonJS({
  "node_modules/ip-address/dist/v6/helpers.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.spanAllZeroes = spanAllZeroes;
    exports2.spanAll = spanAll;
    exports2.spanLeadingZeroes = spanLeadingZeroes;
    exports2.simpleGroup = simpleGroup;
    function spanAllZeroes(s) {
      return s.replace(/(0+)/g, '<span class="zero">$1</span>');
    }
    function spanAll(s, offset = 0) {
      const letters = s.split("");
      return letters.map((n, i) => `<span class="digit value-${n} position-${i + offset}">${spanAllZeroes(n)}</span>`).join("");
    }
    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(":");
    }
    function simpleGroup(addressString, offset = 0) {
      const groups = addressString.split(":");
      return groups.map((g, i) => {
        if (/group-v4/.test(g)) {
          return g;
        }
        return `<span class="hover-group group-${i + offset}">${spanLeadingZeroesSimple(g)}</span>`;
      });
    }
  }
});

// node_modules/ip-address/dist/v6/regular-expressions.js
var require_regular_expressions = __commonJS({
  "node_modules/ip-address/dist/v6/regular-expressions.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ADDRESS_BOUNDARY = void 0;
    exports2.groupPossibilities = groupPossibilities;
    exports2.padGroup = padGroup;
    exports2.simpleRegularExpression = simpleRegularExpression;
    exports2.possibleElisions = possibleElisions;
    var v6 = __importStar2(require_constants5());
    function groupPossibilities(possibilities) {
      return `(${possibilities.join("|")})`;
    }
    function padGroup(group) {
      if (group.length < 4) {
        return `0{0,${4 - group.length}}${group}`;
      }
      return group;
    }
    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);
    }
    function possibleElisions(elidedGroups, moreLeft, moreRight) {
      const left2 = moreLeft ? "" : ":";
      const right2 = moreRight ? "" : ":";
      const possibilities = [];
      if (!moreLeft && !moreRight) {
        possibilities.push("::");
      }
      if (moreLeft && moreRight) {
        possibilities.push("");
      }
      if (moreRight && !moreLeft || !moreRight && moreLeft) {
        possibilities.push(":");
      }
      possibilities.push(`${left2}(:0{1,4}){1,${elidedGroups - 1}}`);
      possibilities.push(`(0{1,4}:){1,${elidedGroups - 1}}${right2}`);
      possibilities.push(`(0{1,4}:){${elidedGroups - 1}}0{1,4}`);
      for (let groups = 1; groups < elidedGroups - 1; groups++) {
        for (let position = 1; position < elidedGroups - groups; position++) {
          possibilities.push(`(0{1,4}:){${position}}:(0{1,4}:){${elidedGroups - position - groups - 1}}0{1,4}`);
        }
      }
      return groupPossibilities(possibilities);
    }
  }
});

// node_modules/ip-address/dist/ipv6.js
var require_ipv6 = __commonJS({
  "node_modules/ip-address/dist/ipv6.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Address6 = void 0;
    var common = __importStar2(require_common2());
    var constants4 = __importStar2(require_constants4());
    var constants6 = __importStar2(require_constants5());
    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 common_1 = require_common2();
    function assert(condition) {
      if (!condition) {
        throw new Error("Assertion failed.");
      }
    }
    function addCommas(number) {
      const r = /(\d+)(\d{3})/;
      while (r.test(number)) {
        number = number.replace(r, "$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 parseInt(octet, 16).toString(16).padStart(4, "0");
    }
    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 BigInt to a v6 address object
       * @memberof Address6
       * @static
       * @param {bigint} bigInt - a BigInt to convert
       * @returns {Address6}
       * @example
       * var bigInt = BigInt('1000000000000');
       * var address = Address6.fromBigInt(bigInt);
       * address.correctForm(); // '::e8:d4a5:1000'
       */
      static fromBigInt(bigInt) {
        const hex = bigInt.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(url) {
        let host;
        let port = null;
        let result;
        if (url.indexOf("[") !== -1 && url.indexOf("]:") !== -1) {
          result = constants6.RE_URL_WITH_PORT.exec(url);
          if (result === null) {
            return {
              error: "failed to parse address with port",
              address: null,
              port: null
            };
          }
          host = result[1];
          port = result[2];
        } else if (url.indexOf("/") !== -1) {
          url = url.replace(/^[a-z0-9]+:\/\//, "");
          result = constants6.RE_URL.exec(url);
          if (result === null) {
            return {
              error: "failed to parse address from URL",
              address: null,
              port: null
            };
          }
          host = result[1];
        } else {
          host = url;
        }
        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 `${this.correctForm().replace(/:/g, "-")}.ipv6-literal.net`;
      }
      /**
       * 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} [subnetSize=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((BigInt("2") ** BigInt(subnetPowers)).toString(10));
      }
      /**
       * Helper function getting start address.
       * @memberof Address6
       * @instance
       * @returns {bigint}
       */
      _startAddress() {
        return BigInt(`0b${this.mask() + "0".repeat(constants6.BITS - this.subnetMask)}`);
      }
      /**
       * 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.fromBigInt(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 = BigInt("1");
        return _Address6.fromBigInt(this._startAddress() + adjust);
      }
      /**
       * Helper function getting end address.
       * @memberof Address6
       * @instance
       * @returns {bigint}
       */
      _endAddress() {
        return BigInt(`0b${this.mask() + "1".repeat(constants6.BITS - this.subnetMask)}`);
      }
      /**
       * 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.fromBigInt(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 = BigInt("1");
        return _Address6.fromBigInt(this._endAddress() - adjust);
      }
      /**
       * Return the scope of the address
       * @memberof Address6
       * @instance
       * @returns {String}
       */
      getScope() {
        let scope = constants6.SCOPES[parseInt(this.getBits(12, 16).toString(10), 10)];
        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 BigInt
       * @memberof Address6
       * @instance
       * @returns {bigint}
       */
      getBits(start, end) {
        return BigInt(`0b${this.getBitsBase2(start, end)}`);
      }
      /**
       * 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 `${reversed}.ip6.arpa.`;
        }
        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.bigInt().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(`Bad character${badCharacters.length > 1 ? "s" : ""} detected in address: ${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(`Address failed regex: ${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) => parseInt(group, 16).toString(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) => parseInt(n, 16).toString(10).padStart(5, "0")).join(":");
      }
      /**
       * Return the address as a BigInt
       * @memberof Address6
       * @instance
       * @returns {bigint}
       */
      bigInt() {
        return BigInt(`0x${this.parsedAddress.map(paddedHex).join("")}`);
      }
      /**
       * 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(BigInt(`0b${binary.slice(96, 128).join("")}`).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 bitsForUdpPort = this.getBits(80, 96);
        const udpPort = (bitsForUdpPort ^ BigInt("0xffff")).toString();
        const server4 = ipv4_1.Address4.fromHex(this.getBitsBase16(32, 64));
        const bitsForClient4 = this.getBits(96, 128);
        const client4 = ipv4_1.Address4.fromHex((bitsForClient4 ^ BigInt("0xffffffff")).toString(16));
        const flagsBase2 = this.getBitsBase2(64, 80);
        const coneNat = (0, common_1.testBit)(flagsBase2, 15);
        const reserved = (0, common_1.testBit)(flagsBase2, 14);
        const groupIndividual = (0, common_1.testBit)(flagsBase2, 8);
        const universalLocal = (0, common_1.testBit)(flagsBase2, 9);
        const nonce = BigInt(`0b${flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16)}`).toString(10);
        return {
          prefix: `${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: 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 valueWithoutPadding = this.bigInt().toString(16);
        const leadingPad = "0".repeat(valueWithoutPadding.length % 2);
        const value = `${leadingPad}${valueWithoutPadding}`;
        const bytes = [];
        for (let i = 0, length = value.length; i < length; i += 2) {
          bytes.push(parseInt(value.substring(i, i + 2), 16));
        }
        return bytes;
      }
      /**
       * 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 = BigInt("256");
        let result = BigInt("0");
        let multiplier = BigInt("1");
        for (let i = bytes.length - 1; i >= 0; i--) {
          result += multiplier * BigInt(bytes[i].toString(10));
          multiplier *= BYTE_MAX;
        }
        return _Address6.fromBigInt(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 = `:${optionalPort}`;
        }
        return `http://[${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;
        }
        const form = formFunction.call(this);
        if (options.className) {
          return `<a href="${options.prefix}${form}" class="${options.className}">${form}</a>`;
        }
        return `<a href="${options.prefix}${form}">${form}</a>`;
      }
      /**
       * Groups an address
       * @returns {String}
       */
      group() {
        if (this.elidedGroups === 0) {
          return helpers.simpleGroup(this.address).join(":");
        }
        assert(typeof this.elidedGroups === "number");
        assert(typeof this.elisionBegin === "number");
        const output = [];
        const [left2, right2] = this.address.split("::");
        if (left2.length) {
          output.push(...helpers.simpleGroup(left2));
        } else {
          output.push("");
        }
        const classes = ["hover-group"];
        for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) {
          classes.push(`group-${i}`);
        }
        output.push(`<span class="${classes.join(" ")}"></span>`);
        if (right2.length) {
          output.push(...helpers.simpleGroup(right2, this.elisionEnd));
        } else {
          output.push("");
        }
        if (this.is4()) {
          assert(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(":")));
          }
          assert(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/ip-address/dist/ip-address.js
var require_ip_address = __commonJS({
  "node_modules/ip-address/dist/ip-address.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.v6 = exports2.AddressError = exports2.Address6 = exports2.Address4 = void 0;
    var ipv4_1 = require_ipv4();
    Object.defineProperty(exports2, "Address4", { enumerable: true, get: function() {
      return ipv4_1.Address4;
    } });
    var ipv6_1 = require_ipv6();
    Object.defineProperty(exports2, "Address6", { enumerable: true, get: function() {
      return ipv6_1.Address6;
    } });
    var address_error_1 = require_address_error();
    Object.defineProperty(exports2, "AddressError", { enumerable: true, get: function() {
      return address_error_1.AddressError;
    } });
    var helpers = __importStar2(require_helpers2());
    exports2.v6 = { helpers };
  }
});

// node_modules/socks/build/common/helpers.js
var require_helpers3 = __commonJS({
  "node_modules/socks/build/common/helpers.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ipToBuffer = exports2.int32ToIpv4 = exports2.ipv4ToInt32 = exports2.validateSocksClientChainOptions = exports2.validateSocksClientOptions = void 0;
    var util_1 = require_util3();
    var constants_1 = require_constants3();
    var stream = require("stream");
    var ip_address_1 = require_ip_address();
    var net = 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" && Buffer.byteLength(remoteHost.host) < 256 && 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 (net.isIPv4(ip)) {
        const address = new ip_address_1.Address4(ip);
        return Buffer.from(address.toArray());
      } else if (net.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/socks/build/common/receivebuffer.js
var require_receivebuffer = __commonJS({
  "node_modules/socks/build/common/receivebuffer.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ReceiveBuffer = void 0;
    var ReceiveBuffer = class {
      constructor(size = 4096) {
        this.buffer = Buffer.allocUnsafe(size);
        this.offset = 0;
        this.originalSize = size;
      }
      get length() {
        return this.offset;
      }
      append(data) {
        if (!Buffer.isBuffer(data)) {
          throw new Error("Attempted to append a non-buffer instance to ReceiveBuffer.");
        }
        if (this.offset + data.length >= this.buffer.length) {
          const tmp = this.buffer;
          this.buffer = Buffer.allocUnsafe(Math.max(this.buffer.length + this.originalSize, this.buffer.length + data.length));
          tmp.copy(this.buffer);
        }
        data.copy(this.buffer, this.offset);
        return this.offset += data.length;
      }
      peek(length) {
        if (length > this.offset) {
          throw new Error("Attempted to read beyond the bounds of the managed internal data.");
        }
        return this.buffer.slice(0, length);
      }
      get(length) {
        if (length > this.offset) {
          throw new Error("Attempted to read beyond the bounds of the managed internal data.");
        }
        const value = Buffer.allocUnsafe(length);
        this.buffer.slice(0, length).copy(value);
        this.buffer.copyWithin(0, length, length + this.offset - length);
        this.offset -= length;
        return value;
      }
    };
    exports2.ReceiveBuffer = ReceiveBuffer;
  }
});

// node_modules/socks/build/client/socksclient.js
var require_socksclient = __commonJS({
  "node_modules/socks/build/client/socksclient.js"(exports2) {
    "use strict";
    init_prefix();
    var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve5) {
          resolve5(value);
        });
      }
      return new (P || (P = Promise))(function(resolve5, 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 ? resolve5(result.value) : adopt(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 net = require("net");
    var smart_buffer_1 = require_smartbuffer();
    var constants_1 = require_constants3();
    var helpers_1 = require_helpers3();
    var receivebuffer_1 = require_receivebuffer();
    var util_1 = require_util3();
    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((resolve5, reject) => {
          try {
            (0, helpers_1.validateSocksClientOptions)(options, ["connect"]);
          } catch (err) {
            if (typeof callback === "function") {
              callback(err);
              return resolve5(err);
            } else {
              return reject(err);
            }
          }
          const client2 = new _SocksClient(options);
          client2.connect(options.existing_socket);
          client2.once("established", (info) => {
            client2.removeAllListeners();
            if (typeof callback === "function") {
              callback(null, info);
              resolve5(info);
            } else {
              resolve5(info);
            }
          });
          client2.once("error", (err) => {
            client2.removeAllListeners();
            if (typeof callback === "function") {
              callback(err);
              resolve5(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((resolve5, reject) => __awaiter2(this, void 0, void 0, function* () {
          try {
            (0, helpers_1.validateSocksClientChainOptions)(options);
          } catch (err) {
            if (typeof callback === "function") {
              callback(err);
              return resolve5(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 });
              resolve5({ socket: sock });
            } else {
              resolve5({ socket: sock });
            }
          } catch (err) {
            if (typeof callback === "function") {
              callback(err);
              resolve5(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 (net.isIPv4(options.remoteHost.host)) {
          buff.writeUInt8(constants_1.Socks5HostType.IPv4);
          buff.writeUInt32BE((0, helpers_1.ipv4ToInt32)(options.remoteHost.host));
        } else if (net.isIPv6(options.remoteHost.host)) {
          buff.writeUInt8(constants_1.Socks5HostType.IPv6);
          buff.writeBuffer((0, helpers_1.ipToBuffer)(options.remoteHost.host));
        } else {
          buff.writeUInt8(constants_1.Socks5HostType.Hostname);
          buff.writeUInt8(Buffer.byteLength(options.remoteHost.host));
          buff.writeString(options.remoteHost.host);
        }
        buff.writeUInt16BE(options.remoteHost.port);
        buff.writeBuffer(options.data);
        return buff.toBuffer();
      }
      /**
       * Parses a SOCKS UDP frame.
       * @param data
       */
      static parseUDPFrame(data) {
        const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
        buff.readOffset = 2;
        const frameNumber = buff.readUInt8();
        const hostType = buff.readUInt8();
        let remoteHost;
        if (hostType === constants_1.Socks5HostType.IPv4) {
          remoteHost = (0, helpers_1.int32ToIpv4)(buff.readUInt32BE());
        } else if (hostType === constants_1.Socks5HostType.IPv6) {
          remoteHost = ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm();
        } else {
          remoteHost = buff.readString(buff.readUInt8());
        }
        const remotePort = buff.readUInt16BE();
        return {
          frameNumber,
          remoteHost: {
            host: remoteHost,
            port: remotePort
          },
          data: buff.readBuffer()
        };
      }
      /**
       * Internal state setter. If the SocksClient is in an error state, it cannot be changed to a non error state.
       */
      setState(newState) {
        if (this.state !== constants_1.SocksClientState.Error) {
          this.state = newState;
        }
      }
      /**
       * Starts the connection establishment to the proxy and destination.
       * @param existingSocket Connected socket to use instead of creating a new one (internal use).
       */
      connect(existingSocket) {
        this.onDataReceived = (data) => this.onDataReceivedHandler(data);
        this.onClose = () => this.onCloseHandler();
        this.onError = (err) => this.onErrorHandler(err);
        this.onConnect = () => this.onConnectHandler();
        const timer = setTimeout(() => this.onEstablishedTimeout(), this.options.timeout || constants_1.DEFAULT_TIMEOUT);
        if (timer.unref && typeof timer.unref === "function") {
          timer.unref();
        }
        if (existingSocket) {
          this.socket = existingSocket;
        } else {
          this.socket = new net.Socket();
        }
        this.socket.once("close", this.onClose);
        this.socket.once("error", this.onError);
        this.socket.once("connect", this.onConnect);
        this.socket.on("data", this.onDataReceived);
        this.setState(constants_1.SocksClientState.Connecting);
        this.receiveBuffer = new receivebuffer_1.ReceiveBuffer();
        if (existingSocket) {
          this.socket.emit("connect");
        } else {
          this.socket.connect(this.getSocketOptions());
          if (this.options.set_tcp_nodelay !== void 0 && this.options.set_tcp_nodelay !== null) {
            this.socket.setNoDelay(!!this.options.set_tcp_nodelay);
          }
        }
        this.prependOnceListener("established", (info) => {
          setImmediate(() => {
            if (this.receiveBuffer.length > 0) {
              const excessData = this.receiveBuffer.get(this.receiveBuffer.length);
              info.socket.emit("data", excessData);
            }
            info.socket.resume();
          });
        });
      }
      // Socket options (defaults host/port to options.proxy.host/options.proxy.port)
      getSocketOptions() {
        return Object.assign(Object.assign({}, this.options.socket_options), { host: this.options.proxy.host || this.options.proxy.ipaddress, port: this.options.proxy.port });
      }
      /**
       * Handles internal Socks timeout callback.
       * Note: If the Socks client is not BoundWaitingForConnection or Established, the connection will be closed.
       */
      onEstablishedTimeout() {
        if (this.state !== constants_1.SocksClientState.Established && this.state !== constants_1.SocksClientState.BoundWaitingForConnection) {
          this.closeSocket(constants_1.ERRORS.ProxyConnectionTimedOut);
        }
      }
      /**
       * Handles Socket connect event.
       */
      onConnectHandler() {
        this.setState(constants_1.SocksClientState.Connected);
        if (this.options.proxy.type === 4) {
          this.sendSocks4InitialHandshake();
        } else {
          this.sendSocks5InitialHandshake();
        }
        this.setState(constants_1.SocksClientState.SentInitialHandshake);
      }
      /**
       * Handles Socket data event.
       * @param data
       */
      onDataReceivedHandler(data) {
        this.receiveBuffer.append(data);
        this.processData();
      }
      /**
       * Handles processing of the data we have received.
       */
      processData() {
        while (this.state !== constants_1.SocksClientState.Established && this.state !== constants_1.SocksClientState.Error && this.receiveBuffer.length >= this.nextRequiredPacketBufferSize) {
          if (this.state === constants_1.SocksClientState.SentInitialHandshake) {
            if (this.options.proxy.type === 4) {
              this.handleSocks4FinalHandshakeResponse();
            } else {
              this.handleInitialSocks5HandshakeResponse();
            }
          } else if (this.state === constants_1.SocksClientState.SentAuthentication) {
            this.handleInitialSocks5AuthenticationHandshakeResponse();
          } else if (this.state === constants_1.SocksClientState.SentFinalHandshake) {
            this.handleSocks5FinalHandshakeResponse();
          } else if (this.state === constants_1.SocksClientState.BoundWaitingForConnection) {
            if (this.options.proxy.type === 4) {
              this.handleSocks4IncomingConnectionResponse();
            } else {
              this.handleSocks5IncomingConnectionResponse();
            }
          } else {
            this.closeSocket(constants_1.ERRORS.InternalError);
            break;
          }
        }
      }
      /**
       * Handles Socket close event.
       * @param had_error
       */
      onCloseHandler() {
        this.closeSocket(constants_1.ERRORS.SocketClosed);
      }
      /**
       * Handles Socket error event.
       * @param err
       */
      onErrorHandler(err) {
        this.closeSocket(err.message);
      }
      /**
       * Removes internal event listeners on the underlying Socket.
       */
      removeInternalSocketHandlers() {
        this.socket.pause();
        this.socket.removeListener("data", this.onDataReceived);
        this.socket.removeListener("close", this.onClose);
        this.socket.removeListener("error", this.onError);
        this.socket.removeListener("connect", this.onConnect);
      }
      /**
       * Closes and destroys the underlying Socket. Emits an error event.
       * @param err { String } An error string to include in error event.
       */
      closeSocket(err) {
        if (this.state !== constants_1.SocksClientState.Error) {
          this.setState(constants_1.SocksClientState.Error);
          this.socket.destroy();
          this.removeInternalSocketHandlers();
          this.emit("error", new util_1.SocksClientError(err, this.options));
        }
      }
      /**
       * Sends initial Socks v4 handshake request.
       */
      sendSocks4InitialHandshake() {
        const userId = this.options.proxy.userId || "";
        const buff = new smart_buffer_1.SmartBuffer();
        buff.writeUInt8(4);
        buff.writeUInt8(constants_1.SocksCommand[this.options.command]);
        buff.writeUInt16BE(this.options.destination.port);
        if (net.isIPv4(this.options.destination.host)) {
          buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host));
          buff.writeStringNT(userId);
        } else {
          buff.writeUInt8(0);
          buff.writeUInt8(0);
          buff.writeUInt8(0);
          buff.writeUInt8(1);
          buff.writeStringNT(userId);
          buff.writeStringNT(this.options.destination.host);
        }
        this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks4Response;
        this.socket.write(buff.toBuffer());
      }
      /**
       * Handles Socks v4 handshake response.
       * @param data
       */
      handleSocks4FinalHandshakeResponse() {
        const data = this.receiveBuffer.get(8);
        if (data[1] !== constants_1.Socks4Response.Granted) {
          this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedConnection} - (${constants_1.Socks4Response[data[1]]})`);
        } else {
          if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) {
            const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
            buff.readOffset = 2;
            const remoteHost = {
              port: buff.readUInt16BE(),
              host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE())
            };
            if (remoteHost.host === "0.0.0.0") {
              remoteHost.host = this.options.proxy.ipaddress;
            }
            this.setState(constants_1.SocksClientState.BoundWaitingForConnection);
            this.emit("bound", { remoteHost, socket: this.socket });
          } else {
            this.setState(constants_1.SocksClientState.Established);
            this.removeInternalSocketHandlers();
            this.emit("established", { socket: this.socket });
          }
        }
      }
      /**
       * Handles Socks v4 incoming connection request (BIND)
       * @param data
       */
      handleSocks4IncomingConnectionResponse() {
        const data = this.receiveBuffer.get(8);
        if (data[1] !== constants_1.Socks4Response.Granted) {
          this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${constants_1.Socks4Response[data[1]]})`);
        } else {
          const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
          buff.readOffset = 2;
          const remoteHost = {
            port: buff.readUInt16BE(),
            host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE())
          };
          this.setState(constants_1.SocksClientState.Established);
          this.removeInternalSocketHandlers();
          this.emit("established", { remoteHost, socket: this.socket });
        }
      }
      /**
       * Sends initial Socks v5 handshake request.
       */
      sendSocks5InitialHandshake() {
        const buff = new smart_buffer_1.SmartBuffer();
        const supportedAuthMethods = [constants_1.Socks5Auth.NoAuth];
        if (this.options.proxy.userId || this.options.proxy.password) {
          supportedAuthMethods.push(constants_1.Socks5Auth.UserPass);
        }
        if (this.options.proxy.custom_auth_method !== void 0) {
          supportedAuthMethods.push(this.options.proxy.custom_auth_method);
        }
        buff.writeUInt8(5);
        buff.writeUInt8(supportedAuthMethods.length);
        for (const authMethod of supportedAuthMethods) {
          buff.writeUInt8(authMethod);
        }
        this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse;
        this.socket.write(buff.toBuffer());
        this.setState(constants_1.SocksClientState.SentInitialHandshake);
      }
      /**
       * Handles initial Socks v5 handshake response.
       * @param data
       */
      handleInitialSocks5HandshakeResponse() {
        const data = this.receiveBuffer.get(2);
        if (data[0] !== 5) {
          this.closeSocket(constants_1.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion);
        } else if (data[1] === constants_1.SOCKS5_NO_ACCEPTABLE_AUTH) {
          this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType);
        } else {
          if (data[1] === constants_1.Socks5Auth.NoAuth) {
            this.socks5ChosenAuthType = constants_1.Socks5Auth.NoAuth;
            this.sendSocks5CommandRequest();
          } else if (data[1] === constants_1.Socks5Auth.UserPass) {
            this.socks5ChosenAuthType = constants_1.Socks5Auth.UserPass;
            this.sendSocks5UserPassAuthentication();
          } else if (data[1] === this.options.proxy.custom_auth_method) {
            this.socks5ChosenAuthType = this.options.proxy.custom_auth_method;
            this.sendSocks5CustomAuthentication();
          } else {
            this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType);
          }
        }
      }
      /**
       * Sends Socks v5 user & password auth handshake.
       *
       * Note: No auth and user/pass are currently supported.
       */
      sendSocks5UserPassAuthentication() {
        const userId = this.options.proxy.userId || "";
        const password = this.options.proxy.password || "";
        const buff = new smart_buffer_1.SmartBuffer();
        buff.writeUInt8(1);
        buff.writeUInt8(Buffer.byteLength(userId));
        buff.writeString(userId);
        buff.writeUInt8(Buffer.byteLength(password));
        buff.writeString(password);
        this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse;
        this.socket.write(buff.toBuffer());
        this.setState(constants_1.SocksClientState.SentAuthentication);
      }
      sendSocks5CustomAuthentication() {
        return __awaiter2(this, void 0, void 0, function* () {
          this.nextRequiredPacketBufferSize = this.options.proxy.custom_auth_response_size;
          this.socket.write(yield this.options.proxy.custom_auth_request_handler());
          this.setState(constants_1.SocksClientState.SentAuthentication);
        });
      }
      handleSocks5CustomAuthHandshakeResponse(data) {
        return __awaiter2(this, void 0, void 0, function* () {
          return yield this.options.proxy.custom_auth_response_handler(data);
        });
      }
      handleSocks5AuthenticationNoAuthHandshakeResponse(data) {
        return __awaiter2(this, void 0, void 0, function* () {
          return data[1] === 0;
        });
      }
      handleSocks5AuthenticationUserPassHandshakeResponse(data) {
        return __awaiter2(this, void 0, void 0, function* () {
          return data[1] === 0;
        });
      }
      /**
       * Handles Socks v5 auth handshake response.
       * @param data
       */
      handleInitialSocks5AuthenticationHandshakeResponse() {
        return __awaiter2(this, void 0, void 0, function* () {
          this.setState(constants_1.SocksClientState.ReceivedAuthenticationResponse);
          let authResult = false;
          if (this.socks5ChosenAuthType === constants_1.Socks5Auth.NoAuth) {
            authResult = yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2));
          } else if (this.socks5ChosenAuthType === constants_1.Socks5Auth.UserPass) {
            authResult = yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2));
          } else if (this.socks5ChosenAuthType === this.options.proxy.custom_auth_method) {
            authResult = yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size));
          }
          if (!authResult) {
            this.closeSocket(constants_1.ERRORS.Socks5AuthenticationFailed);
          } else {
            this.sendSocks5CommandRequest();
          }
        });
      }
      /**
       * Sends Socks v5 final handshake request.
       */
      sendSocks5CommandRequest() {
        const buff = new smart_buffer_1.SmartBuffer();
        buff.writeUInt8(5);
        buff.writeUInt8(constants_1.SocksCommand[this.options.command]);
        buff.writeUInt8(0);
        if (net.isIPv4(this.options.destination.host)) {
          buff.writeUInt8(constants_1.Socks5HostType.IPv4);
          buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host));
        } else if (net.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/socks/build/index.js
var require_build = __commonJS({
  "node_modules/socks/build/index.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    __exportStar2(require_socksclient(), exports2);
  }
});

// node_modules/socks-proxy-agent/dist/index.js
var require_dist4 = __commonJS({
  "node_modules/socks-proxy-agent/dist/index.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SocksProxyAgent = void 0;
    var socks_1 = require_build();
    var agent_base_1 = require_dist();
    var debug_1 = __importDefault2(require_src());
    var dns = __importStar2(require("dns"));
    var net = __importStar2(require("net"));
    var tls = __importStar2(require("tls"));
    var url_1 = require("url");
    var debug = (0, debug_1.default)("socks-proxy-agent");
    var setServernameFromNonIpHost = (options) => {
      if (options.servername === void 0 && options.host && !net.isIP(options.host)) {
        return {
          ...options,
          servername: options.host
        };
      }
      return options;
    };
    function parseSocksURL(url) {
      let lookup = false;
      let type = 5;
      const host = url.hostname;
      const port = parseInt(url.port, 10) || 1080;
      switch (url.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(url.protocol)}`);
      }
      const proxy = {
        host,
        port,
        type
      };
      if (url.username) {
        Object.defineProperty(proxy, "userId", {
          value: decodeURIComponent(url.username),
          enumerable: false
        });
      }
      if (url.password != null) {
        Object.defineProperty(proxy, "password", {
          value: decodeURIComponent(url.password),
          enumerable: false
        });
      }
      return { lookup, proxy };
    }
    var SocksProxyAgent = class extends agent_base_1.Agent {
      constructor(uri, opts) {
        super(opts);
        const url = typeof uri === "string" ? new url_1.URL(uri) : uri;
        const { proxy, lookup } = parseSocksURL(url);
        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((resolve5, reject) => {
            lookupFn(host, {}, (err, res) => {
              if (err) {
                reject(err);
              } else {
                resolve5(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();
        };
        debug("Creating socks proxy connection: %o", socksOpts);
        const { socket } = await socks_1.SocksClient.createConnection(socksOpts);
        debug("Successfully created socks proxy connection");
        if (timeout !== null) {
          socket.setTimeout(timeout);
          socket.on("timeout", () => cleanup());
        }
        if (opts.secureEndpoint) {
          debug("Upgrading socket connection to TLS");
          const tlsSocket = tls.connect({
            ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"),
            socket
          });
          tlsSocket.once("error", (error) => {
            debug("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/data-uri-to-buffer/dist/common.js
var require_common3 = __commonJS({
  "node_modules/data-uri-to-buffer/dist/common.js"(exports2) {
    "use strict";
    init_prefix();
    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 data = unescape(uri.substring(firstComma + 1));
      const buffer = base64 ? convert.base64ToArrayBuffer(data) : convert.stringToBuffer(data);
      return {
        type,
        typeFull,
        charset,
        buffer
      };
    };
    exports2.makeDataUriToBuffer = makeDataUriToBuffer;
  }
});

// node_modules/data-uri-to-buffer/dist/node.js
var require_node2 = __commonJS({
  "node_modules/data-uri-to-buffer/dist/node.js"(exports2) {
    "use strict";
    init_prefix();
    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/get-uri/dist/notmodified.js
var require_notmodified = __commonJS({
  "node_modules/get-uri/dist/notmodified.js"(exports2) {
    "use strict";
    init_prefix();
    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/get-uri/dist/data.js
var require_data = __commonJS({
  "node_modules/get-uri/dist/data.js"(exports2) {
    "use strict";
    init_prefix();
    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_src());
    var stream_1 = require("stream");
    var crypto_1 = require("crypto");
    var data_uri_to_buffer_1 = require_node2();
    var notmodified_1 = __importDefault2(require_notmodified());
    var debug = (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 data = async ({ href: uri }, { cache } = {}) => {
      const shasum = (0, crypto_1.createHash)("sha1");
      shasum.update(uri);
      const hash = shasum.digest("hex");
      debug('generated SHA1 hash for "data:" URI: %o', hash);
      if (cache?.hash === hash) {
        debug("got matching cache SHA1 hash: %o", hash);
        throw new notmodified_1.default();
      } else {
        debug('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 = data;
  }
});

// node_modules/get-uri/dist/notfound.js
var require_notfound = __commonJS({
  "node_modules/get-uri/dist/notfound.js"(exports2) {
    "use strict";
    init_prefix();
    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/get-uri/dist/file.js
var require_file = __commonJS({
  "node_modules/get-uri/dist/file.js"(exports2) {
    "use strict";
    init_prefix();
    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_src());
    var fs_1 = require("fs");
    var notfound_1 = __importDefault2(require_notfound());
    var notmodified_1 = __importDefault2(require_notmodified());
    var url_1 = require("url");
    var debug = (0, debug_1.default)("get-uri:file");
    var file = async ({ href: uri }, opts = {}) => {
      const {
        cache,
        flags = "r",
        mode: mode2 = 438
        // =0666
      } = opts;
      try {
        const filepath = (0, url_1.fileURLToPath)(uri);
        debug("Normalized pathname: %o", filepath);
        const fdHandle = await fs_1.promises.open(filepath, flags, mode2);
        const fd = fdHandle.fd;
        const stat = await fdHandle.stat();
        if (cache && cache.stat && stat && isNotModified(cache.stat, stat)) {
          await fdHandle.close();
          throw new notmodified_1.default();
        }
        const rs = (0, fs_1.createReadStream)(filepath, {
          autoClose: true,
          ...opts,
          fd
        });
        rs.stat = stat;
        return rs;
      } catch (err) {
        if (err.code === "ENOENT") {
          throw new notfound_1.default();
        }
        throw err;
      }
    };
    exports2.file = file;
    function isNotModified(prev, curr) {
      return +prev.mtime === +curr.mtime;
    }
  }
});

// node_modules/basic-ftp/dist/parseControlResponse.js
var require_parseControlResponse = __commonJS({
  "node_modules/basic-ftp/dist/parseControlResponse.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.parseControlResponse = parseControlResponse;
    exports2.isSingleLine = isSingleLine;
    exports2.isMultiline = isMultiline;
    exports2.positiveCompletion = positiveCompletion;
    exports2.positiveIntermediate = positiveIntermediate;
    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 };
    }
    function isSingleLine(line) {
      return /^\d\d\d(?:$| )/.test(line);
    }
    function isMultiline(line) {
      return /^\d\d\d-/.test(line);
    }
    function positiveCompletion(code) {
      return code >= 200 && code < 300;
    }
    function positiveIntermediate(code) {
      return code >= 300 && code < 400;
    }
    function isNotBlank(str) {
      return str.trim() !== "";
    }
  }
});

// node_modules/basic-ftp/dist/FtpContext.js
var require_FtpContext = __commonJS({
  "node_modules/basic-ftp/dist/FtpContext.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.FTPContext = exports2.FTPError = void 0;
    var net_1 = require("net");
    var parseControlResponse_1 = require_parseControlResponse();
    var FTPError = class extends Error {
      constructor(res) {
        super(res.message);
        this.name = this.constructor.name;
        this.code = res.code;
      }
    };
    exports2.FTPError = FTPError;
    function doNothing() {
    }
    var FTPContext = class {
      /**
       * Instantiate an FTP context.
       *
       * @param timeout - Timeout in milliseconds to apply to control and data connections. Use 0 for no timeout.
       * @param encoding - Encoding to use for control connection. UTF-8 by default. Use "latin1" for older servers.
       */
      constructor(timeout = 0, encoding = "utf8") {
        this.timeout = timeout;
        this.verbose = false;
        this.ipFamily = void 0;
        this.tlsOptions = {};
        this._partialResponse = "";
        this._encoding = encoding;
        this._socket = this.socket = this._newSocket();
        this._dataSocket = void 0;
      }
      /**
       * Close the context.
       */
      close() {
        const message = this._task ? "User closed client during task" : "User closed client";
        const err = new Error(message);
        this.closeWithError(err);
      }
      /**
       * Close the context with an error.
       */
      closeWithError(err) {
        if (this._closingError) {
          return;
        }
        this._closingError = err;
        this._closeControlSocket();
        this._closeSocket(this._dataSocket);
        this._passToHandler(err);
        this._stopTrackingTask();
      }
      /**
       * Returns true if this context has been closed or hasn't been connected yet. You can reopen it with `access`.
       */
      get closed() {
        return this.socket.remoteAddress === void 0 || this._closingError !== void 0;
      }
      /**
       * Reset this contex and all of its state.
       */
      reset() {
        this.socket = this._newSocket();
      }
      /**
       * Get the FTP control socket.
       */
      get socket() {
        return this._socket;
      }
      /**
       * Set the socket for the control connection. This will only close the current control socket
       * if the new one is not an upgrade to the current one.
       */
      set socket(socket) {
        this.dataSocket = void 0;
        this.tlsOptions = {};
        this._partialResponse = "";
        if (this._socket) {
          const newSocketUpgradesExisting = socket.localPort === this._socket.localPort;
          if (newSocketUpgradesExisting) {
            this._removeSocketListeners(this.socket);
          } else {
            this._closeControlSocket();
          }
        }
        if (socket) {
          this._closingError = void 0;
          socket.setTimeout(0);
          socket.setEncoding(this._encoding);
          socket.setKeepAlive(true);
          socket.on("data", (data) => this._onControlSocketData(data));
          socket.on("end", () => this.closeWithError(new Error("Server sent FIN packet unexpectedly, closing connection.")));
          socket.on("close", (hadError) => {
            if (!hadError)
              this.closeWithError(new Error("Server closed connection unexpectedly."));
          });
          this._setupDefaultErrorHandlers(socket, "control socket");
        }
        this._socket = socket;
      }
      /**
       * Get the current FTP data connection if present.
       */
      get dataSocket() {
        return this._dataSocket;
      }
      /**
       * Set the socket for the data connection. This will automatically close the former data socket.
       */
      set dataSocket(socket) {
        this._closeSocket(this._dataSocket);
        if (socket) {
          socket.setTimeout(0);
          this._setupDefaultErrorHandlers(socket, "data socket");
        }
        this._dataSocket = socket;
      }
      /**
       * Get the currently used encoding.
       */
      get encoding() {
        return this._encoding;
      }
      /**
       * Set the encoding used for the control socket.
       *
       * See https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings for what encodings
       * are supported by Node.
       */
      set encoding(encoding) {
        this._encoding = encoding;
        if (this.socket) {
          this.socket.setEncoding(encoding);
        }
      }
      /**
       * Send an FTP command without waiting for or handling the result.
       */
      send(command2) {
        if (/[\r\n\0]/.test(command2)) {
          throw new Error(`Invalid command: Contains control characters. (${command2})`);
        }
        const containsPassword = command2.startsWith("PASS");
        const message = containsPassword ? "> PASS ###" : `> ${command2}`;
        this.log(message);
        this._socket.write(command2 + "\r\n", this.encoding);
      }
      /**
       * Send an FTP command and handle the first response. Use this if you have a simple
       * request-response situation.
       */
      request(command2) {
        return this.handle(command2, (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(command2, 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 (command2) {
            this.send(command2);
          }
        });
      }
      /**
       * 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/basic-ftp/dist/FileInfo.js
var require_FileInfo = __commonJS({
  "node_modules/basic-ftp/dist/FileInfo.js"(exports2) {
    "use strict";
    init_prefix();
    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/basic-ftp/dist/parseListDOS.js
var require_parseListDOS = __commonJS({
  "node_modules/basic-ftp/dist/parseListDOS.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.testLine = testLine;
    exports2.parseLine = parseLine;
    exports2.transformList = transformList;
    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);
    }
    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 file = new FileInfo_1.FileInfo(name);
      const fileType = groups[3];
      if (fileType === "<DIR>") {
        file.type = FileInfo_1.FileType.Directory;
        file.size = 0;
      } else {
        file.type = FileInfo_1.FileType.File;
        file.size = parseInt(groups[4], 10);
      }
      file.rawModifiedAt = groups[1] + " " + groups[2];
      return file;
    }
    function transformList(files) {
      return files;
    }
  }
});

// node_modules/basic-ftp/dist/parseListUnix.js
var require_parseListUnix = __commonJS({
  "node_modules/basic-ftp/dist/parseListUnix.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.testLine = testLine;
    exports2.parseLine = parseLine;
    exports2.transformList = transformList;
    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);
    }
    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 file = new FileInfo_1.FileInfo(name);
      file.size = parseInt(groups[18], 10);
      file.user = groups[16];
      file.group = groups[17];
      file.hardLinkCount = parseInt(groups[15], 10);
      file.rawModifiedAt = groups[19] + " " + groups[20];
      file.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":
          file.type = FileInfo_1.FileType.Directory;
          break;
        case "e":
          file.type = FileInfo_1.FileType.SymbolicLink;
          break;
        case "l":
          file.type = FileInfo_1.FileType.SymbolicLink;
          break;
        case "b":
        case "c":
          file.type = FileInfo_1.FileType.File;
          break;
        case "f":
        case "-":
          file.type = FileInfo_1.FileType.File;
          break;
        default:
          file.type = FileInfo_1.FileType.Unknown;
      }
      if (file.isSymbolicLink) {
        const end = name.indexOf(" -> ");
        if (end !== -1) {
          file.name = name.substring(0, end);
          file.link = name.substring(end + 4);
        }
      }
      return file;
    }
    function transformList(files) {
      return files;
    }
    function parseMode(r, w, x) {
      let value = 0;
      if (r !== "-") {
        value += FileInfo_1.FileInfo.UnixPermission.Read;
      }
      if (w !== "-") {
        value += FileInfo_1.FileInfo.UnixPermission.Write;
      }
      const execToken = x.charAt(0);
      if (execToken !== "-" && execToken.toUpperCase() !== execToken) {
        value += FileInfo_1.FileInfo.UnixPermission.Execute;
      }
      return value;
    }
  }
});

// node_modules/basic-ftp/dist/parseListMLSD.js
var require_parseListMLSD = __commonJS({
  "node_modules/basic-ftp/dist/parseListMLSD.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.testLine = testLine;
    exports2.parseLine = parseLine;
    exports2.transformList = transformList;
    exports2.parseMLSxDate = parseMLSxDate;
    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(" ");
    }
    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;
    }
    function transformList(files) {
      const nonLinksByID = /* @__PURE__ */ new Map();
      for (const file of files) {
        if (!file.isSymbolicLink && file.uniqueID !== void 0) {
          nonLinksByID.set(file.uniqueID, file);
        }
      }
      const resolvedFiles = [];
      for (const file of files) {
        if (file.isSymbolicLink && file.uniqueID !== void 0 && file.link === void 0) {
          const target = nonLinksByID.get(file.uniqueID);
          if (target !== void 0) {
            file.link = target.name;
          }
        }
        const isPartOfDirectory = !file.name.includes("/");
        if (isPartOfDirectory) {
          resolvedFiles.push(file);
        }
      }
      return resolvedFiles;
    }
    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
      ));
    }
  }
});

// node_modules/basic-ftp/dist/parseList.js
var require_parseList = __commonJS({
  "node_modules/basic-ftp/dist/parseList.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
      var ownKeys2 = function(o) {
        ownKeys2 = 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 ownKeys2(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]);
        }
        __setModuleDefault2(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.parseList = parseList;
    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((parser2) => parser2.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 parser2 = firstCompatibleParser(testLine, availableParsers);
      if (!parser2) {
        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(parser2.parseLine).filter((info) => info !== void 0);
      return parser2.transformList(files);
    }
  }
});

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

// node_modules/basic-ftp/dist/netUtils.js
var require_netUtils = __commonJS({
  "node_modules/basic-ftp/dist/netUtils.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.describeTLS = describeTLS;
    exports2.describeAddress = describeAddress;
    exports2.upgradeSocket = upgradeSocket;
    exports2.ipIsPrivateV4Address = ipIsPrivateV4Address;
    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";
    }
    function describeAddress(socket) {
      if (socket.remoteFamily === "IPv6") {
        return `[${socket.remoteAddress}]:${socket.remotePort}`;
      }
      return `${socket.remoteAddress}:${socket.remotePort}`;
    }
    function upgradeSocket(socket, options) {
      return new Promise((resolve5, 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");
            resolve5(tlsSocket);
          }
        }).once("error", (error) => {
          reject(error);
        });
      });
    }
    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";
    }
  }
});

// node_modules/basic-ftp/dist/transfer.js
var require_transfer = __commonJS({
  "node_modules/basic-ftp/dist/transfer.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.enterPassiveModeIPv6 = enterPassiveModeIPv6;
    exports2.parseEpsvResponse = parseEpsvResponse;
    exports2.enterPassiveModeIPv4 = enterPassiveModeIPv4;
    exports2.enterPassiveModeIPv4_forceControlHostIP = enterPassiveModeIPv4_forceControlHostIP;
    exports2.parsePasvResponse = parsePasvResponse;
    exports2.connectForPassiveTransfer = connectForPassiveTransfer;
    exports2.uploadFrom = uploadFrom;
    exports2.downloadTo = downloadTo;
    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;
    }
    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;
    }
    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;
    }
    async function enterPassiveModeIPv4_forceControlHostIP(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 (controlHost === void 0) {
        throw new Error("Control socket is disconnected, can't get remote address.");
      }
      await connectForPassiveTransfer(controlHost, target.port, ftp);
      return res;
    }
    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)
      };
    }
    function connectForPassiveTransfer(host, port, ftp) {
      return new Promise((resolve5, 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;
          resolve5();
        });
      });
    }
    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, config2) {
      const resolver = new TransferResolver(config2.ftp, config2.tracker);
      const fullCommand = `${config2.command} ${config2.remotePath}`;
      return config2.ftp.handle(fullCommand, (res, task) => {
        if (res instanceof Error) {
          resolver.onError(task, res);
        } else if (res.code === 150 || res.code === 125) {
          const dataSocket = config2.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", () => {
            config2.ftp.log(`Uploading to ${(0, netUtils_1.describeAddress)(dataSocket)} (${(0, netUtils_1.describeTLS)(dataSocket)})`);
            resolver.onDataStart(config2.remotePath, config2.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);
        }
      });
    }
    function downloadTo(destination, config2) {
      if (!config2.ftp.dataSocket) {
        throw new Error("Download will be initiated but no data connection is available.");
      }
      const resolver = new TransferResolver(config2.ftp, config2.tracker);
      return config2.ftp.handle(config2.command, (res, task) => {
        if (res instanceof Error) {
          resolver.onError(task, res);
        } else if (res.code === 150 || res.code === 125) {
          const dataSocket = config2.ftp.dataSocket;
          if (!dataSocket) {
            resolver.onError(task, new Error("Download should begin but no data connection is available."));
            return;
          }
          config2.ftp.log(`Downloading from ${(0, netUtils_1.describeAddress)(dataSocket)} (${(0, netUtils_1.describeTLS)(dataSocket)})`);
          resolver.onDataStart(config2.remotePath, config2.type);
          (0, stream_1.pipeline)(dataSocket, destination, (err) => {
            if (err) {
              resolver.onError(task, err);
            } else {
              resolver.onDataDone(task);
            }
          });
        } else if (res.code === 350) {
          config2.ftp.send("RETR " + config2.remotePath);
        } else if ((0, parseControlResponse_1.positiveCompletion)(res.code)) {
          resolver.onControlDone(task, res);
        } else if ((0, parseControlResponse_1.positiveIntermediate)(res.code)) {
          resolver.onUnexpectedRequest(res);
        }
      });
    }
    function onConditionOrEvent(condition, emitter, eventName, action) {
      if (condition === true) {
        action();
      } else {
        emitter.once(eventName, () => action());
      }
    }
  }
});

// node_modules/basic-ftp/dist/Client.js
var require_Client = __commonJS({
  "node_modules/basic-ftp/dist/Client.js"(exports2) {
    "use strict";
    init_prefix();
    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 defaultClientOptions = {
      allowSeparateTransferHost: true
    };
    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, options = defaultClientOptions) {
        this.availableListCommands = LIST_COMMANDS_DEFAULT();
        this.ftp = new FtpContext_1.FTPContext(timeout);
        this.prepareTransfer = this._enterFirstCompatibleMode([
          transfer_1.enterPassiveModeIPv6,
          options.allowSeparateTransferHost ? transfer_1.enterPassiveModeIPv4 : transfer_1.enterPassiveModeIPv4_forceControlHostIP
        ]);
        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(command2, 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(command2);
        }
        return this.ftp.request(command2);
      }
      /**
       * 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(command2) {
        return this.ftp.handle(command2, (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 = {}, command2 = "AUTH TLS") {
        const ret = await this.send(command2);
        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 _a2, _b2;
        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 = (_a2 = options.secureOptions) !== null && _a2 !== void 0 ? _a2 : {};
          secureOptions.host = (_b2 = secureOptions.host) !== null && _b2 !== void 0 ? _b2 : 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(path2) {
        const validPath = await this.protectWhitespace(path2);
        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(path2) {
        const validPath = await this.protectWhitespace(path2);
        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(path2) {
        const validPath = await this.protectWhitespace(path2);
        const command2 = `SIZE ${validPath}`;
        const res = await this.send(command2);
        const size = parseInt(res.message.slice(4), 10);
        if (Number.isNaN(size)) {
          throw new Error(`Can't parse response to command '${command2}' 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(path2, ignoreErrorCodes = false) {
        const validPath = await this.protectWhitespace(path2);
        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, command2, options) {
        if (typeof source === "string") {
          return this._uploadLocalFile(source, remotePath, command2, options);
        }
        return this._uploadFromStream(source, remotePath, command2);
      }
      /**
       * @protected
       */
      async _uploadLocalFile(localPath, remotePath, command2, 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, command2);
        } finally {
          await ignoreError(() => fsClose(fd));
        }
      }
      /**
       * @protected
       */
      async _uploadFromStream(source, remotePath, command2) {
        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: command2,
            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(path2 = "") {
        const validPath = await this.protectWhitespace(path2);
        let lastError;
        for (const candidate of this.availableListCommands) {
          const command2 = validPath === "" ? candidate : `${candidate} ${validPath}`;
          await this.prepareTransfer(this.ftp);
          try {
            const parsedList = await this._requestListWithCommand(command2);
            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(command2) {
        const buffer = new StringWriter_1.StringWriter();
        await (0, transfer_1.downloadTo)(buffer, {
          ftp: this.ftp,
          tracker: this._progressTracker,
          command: command2,
          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 file of await this.list()) {
          if (file.isDirectory) {
            await this.cd(file.name);
            await this.clearWorkingDir();
            await this.cdup();
            await this.removeEmptyDir(file.name);
          } else {
            await this.remove(file.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 file of files) {
          const fullPath = (0, path_1.join)(localDirPath, file);
          const stats = await fsStat(fullPath);
          if (stats.isFile()) {
            await this.uploadFrom(fullPath, file);
          } else if (stats.isDirectory()) {
            await this._openDir(file);
            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 file of await this.list()) {
          const hasInvalidName = !file.name || (0, path_1.basename)(file.name) !== file.name;
          if (hasInvalidName) {
            const safeName = JSON.stringify(file.name);
            this.ftp.log(`Invalid filename from server listing, will skip file. (${safeName})`);
            continue;
          }
          const localPath = (0, path_1.join)(localDirPath, file.name);
          if (file.isDirectory) {
            await this.cd(file.name);
            await this._downloadFromWorkingDir(localPath);
            await this.cdup();
          } else if (file.isFile) {
            await this.downloadTo(localPath, file.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(path2) {
        const validPath = await this.protectWhitespace(path2);
        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(path2) {
        if (!path2.startsWith(" ")) {
          return path2;
        }
        const pwd = await this.pwd();
        const absolutePathPrefix = pwd.endsWith("/") ? pwd : pwd + "/";
        return absolutePathPrefix + path2;
      }
      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(path2) {
      try {
        await fsStat(path2);
      } catch (_a2) {
        await fsMkDir(path2, { recursive: true });
      }
    }
    async function ignoreError(func) {
      try {
        return await func();
      } catch (_a2) {
        return void 0;
      }
    }
  }
});

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

// node_modules/basic-ftp/dist/index.js
var require_dist5 = __commonJS({
  "node_modules/basic-ftp/dist/index.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, 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/get-uri/dist/ftp.js
var require_ftp = __commonJS({
  "node_modules/get-uri/dist/ftp.js"(exports2) {
    "use strict";
    init_prefix();
    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_src());
    var notfound_1 = __importDefault2(require_notfound());
    var notmodified_1 = __importDefault2(require_notmodified());
    var debug = (0, debug_1.default)("get-uri:ftp");
    var ftp = async (url, opts = {}) => {
      const { cache } = opts;
      const filepath = decodeURIComponent(url.pathname);
      let lastModified;
      if (!filepath) {
        throw new TypeError('No "pathname"!');
      }
      const client2 = new basic_ftp_1.Client();
      try {
        const host = url.hostname || url.host || "localhost";
        const port = parseInt(url.port || "0", 10) || 21;
        const user = url.username ? decodeURIComponent(url.username) : void 0;
        const password = url.password ? decodeURIComponent(url.password) : void 0;
        await client2.access({
          host,
          port,
          user,
          password,
          ...opts
        });
        try {
          lastModified = await client2.lastMod(filepath);
        } catch (err) {
          if (err.code === 550) {
            throw new notfound_1.default();
          }
        }
        if (!lastModified) {
          const list = await client2.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;
        client2.downloadTo(stream, filepath).then((result) => {
          debug(result.message);
          client2.close();
        });
        rs.lastModified = lastModified;
        return rs;
      } catch (err) {
        client2.close();
        throw err;
      }
      function isNotModified() {
        if (cache?.lastModified && lastModified) {
          return +cache.lastModified === +lastModified;
        }
        return false;
      }
    };
    exports2.ftp = ftp;
  }
});

// node_modules/get-uri/dist/http-error.js
var require_http_error = __commonJS({
  "node_modules/get-uri/dist/http-error.js"(exports2) {
    "use strict";
    init_prefix();
    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/get-uri/dist/http.js
var require_http = __commonJS({
  "node_modules/get-uri/dist/http.js"(exports2) {
    "use strict";
    init_prefix();
    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_src());
    var http_error_1 = __importDefault2(require_http_error());
    var notfound_1 = __importDefault2(require_notfound());
    var notmodified_1 = __importDefault2(require_notmodified());
    var debug = (0, debug_1.default)("get-uri:http");
    var http = async (url, opts = {}) => {
      debug("GET %o", url.href);
      const cache = getCache(url, opts.cache);
      if (cache && isFresh(cache) && typeof cache.statusCode === "number") {
        const type2 = cache.statusCode / 100 | 0;
        if (type2 === 3 && cache.headers.location) {
          debug("cached redirect");
          throw new Error("TODO: implement cached redirects!");
        }
        throw new notmodified_1.default();
      }
      const maxRedirects = typeof opts.maxRedirects === "number" ? opts.maxRedirects : 5;
      debug("allowing %o max redirects", maxRedirects);
      let mod;
      if (opts.http) {
        mod = opts.http;
        debug("using secure `https` core module");
      } else {
        mod = http_1.default;
        debug("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;
          debug('added "If-Modified-Since" request header: %o', lastModified);
        }
        const etag = cache.headers.etag;
        if (etag) {
          options.headers["If-None-Match"] = etag;
          debug('added "If-None-Match" request header: %o', etag);
        }
      }
      const req = mod.get(url, options);
      const [res] = await (0, events_1.once)(req, "response");
      const code = res.statusCode || 0;
      res.date = Date.now();
      res.parsed = url;
      debug("got %o response status code", code);
      const type = code / 100 | 0;
      const location2 = res.headers.location;
      if (type === 3 && location2) {
        if (!opts.redirects)
          opts.redirects = [];
        const redirects = opts.redirects;
        if (redirects.length < maxRedirects) {
          debug('got a "redirect" status code with Location: %o', location2);
          res.resume();
          redirects.push(res);
          const newUri = new URL(location2, url.href);
          debug("resolved redirect URL: %o", newUri.href);
          const left2 = maxRedirects - redirects.length;
          debug("%o more redirects allowed after this one", left2);
          if (newUri.protocol !== url.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 = http;
    function isFresh(cache) {
      let fresh = false;
      let expires = parseInt(cache.headers.expires || "", 10);
      const cacheControl = cache.headers["cache-control"];
      if (cacheControl) {
        debug("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) {
                debug('cache is "fresh" due to previous %o Cache-Control param', part);
              }
              return fresh;
            case "must-revalidate":
              break;
            case "no-cache":
            case "no-store":
              debug('cache is "stale" due to explicit %o Cache-Control param', name);
              return false;
            default:
              break;
          }
        }
      } else if (expires) {
        debug("Expires: %o", expires);
        fresh = Date.now() < expires;
        if (fresh) {
          debug('cache is "fresh" due to previous Expires response header');
        }
        return fresh;
      }
      return false;
    }
    function getCache(url, cache) {
      if (cache) {
        if (cache.parsed && cache.parsed.href === url.href) {
          return cache;
        }
        if (cache.redirects) {
          for (let i = 0; i < cache.redirects.length; i++) {
            const c = getCache(url, cache.redirects[i]);
            if (c) {
              return c;
            }
          }
        }
      }
      return null;
    }
  }
});

// node_modules/get-uri/dist/https.js
var require_https = __commonJS({
  "node_modules/get-uri/dist/https.js"(exports2) {
    "use strict";
    init_prefix();
    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 https = (url, opts) => {
      return (0, http_1.http)(url, { ...opts, http: https_1.default });
    };
    exports2.https = https;
  }
});

// node_modules/get-uri/dist/index.js
var require_dist6 = __commonJS({
  "node_modules/get-uri/dist/index.js"(exports2) {
    "use strict";
    init_prefix();
    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_src());
    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 debug = (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) {
      debug("getUri(%o)", uri);
      if (!uri) {
        throw new TypeError('Must pass in a URI to "getUri()"');
      }
      const url = typeof uri === "string" ? new URL(uri) : uri;
      const protocol = url.protocol.replace(/:$/, "");
      if (!isValidProtocol(protocol)) {
        throw new TypeError(`Unsupported protocol "${protocol}" specified in URI: "${uri}"`);
      }
      const getter = exports2.protocols[protocol];
      return getter(url, opts);
    }
    exports2.getUri = getUri;
  }
});

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

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

// node_modules/esutils/lib/keyword.js
var require_keyword = __commonJS({
  "node_modules/esutils/lib/keyword.js"(exports2, module2) {
    init_prefix();
    (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/esutils/lib/utils.js
var require_utils3 = __commonJS({
  "node_modules/esutils/lib/utils.js"(exports2) {
    init_prefix();
    (function() {
      "use strict";
      exports2.ast = require_ast();
      exports2.code = require_code();
      exports2.keyword = require_keyword();
    })();
  }
});

// node_modules/source-map/lib/base64.js
var require_base642 = __commonJS({
  "node_modules/source-map/lib/base64.js"(exports2) {
    init_prefix();
    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/source-map/lib/base64-vlq.js
var require_base64_vlq = __commonJS({
  "node_modules/source-map/lib/base64-vlq.js"(exports2) {
    init_prefix();
    var base64 = require_base642();
    var VLQ_BASE_SHIFT = 5;
    var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
    var VLQ_BASE_MASK = VLQ_BASE - 1;
    var VLQ_CONTINUATION_BIT = VLQ_BASE;
    function toVLQSigned(aValue) {
      return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0;
    }
    function fromVLQSigned(aValue) {
      var isNegative = (aValue & 1) === 1;
      var shifted = aValue >> 1;
      return isNegative ? -shifted : shifted;
    }
    exports2.encode = function base64VLQ_encode(aValue) {
      var encoded = "";
      var digit;
      var vlq = toVLQSigned(aValue);
      do {
        digit = vlq & VLQ_BASE_MASK;
        vlq >>>= VLQ_BASE_SHIFT;
        if (vlq > 0) {
          digit |= VLQ_CONTINUATION_BIT;
        }
        encoded += 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/source-map/lib/util.js
var require_util4 = __commonJS({
  "node_modules/source-map/lib/util.js"(exports2) {
    init_prefix();
    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 url = "";
      if (aParsedUrl.scheme) {
        url += aParsedUrl.scheme + ":";
      }
      url += "//";
      if (aParsedUrl.auth) {
        url += aParsedUrl.auth + "@";
      }
      if (aParsedUrl.host) {
        url += aParsedUrl.host;
      }
      if (aParsedUrl.port) {
        url += ":" + aParsedUrl.port;
      }
      if (aParsedUrl.path) {
        url += aParsedUrl.path;
      }
      return url;
    }
    exports2.urlGenerate = urlGenerate;
    function normalize2(aPath) {
      var path2 = aPath;
      var url = urlParse(aPath);
      if (url) {
        if (!url.path) {
          return aPath;
        }
        path2 = url.path;
      }
      var isAbsolute = exports2.isAbsolute(path2);
      var parts = path2.split(/\/+/);
      for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
        part = parts[i];
        if (part === ".") {
          parts.splice(i, 1);
        } else if (part === "..") {
          up++;
        } else if (up > 0) {
          if (part === "") {
            parts.splice(i + 1, up);
            up = 0;
          } else {
            parts.splice(i, 2);
            up--;
          }
        }
      }
      path2 = parts.join("/");
      if (path2 === "") {
        path2 = isAbsolute ? "/" : ".";
      }
      if (url) {
        url.path = path2;
        return urlGenerate(url);
      }
      return path2;
    }
    exports2.normalize = normalize2;
    function join(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 = join;
    exports2.isAbsolute = function(aPath) {
      return aPath.charAt(0) === "/" || urlRegexp.test(aPath);
    };
    function relative2(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 = relative2;
    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 = join(urlGenerate(parsed), sourceURL);
      }
      return normalize2(sourceURL);
    }
    exports2.computeSourceURL = computeSourceURL;
  }
});

// node_modules/source-map/lib/array-set.js
var require_array_set = __commonJS({
  "node_modules/source-map/lib/array-set.js"(exports2) {
    init_prefix();
    var util = require_util4();
    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 : util.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 = util.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 = util.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/source-map/lib/mapping-list.js
var require_mapping_list = __commonJS({
  "node_modules/source-map/lib/mapping-list.js"(exports2) {
    init_prefix();
    var util = require_util4();
    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 || util.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(util.compareByGeneratedPositionsInflated);
        this._sorted = true;
      }
      return this._array;
    };
    exports2.MappingList = MappingList;
  }
});

// node_modules/source-map/lib/source-map-generator.js
var require_source_map_generator = __commonJS({
  "node_modules/source-map/lib/source-map-generator.js"(exports2) {
    init_prefix();
    var base64VLQ = require_base64_vlq();
    var util = require_util4();
    var ArraySet = require_array_set().ArraySet;
    var MappingList = require_mapping_list().MappingList;
    function SourceMapGenerator(aArgs) {
      if (!aArgs) {
        aArgs = {};
      }
      this._file = util.getArg(aArgs, "file", null);
      this._sourceRoot = util.getArg(aArgs, "sourceRoot", null);
      this._skipValidation = util.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 = util.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 = util.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 = util.getArg(aArgs, "generated");
      var original = util.getArg(aArgs, "original", null);
      var source = util.getArg(aArgs, "source", null);
      var name = util.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 = util.relative(this._sourceRoot, source);
      }
      if (aSourceContent != null) {
        if (!this._sourcesContents) {
          this._sourcesContents = /* @__PURE__ */ Object.create(null);
        }
        this._sourcesContents[util.toSetString(source)] = aSourceContent;
      } else if (this._sourcesContents) {
        delete this._sourcesContents[util.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 = util.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 = util.join(aSourceMapPath, mapping.source);
            }
            if (sourceRoot != null) {
              mapping.source = util.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 = util.join(aSourceMapPath, sourceFile2);
          }
          if (sourceRoot != null) {
            sourceFile2 = util.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 (!util.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 = util.relative(aSourceRoot, source);
        }
        var key = util.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/source-map/lib/binary-search.js
var require_binary_search = __commonJS({
  "node_modules/source-map/lib/binary-search.js"(exports2) {
    init_prefix();
    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/source-map/lib/quick-sort.js
var require_quick_sort = __commonJS({
  "node_modules/source-map/lib/quick-sort.js"(exports2) {
    init_prefix();
    function swap(ary, x, y) {
      var temp = ary[x];
      ary[x] = ary[y];
      ary[y] = temp;
    }
    function randomIntInRange(low, high) {
      return Math.round(low + Math.random() * (high - low));
    }
    function doQuickSort(ary, comparator, p, r) {
      if (p < r) {
        var pivotIndex = randomIntInRange(p, r);
        var i = p - 1;
        swap(ary, pivotIndex, r);
        var pivot = ary[r];
        for (var j = p; j < r; j++) {
          if (comparator(ary[j], pivot) <= 0) {
            i += 1;
            swap(ary, i, j);
          }
        }
        swap(ary, i + 1, j);
        var q = i + 1;
        doQuickSort(ary, comparator, p, q - 1);
        doQuickSort(ary, comparator, q + 1, r);
      }
    }
    exports2.quickSort = function(ary, comparator) {
      doQuickSort(ary, comparator, 0, ary.length - 1);
    };
  }
});

// node_modules/source-map/lib/source-map-consumer.js
var require_source_map_consumer = __commonJS({
  "node_modules/source-map/lib/source-map-consumer.js"(exports2) {
    init_prefix();
    var util = require_util4();
    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 = util.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 = util.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 = util.getArg(aArgs, "line");
      var needle = {
        source: util.getArg(aArgs, "source"),
        originalLine: line,
        originalColumn: util.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",
        util.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: util.getArg(mapping, "generatedLine", null),
              column: util.getArg(mapping, "generatedColumn", null),
              lastColumn: util.getArg(mapping, "lastGeneratedColumn", null)
            });
            mapping = this._originalMappings[++index];
          }
        } else {
          var originalColumn = mapping.originalColumn;
          while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) {
            mappings.push({
              line: util.getArg(mapping, "generatedLine", null),
              column: util.getArg(mapping, "generatedColumn", null),
              lastColumn: util.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 = util.parseSourceMapInput(aSourceMap);
      }
      var version = util.getArg(sourceMap, "version");
      var sources = util.getArg(sourceMap, "sources");
      var names = util.getArg(sourceMap, "names", []);
      var sourceRoot = util.getArg(sourceMap, "sourceRoot", null);
      var sourcesContent = util.getArg(sourceMap, "sourcesContent", null);
      var mappings = util.getArg(sourceMap, "mappings");
      var file = util.getArg(sourceMap, "file", null);
      if (version != this._version) {
        throw new Error("Unsupported version: " + version);
      }
      if (sourceRoot) {
        sourceRoot = util.normalize(sourceRoot);
      }
      sources = sources.map(String).map(util.normalize).map(function(source) {
        return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) ? util.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 util.computeSourceURL(sourceRoot, s, aSourceMapURL);
      });
      this.sourceRoot = sourceRoot;
      this.sourcesContent = sourcesContent;
      this._mappings = mappings;
      this._sourceMapURL = aSourceMapURL;
      this.file = file;
    }
    BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
    BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
    BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
      var relativeSource = aSource;
      if (this.sourceRoot != null) {
        relativeSource = util.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 util.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, util.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, util.compareByGeneratedPositionsDeflated);
      this.__generatedMappings = generatedMappings;
      quickSort(originalMappings, util.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: util.getArg(aArgs, "line"),
        generatedColumn: util.getArg(aArgs, "column")
      };
      var index = this._findMapping(
        needle,
        this._generatedMappings,
        "generatedLine",
        "generatedColumn",
        util.compareByGeneratedPositionsDeflated,
        util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND)
      );
      if (index >= 0) {
        var mapping = this._generatedMappings[index];
        if (mapping.generatedLine === needle.generatedLine) {
          var source = util.getArg(mapping, "source", null);
          if (source !== null) {
            source = this._sources.at(source);
            source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
          }
          var name = util.getArg(mapping, "name", null);
          if (name !== null) {
            name = this._names.at(name);
          }
          return {
            source,
            line: util.getArg(mapping, "originalLine", null),
            column: util.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 = util.relative(this.sourceRoot, relativeSource);
      }
      var url;
      if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) {
        var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
        if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) {
          return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
        }
        if ((!url.path || url.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 = util.getArg(aArgs, "source");
      source = this._findSourceIndex(source);
      if (source < 0) {
        return {
          line: null,
          column: null,
          lastColumn: null
        };
      }
      var needle = {
        source,
        originalLine: util.getArg(aArgs, "line"),
        originalColumn: util.getArg(aArgs, "column")
      };
      var index = this._findMapping(
        needle,
        this._originalMappings,
        "originalLine",
        "originalColumn",
        util.compareByOriginalPositions,
        util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND)
      );
      if (index >= 0) {
        var mapping = this._originalMappings[index];
        if (mapping.source === needle.source) {
          return {
            line: util.getArg(mapping, "generatedLine", null),
            column: util.getArg(mapping, "generatedColumn", null),
            lastColumn: util.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 = util.parseSourceMapInput(aSourceMap);
      }
      var version = util.getArg(sourceMap, "version");
      var sections = util.getArg(sourceMap, "sections");
      if (version != this._version) {
        throw new Error("Unsupported version: " + version);
      }
      this._sources = new ArraySet();
      this._names = new ArraySet();
      var lastOffset = {
        line: -1,
        column: 0
      };
      this._sections = sections.map(function(s) {
        if (s.url) {
          throw new Error("Support for url field in sections not implemented.");
        }
        var offset = util.getArg(s, "offset");
        var offsetLine = util.getArg(offset, "line");
        var offsetColumn = util.getArg(offset, "column");
        if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) {
          throw new Error("Section offsets must be ordered and non-overlapping.");
        }
        lastOffset = offset;
        return {
          generatedOffset: {
            // The offset fields are 0-based, but we use 1-based indices when
            // encoding/decoding from VLQ.
            generatedLine: offsetLine + 1,
            generatedColumn: offsetColumn + 1
          },
          consumer: new SourceMapConsumer(util.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: util.getArg(aArgs, "line"),
        generatedColumn: util.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(util.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 = util.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, util.compareByGeneratedPositionsDeflated);
      quickSort(this.__originalMappings, util.compareByOriginalPositions);
    };
    exports2.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  }
});

// node_modules/source-map/lib/source-node.js
var require_source_node = __commonJS({
  "node_modules/source-map/lib/source-node.js"(exports2) {
    init_prefix();
    var SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
    var util = require_util4();
    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 = util.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 ? util.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[util.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(util.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/source-map/source-map.js
var require_source_map = __commonJS({
  "node_modules/source-map/source-map.js"(exports2) {
    init_prefix();
    exports2.SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
    exports2.SourceMapConsumer = require_source_map_consumer().SourceMapConsumer;
    exports2.SourceNode = require_source_node().SourceNode;
  }
});

// node_modules/escodegen/package.json
var require_package = __commonJS({
  "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/escodegen/escodegen.js
var require_escodegen = __commonJS({
  "node_modules/escodegen/escodegen.js"(exports2) {
    init_prefix();
    (function() {
      "use strict";
      var Syntax, Precedence, BinaryPrecedence, SourceNode, estraverse, esutils, base, indent, json, renumber, hexadecimal, quotes, escapeless, newline, space, parentheses, semicolons, safeConcatenation, directive, extra, parse, sourceMap, sourceCode, preserveBlankLines, FORMAT_MINIFY, FORMAT_DEFAULTS;
      estraverse = require_estraverse();
      esutils = require_utils3();
      Syntax = estraverse.Syntax;
      function isExpression(node) {
        return CodeGenerator.Expression.hasOwnProperty(node.type);
      }
      function isStatement(node) {
        return CodeGenerator.Statement.hasOwnProperty(node.type);
      }
      Precedence = {
        Sequence: 0,
        Yield: 1,
        Assignment: 1,
        Conditional: 2,
        ArrowFunction: 2,
        Coalesce: 3,
        LogicalOR: 4,
        LogicalAND: 5,
        BitwiseOR: 6,
        BitwiseXOR: 7,
        BitwiseAND: 8,
        Equality: 9,
        Relational: 10,
        BitwiseSHIFT: 11,
        Additive: 12,
        Multiplicative: 13,
        Exponentiation: 14,
        Await: 15,
        Unary: 15,
        Postfix: 16,
        OptionalChaining: 17,
        Call: 18,
        New: 19,
        TaggedTemplate: 20,
        Member: 21,
        Primary: 22
      };
      BinaryPrecedence = {
        "??": Precedence.Coalesce,
        "||": Precedence.LogicalOR,
        "&&": Precedence.LogicalAND,
        "|": Precedence.BitwiseOR,
        "^": Precedence.BitwiseXOR,
        "&": Precedence.BitwiseAND,
        "==": Precedence.Equality,
        "!=": Precedence.Equality,
        "===": Precedence.Equality,
        "!==": Precedence.Equality,
        "is": Precedence.Equality,
        "isnt": Precedence.Equality,
        "<": Precedence.Relational,
        ">": Precedence.Relational,
        "<=": Precedence.Relational,
        ">=": Precedence.Relational,
        "in": Precedence.Relational,
        "instanceof": Precedence.Relational,
        "<<": Precedence.BitwiseSHIFT,
        ">>": Precedence.BitwiseSHIFT,
        ">>>": Precedence.BitwiseSHIFT,
        "+": Precedence.Additive,
        "-": Precedence.Additive,
        "*": Precedence.Multiplicative,
        "%": Precedence.Multiplicative,
        "/": Precedence.Multiplicative,
        "**": Precedence.Exponentiation
      };
      var F_ALLOW_IN = 1, F_ALLOW_CALL = 1 << 1, F_ALLOW_UNPARATH_NEW = 1 << 2, F_FUNC_BODY = 1 << 3, F_DIRECTIVE_CTX = 1 << 4, F_SEMICOLON_OPT = 1 << 5, F_FOUND_COALESCE = 1 << 6;
      var E_FTT = F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW, E_TTF = F_ALLOW_IN | F_ALLOW_CALL, E_TTT = F_ALLOW_IN | F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW, E_TFF = F_ALLOW_IN, E_FFT = F_ALLOW_UNPARATH_NEW, E_TFT = F_ALLOW_IN | F_ALLOW_UNPARATH_NEW;
      var S_TFFF = F_ALLOW_IN, S_TFFT = F_ALLOW_IN | F_SEMICOLON_OPT, S_FFFF = 0, S_TFTF = F_ALLOW_IN | F_DIRECTIVE_CTX, S_TTFF = F_ALLOW_IN | F_FUNC_BODY;
      function getDefaultOptions() {
        return {
          indent: null,
          base: null,
          parse: null,
          comment: false,
          format: {
            indent: {
              style: "    ",
              base: 0,
              adjustMultilineComment: false
            },
            newline: "\n",
            space: " ",
            json: false,
            renumber: false,
            hexadecimal: false,
            quotes: "single",
            escapeless: false,
            compact: false,
            parentheses: true,
            semicolons: true,
            safeConcatenation: false,
            preserveBlankLines: false
          },
          moz: {
            comprehensionExpressionStartsWithAssignment: false,
            starlessGenerator: false
          },
          sourceMap: null,
          sourceMapRoot: null,
          sourceMapWithCode: false,
          directive: false,
          raw: true,
          verbatim: null,
          sourceCode: null
        };
      }
      function stringRepeat(str, num) {
        var result = "";
        for (num |= 0; num > 0; num >>>= 1, str += str) {
          if (num & 1) {
            result += str;
          }
        }
        return result;
      }
      function hasLineTerminator(str) {
        return /[\r\n]/g.test(str);
      }
      function endsWithLineTerminator(str) {
        var len = str.length;
        return len && esutils.code.isLineTerminator(str.charCodeAt(len - 1));
      }
      function 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 space ? space : " ";
      }
      function join(left2, right2) {
        var leftSource, rightSource, leftCharCode, rightCharCode;
        leftSource = toSourceNodeWhenNeeded(left2).toString();
        if (leftSource.length === 0) {
          return [right2];
        }
        rightSource = toSourceNodeWhenNeeded(right2).toString();
        if (rightSource.length === 0) {
          return [left2];
        }
        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 [left2, noEmptySpace(), right2];
        } else if (esutils.code.isWhiteSpace(leftCharCode) || esutils.code.isLineTerminator(leftCharCode) || esutils.code.isWhiteSpace(rightCharCode) || esutils.code.isLineTerminator(rightCharCode)) {
          return [left2, right2];
        }
        return [left2, space, right2];
      }
      function addIndent(stmt) {
        return [base, stmt];
      }
      function withIndent(fn) {
        var previousBase;
        previousBase = base;
        base += indent;
        fn(base);
        base = previousBase;
      }
      function calculateSpaces(str) {
        var i;
        for (i = str.length - 1; i >= 0; --i) {
          if (esutils.code.isLineTerminator(str.charCodeAt(i))) {
            break;
          }
        }
        return str.length - 1 - i;
      }
      function adjustMultilineComment(value, specialBase) {
        var 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 = base;
          if (array[1][spaces] === "*") {
            specialBase += " ";
          }
          base = specialBase;
        } else {
          if (spaces & 1) {
            --spaces;
          }
          previousBase = base;
        }
        for (i = 1, len = array.length; i < len; ++i) {
          sn = toSourceNodeWhenNeeded(addIndent(array[i].slice(spaces)));
          array[i] = sourceMap ? sn.join("") : sn;
        }
        base = 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([base, result, indent]).toString()));
            for (i = 0, len = stmt.trailingComments.length; i < len; ++i) {
              comment = stmt.trailingComments[i];
              if (tailingToStatement) {
                if (i === 0) {
                  result = [result, indent];
                } else {
                  result = [result, specialBase];
                }
                result.push(generateComment(comment, specialBase));
              } else {
                result = [result, addIndent(generateComment(comment))];
              }
              if (i !== len - 1 && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
                result = [result, "\n"];
              }
            }
          }
        }
        return result;
      }
      function generateBlankLines(start, end, result) {
        var j, newlineCount = 0;
        for (j = start; j < end; j++) {
          if (sourceCode[j] === "\n") {
            newlineCount++;
          }
        }
        for (j = 1; j < newlineCount; j++) {
          result.push(newline);
        }
      }
      function parenthesize(text, current, should) {
        if (current < 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] = newline + base + result[i];
        }
        return result;
      }
      function generateVerbatim(expr, precedence) {
        var verbatim, result, prec;
        verbatim = expr[extra.verbatim];
        if (typeof verbatim === "string") {
          result = parenthesize(generateVerbatimString(verbatim), Precedence.Sequence, precedence);
        } else {
          result = generateVerbatimString(verbatim.content);
          prec = verbatim.precedence != null ? verbatim.precedence : Precedence.Sequence;
          result = parenthesize(result, prec, precedence);
        }
        return toSourceNodeWhenNeeded(result, expr);
      }
      function CodeGenerator() {
      }
      CodeGenerator.prototype.maybeBlock = function(stmt, flags) {
        var result, noLeadingComment, that = this;
        noLeadingComment = !extra.comment || !stmt.leadingComments;
        if (stmt.type === Syntax.BlockStatement && noLeadingComment) {
          return [space, this.generateStatement(stmt, flags)];
        }
        if (stmt.type === Syntax.EmptyStatement && noLeadingComment) {
          return ";";
        }
        withIndent(function() {
          result = [
            newline,
            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, space];
        }
        if (ends) {
          return [result, base];
        }
        return [result, newline, base];
      };
      function generateIdentifier(node) {
        return toSourceNodeWhenNeeded(node.name, node);
      }
      function generateAsyncPrefix(node, spaceRequired) {
        return node.async ? "async" + (spaceRequired ? noEmptySpace() : space) : "";
      }
      function generateStarSuffix(node) {
        var isGenerator = node.generator && !extra.moz.starlessGenerator;
        return isGenerator ? "*" + space : "";
      }
      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("," + space);
            }
          }
          if (node.rest) {
            if (node.params.length) {
              result.push("," + space);
            }
            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(space);
          result.push("=>");
        }
        if (node.expression) {
          result.push(space);
          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" : "") + space + "("], 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 = join(result, operator);
          result = [join(
            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(left2, right2, operator, precedence, flags) {
        if (Precedence.Assignment < precedence) {
          flags |= F_ALLOW_IN;
        }
        return parenthesize(
          [
            this.generateExpression(left2, Precedence.Call, flags),
            space + operator + space,
            this.generateExpression(right2, 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 = ["{", newline], 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(newline);
                  }
                } else {
                  result.push(newline);
                }
              }
              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 = ["{", newline], 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(newline);
              }
            }
          });
          if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
            result.push(newline);
          }
          result.push(base);
          result.push("}");
          return result;
        },
        ClassDeclaration: function(stmt, flags) {
          var result, fragment;
          result = ["class"];
          if (stmt.id) {
            result = join(result, this.generateExpression(stmt.id, Precedence.Sequence, E_TTT));
          }
          if (stmt.superClass) {
            fragment = join("extends", this.generateExpression(stmt.superClass, Precedence.Unary, E_TTT));
            result = join(result, fragment);
          }
          result.push(space);
          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 = join("do", this.maybeBlock(stmt.body, S_TFFF));
          result = this.maybeBlockSuffix(stmt.body, result);
          return join(result, [
            "while" + space + "(",
            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" + space + "(",
                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 = join(result, "default");
          if (isStatement(stmt.declaration)) {
            result = join(result, this.generateStatement(stmt.declaration, bodyFlags));
          } else {
            result = join(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 join(result, this.generateStatement(stmt.declaration, bodyFlags));
          }
          if (stmt.specifiers) {
            if (stmt.specifiers.length === 0) {
              result = join(result, "{" + space + "}");
            } else if (stmt.specifiers[0].type === Syntax.ExportBatchSpecifier) {
              result = join(result, this.generateExpression(stmt.specifiers[0], Precedence.Sequence, E_TTT));
            } else {
              result = join(result, "{");
              withIndent(function(indent2) {
                var i, iz;
                result.push(newline);
                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("," + newline);
                  }
                }
              });
              if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
                result.push(newline);
              }
              result.push(base + "}");
            }
            if (stmt.source) {
              result = join(result, [
                "from" + space,
                // 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" + space,
            "*" + space,
            "from" + space,
            // 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",
              space,
              // ModuleSpecifier
              this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
              this.semicolon(flags)
            ];
          }
          result = [
            "import"
          ];
          cursor = 0;
          if (stmt.specifiers[cursor].type === Syntax.ImportDefaultSpecifier) {
            result = join(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 = join(result, [
                space,
                this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)
              ]);
            } else {
              result.push(space + "{");
              if (stmt.specifiers.length - cursor === 1) {
                result.push(space);
                result.push(this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT));
                result.push(space + "}" + space);
              } else {
                withIndent(function(indent2) {
                  var i, iz;
                  result.push(newline);
                  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("," + newline);
                    }
                  }
                });
                if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
                  result.push(newline);
                }
                result.push(base + "}" + space);
              }
            }
          }
          result = join(result, [
            "from" + space,
            // 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),
              space,
              "=",
              space,
              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("," + newline);
                result.push(addIndent(that.generateStatement(node, bodyFlags)));
              } else {
                result.push("," + space);
                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 [join(
            "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 = join(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 = join(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 = join(result, this.generateStatement(stmt.handler[i], S_TFFF));
                  if (stmt.finalizer || i + 1 !== iz) {
                    result = this.maybeBlockSuffix(stmt.handler[i].body, result);
                  }
                }
              } else {
                result = join(result, this.generateStatement(stmt.handler, S_TFFF));
                if (stmt.finalizer) {
                  result = this.maybeBlockSuffix(stmt.handler.body, result);
                }
              }
            }
          }
          if (stmt.finalizer) {
            result = join(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" + space + "(",
              that.generateExpression(stmt.discriminant, Precedence.Sequence, E_TTT),
              ")" + space + "{" + newline
            ];
          });
          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(newline);
              }
            }
          }
          result.push(addIndent("}"));
          return result;
        },
        SwitchCase: function(stmt, flags) {
          var result, fragment, i, iz, bodyFlags, that = this;
          withIndent(function() {
            if (stmt.test) {
              result = [
                join("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(newline);
            }
            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(newline);
              }
            }
          });
          return result;
        },
        IfStatement: function(stmt, flags) {
          var result, bodyFlags, semicolonOptional, that = this;
          withIndent(function() {
            result = [
              "if" + space + "(",
              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 = join(result, ["else ", this.generateStatement(stmt.alternate, bodyFlags)]);
            } else {
              result = join(result, join("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" + space + "("];
            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(space);
              result.push(that.generateExpression(stmt.test, Precedence.Sequence, E_TTT));
              result.push(";");
            } else {
              result.push(";");
            }
            if (stmt.update) {
              result.push(space);
              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(newline);
                }
              } else {
                result.push(newline);
              }
            }
            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 [join(
              "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" + space + "(",
              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" + space + "(",
              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("," + space);
            }
          }
          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),
              space + "?" + space,
              this.generateExpression(expr.consequent, Precedence.Assignment, flags),
              space + ":" + space,
              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 = join(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 = join(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("," + space);
            }
          }
          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 = join(
            "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("," + space);
              }
            }
            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 (space === "") {
            result = join(expr.operator, fragment);
          } else {
            result = [expr.operator];
            if (expr.operator.length > 2) {
              result = join(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 = join(
              result,
              this.generateExpression(expr.argument, Precedence.Yield, E_TTT)
            );
          }
          return parenthesize(result, Precedence.Yield, precedence);
        },
        AwaitExpression: function(expr, precedence, flags) {
          var result = join(
            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) || space);
          }
          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 ? newline : ""];
          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 ? newline : space));
              }
            }
          });
          if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
            result.push(newline);
          }
          result.push(multiline ? base : "");
          result.push("]");
          return result;
        },
        RestElement: function(expr, precedence, flags) {
          return "..." + this.generatePattern(expr.argument);
        },
        ClassExpression: function(expr, precedence, flags) {
          var result, fragment;
          result = ["class"];
          if (expr.id) {
            result = join(result, this.generateExpression(expr.id, Precedence.Sequence, E_TTT));
          }
          if (expr.superClass) {
            fragment = join("extends", this.generateExpression(expr.superClass, Precedence.Unary, E_TTT));
            result = join(result, fragment);
          }
          result.push(space);
          result.push(this.generateStatement(expr.body, S_TFFT));
          return result;
        },
        MethodDefinition: function(expr, precedence, flags) {
          var result, fragment;
          if (expr["static"]) {
            result = ["static" + space];
          } else {
            result = [];
          }
          if (expr.kind === "get" || expr.kind === "set") {
            fragment = [
              join(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 join(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),
            ":" + space,
            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 ["{", space, fragment, space, "}"];
            }
          }
          withIndent(function(indent2) {
            var i, iz;
            result = ["{", newline, indent2, fragment];
            if (multiline) {
              result.push("," + newline);
              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("," + newline);
                }
              }
            }
          });
          if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
            result.push(newline);
          }
          result.push(base);
          result.push("}");
          return result;
        },
        AssignmentPattern: function(expr, precedence, flags) {
          return this.generateAssignment(expr.left, expr.right, "=", precedence, flags);
        },
        ObjectPattern: function(expr, precedence, flags) {
          var result, i, iz, multiline, property, that = this;
          if (!expr.properties.length) {
            return "{}";
          }
          multiline = false;
          if (expr.properties.length === 1) {
            property = expr.properties[0];
            if (property.type === Syntax.Property && property.value.type !== Syntax.Identifier) {
              multiline = true;
            }
          } else {
            for (i = 0, iz = expr.properties.length; i < iz; ++i) {
              property = expr.properties[i];
              if (property.type === Syntax.Property && !property.shorthand) {
                multiline = true;
                break;
              }
            }
          }
          result = ["{", multiline ? newline : ""];
          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 ? newline : space));
              }
            }
          });
          if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
            result.push(newline);
          }
          result.push(multiline ? base : "");
          result.push("}");
          return result;
        },
        ThisExpression: function(expr, precedence, flags) {
          return "this";
        },
        Super: function(expr, precedence, flags) {
          return "super";
        },
        Identifier: function(expr, precedence, flags) {
          return generateIdentifier(expr);
        },
        ImportDefaultSpecifier: function(expr, precedence, flags) {
          return generateIdentifier(expr.id || expr.local);
        },
        ImportNamespaceSpecifier: function(expr, precedence, flags) {
          var result = ["*"];
          var id = expr.id || expr.local;
          if (id) {
            result.push(space + "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") && parse && extra.raw) {
            try {
              raw = parse(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 = join(result, fragment);
                } else {
                  result.push(fragment);
                }
              }
            });
          }
          if (expr.filter) {
            result = join(result, "if" + space);
            fragment = this.generateExpression(expr.filter, Precedence.Sequence, E_TTT);
            result = join(result, ["(", fragment, ")"]);
          }
          if (!extra.moz.comprehensionExpressionStartsWithAssignment) {
            fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT);
            result = join(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 = join(fragment, expr.of ? "of" : "in");
          fragment = join(fragment, this.generateExpression(expr.right, Precedence.Sequence, E_TTT));
          return ["for" + space + "(", 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("${" + space);
              result.push(this.generateExpression(expr.expressions[i], Precedence.Sequence, E_TTT));
              result.push(space + "}");
            }
          }
          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 && newline === "" && 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 defaultOptions = getDefaultOptions(), result, pair;
        if (options != null) {
          if (typeof options.indent === "string") {
            defaultOptions.format.indent.style = options.indent;
          }
          if (typeof options.base === "number") {
            defaultOptions.format.indent.base = options.base;
          }
          options = updateDeeply(defaultOptions, options);
          indent = options.format.indent.style;
          if (typeof options.base === "string") {
            base = options.base;
          } else {
            base = stringRepeat(indent, options.format.indent.base);
          }
        } else {
          options = defaultOptions;
          indent = options.format.indent.style;
          base = 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;
        newline = options.format.newline;
        space = options.format.space;
        if (options.format.compact) {
          newline = space = indent = base = "";
        }
        parentheses = options.format.parentheses;
        semicolons = options.format.semicolons;
        safeConcatenation = options.format.safeConcatenation;
        directive = options.directive;
        parse = 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/esprima/dist/esprima.js
var require_esprima = __commonJS({
  "node_modules/esprima/dist/esprima.js"(exports2, module2) {
    init_prefix();
    (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 parse(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 parser2;
              if (options && typeof options.jsx === "boolean" && options.jsx) {
                parser2 = new jsx_parser_1.JSXParser(code, options, parserDelegate);
              } else {
                parser2 = new parser_1.Parser(code, options, parserDelegate);
              }
              var program = isModule ? parser2.parseModule() : parser2.parseScript();
              var ast = program;
              if (collectComment && commentHandler) {
                ast.comments = commentHandler.comments;
              }
              if (parser2.config.tokens) {
                ast.tokens = parser2.tokens;
              }
              if (parser2.config.tolerant) {
                ast.errors = parser2.errorHandler.errors;
              }
              return ast;
            }
            exports3.parse = parse;
            function parseModule(code, options, delegate) {
              var parsingOptions = options || {};
              parsingOptions.sourceType = "module";
              return parse(code, parsingOptions, delegate);
            }
            exports3.parseModule = parseModule;
            function parseScript(code, options, delegate) {
              var parsingOptions = options || {};
              parsingOptions.sourceType = "script";
              return parse(code, parsingOptions, delegate);
            }
            exports3.parseScript = parseScript;
            function tokenize(code, options, delegate) {
              var tokenizer = new tokenizer_1.Tokenizer(code, options);
              var tokens;
              tokens = [];
              try {
                while (true) {
                  var token = tokenizer.getNextToken();
                  if (!token) {
                    break;
                  }
                  if (delegate) {
                    token = delegate(token);
                  }
                  tokens.push(token);
                }
              } catch (e) {
                tokenizer.errorHandler.tolerate(e);
              }
              if (tokenizer.errorHandler.tolerant) {
                tokens.errors = tokenizer.errors();
              }
              return tokens;
            }
            exports3.tokenize = tokenize;
            var syntax_1 = __webpack_require__(2);
            exports3.Syntax = syntax_1.Syntax;
            exports3.version = "4.0.1";
          },
          /* 1 */
          /***/
          function(module3, exports3, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var syntax_1 = __webpack_require__(2);
            var CommentHandler = (function() {
              function CommentHandler2() {
                this.attach = false;
                this.comments = [];
                this.stack = [];
                this.leading = [];
                this.trailing = [];
              }
              CommentHandler2.prototype.insertInnerComments = function(node, metadata) {
                if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) {
                  var innerComments = [];
                  for (var i = this.leading.length - 1; i >= 0; --i) {
                    var entry = this.leading[i];
                    if (metadata.end.offset >= entry.start) {
                      innerComments.unshift(entry.comment);
                      this.leading.splice(i, 1);
                      this.trailing.splice(i, 1);
                    }
                  }
                  if (innerComments.length) {
                    node.innerComments = innerComments;
                  }
                }
              };
              CommentHandler2.prototype.findTrailingComments = function(metadata) {
                var trailingComments = [];
                if (this.trailing.length > 0) {
                  for (var i = this.trailing.length - 1; i >= 0; --i) {
                    var entry_1 = this.trailing[i];
                    if (entry_1.start >= metadata.end.offset) {
                      trailingComments.unshift(entry_1.comment);
                    }
                  }
                  this.trailing.length = 0;
                  return trailingComments;
                }
                var entry = this.stack[this.stack.length - 1];
                if (entry && entry.node.trailingComments) {
                  var firstComment = entry.node.trailingComments[0];
                  if (firstComment && firstComment.range[0] >= metadata.end.offset) {
                    trailingComments = entry.node.trailingComments;
                    delete entry.node.trailingComments;
                  }
                }
                return trailingComments;
              };
              CommentHandler2.prototype.findLeadingComments = function(metadata) {
                var leadingComments = [];
                var target;
                while (this.stack.length > 0) {
                  var entry = this.stack[this.stack.length - 1];
                  if (entry && entry.start >= metadata.start.offset) {
                    target = entry.node;
                    this.stack.pop();
                  } else {
                    break;
                  }
                }
                if (target) {
                  var count = target.leadingComments ? target.leadingComments.length : 0;
                  for (var i = count - 1; i >= 0; --i) {
                    var comment = target.leadingComments[i];
                    if (comment.range[1] <= metadata.start.offset) {
                      leadingComments.unshift(comment);
                      target.leadingComments.splice(i, 1);
                    }
                  }
                  if (target.leadingComments && target.leadingComments.length === 0) {
                    delete target.leadingComments;
                  }
                  return leadingComments;
                }
                for (var i = this.leading.length - 1; i >= 0; --i) {
                  var entry = this.leading[i];
                  if (entry.start <= metadata.start.offset) {
                    leadingComments.unshift(entry.comment);
                    this.leading.splice(i, 1);
                  }
                }
                return leadingComments;
              };
              CommentHandler2.prototype.visitNode = function(node, metadata) {
                if (node.type === syntax_1.Syntax.Program && node.body.length > 0) {
                  return;
                }
                this.insertInnerComments(node, metadata);
                var trailingComments = this.findTrailingComments(metadata);
                var leadingComments = this.findLeadingComments(metadata);
                if (leadingComments.length > 0) {
                  node.leadingComments = leadingComments;
                }
                if (trailingComments.length > 0) {
                  node.trailingComments = trailingComments;
                }
                this.stack.push({
                  node,
                  start: metadata.start.offset
                });
              };
              CommentHandler2.prototype.visitComment = function(node, metadata) {
                var type = node.type[0] === "L" ? "Line" : "Block";
                var comment = {
                  type,
                  value: node.value
                };
                if (node.range) {
                  comment.range = node.range;
                }
                if (node.loc) {
                  comment.loc = node.loc;
                }
                this.comments.push(comment);
                if (this.attach) {
                  var entry = {
                    comment: {
                      type,
                      value: node.value,
                      range: [metadata.start.offset, metadata.end.offset]
                    },
                    start: metadata.start.offset
                  };
                  if (node.loc) {
                    entry.comment.loc = node.loc;
                  }
                  node.type = type;
                  this.leading.push(entry);
                  this.trailing.push(entry);
                }
              };
              CommentHandler2.prototype.visit = function(node, metadata) {
                if (node.type === "LineComment") {
                  this.visitComment(node, metadata);
                } else if (node.type === "BlockComment") {
                  this.visitComment(node, metadata);
                } else if (this.attach) {
                  this.visitNode(node, metadata);
                }
              };
              return CommentHandler2;
            })();
            exports3.CommentHandler = CommentHandler;
          },
          /* 2 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            exports3.Syntax = {
              AssignmentExpression: "AssignmentExpression",
              AssignmentPattern: "AssignmentPattern",
              ArrayExpression: "ArrayExpression",
              ArrayPattern: "ArrayPattern",
              ArrowFunctionExpression: "ArrowFunctionExpression",
              AwaitExpression: "AwaitExpression",
              BlockStatement: "BlockStatement",
              BinaryExpression: "BinaryExpression",
              BreakStatement: "BreakStatement",
              CallExpression: "CallExpression",
              CatchClause: "CatchClause",
              ClassBody: "ClassBody",
              ClassDeclaration: "ClassDeclaration",
              ClassExpression: "ClassExpression",
              ConditionalExpression: "ConditionalExpression",
              ContinueStatement: "ContinueStatement",
              DoWhileStatement: "DoWhileStatement",
              DebuggerStatement: "DebuggerStatement",
              EmptyStatement: "EmptyStatement",
              ExportAllDeclaration: "ExportAllDeclaration",
              ExportDefaultDeclaration: "ExportDefaultDeclaration",
              ExportNamedDeclaration: "ExportNamedDeclaration",
              ExportSpecifier: "ExportSpecifier",
              ExpressionStatement: "ExpressionStatement",
              ForStatement: "ForStatement",
              ForOfStatement: "ForOfStatement",
              ForInStatement: "ForInStatement",
              FunctionDeclaration: "FunctionDeclaration",
              FunctionExpression: "FunctionExpression",
              Identifier: "Identifier",
              IfStatement: "IfStatement",
              ImportDeclaration: "ImportDeclaration",
              ImportDefaultSpecifier: "ImportDefaultSpecifier",
              ImportNamespaceSpecifier: "ImportNamespaceSpecifier",
              ImportSpecifier: "ImportSpecifier",
              Literal: "Literal",
              LabeledStatement: "LabeledStatement",
              LogicalExpression: "LogicalExpression",
              MemberExpression: "MemberExpression",
              MetaProperty: "MetaProperty",
              MethodDefinition: "MethodDefinition",
              NewExpression: "NewExpression",
              ObjectExpression: "ObjectExpression",
              ObjectPattern: "ObjectPattern",
              Program: "Program",
              Property: "Property",
              RestElement: "RestElement",
              ReturnStatement: "ReturnStatement",
              SequenceExpression: "SequenceExpression",
              SpreadElement: "SpreadElement",
              Super: "Super",
              SwitchCase: "SwitchCase",
              SwitchStatement: "SwitchStatement",
              TaggedTemplateExpression: "TaggedTemplateExpression",
              TemplateElement: "TemplateElement",
              TemplateLiteral: "TemplateLiteral",
              ThisExpression: "ThisExpression",
              ThrowStatement: "ThrowStatement",
              TryStatement: "TryStatement",
              UnaryExpression: "UnaryExpression",
              UpdateExpression: "UpdateExpression",
              VariableDeclaration: "VariableDeclaration",
              VariableDeclarator: "VariableDeclarator",
              WhileStatement: "WhileStatement",
              WithStatement: "WithStatement",
              YieldExpression: "YieldExpression"
            };
          },
          /* 3 */
          /***/
          function(module3, exports3, __webpack_require__) {
            "use strict";
            var __extends2 = this && this.__extends || (function() {
              var extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d, b) {
                d.__proto__ = b;
              } || function(d, b) {
                for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
              };
              return function(d, b) {
                extendStatics2(d, b);
                function __() {
                  this.constructor = d;
                }
                d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
              };
            })();
            Object.defineProperty(exports3, "__esModule", { value: true });
            var character_1 = __webpack_require__(4);
            var JSXNode = __webpack_require__(5);
            var jsx_syntax_1 = __webpack_require__(6);
            var Node2 = __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 Node2.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, left2, right2) {
                this.type = syntax_1.Syntax.AssignmentExpression;
                this.operator = operator;
                this.left = left2;
                this.right = right2;
              }
              return AssignmentExpression2;
            })();
            exports3.AssignmentExpression = AssignmentExpression;
            var AssignmentPattern = /* @__PURE__ */ (function() {
              function AssignmentPattern2(left2, right2) {
                this.type = syntax_1.Syntax.AssignmentPattern;
                this.left = left2;
                this.right = right2;
              }
              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, left2, right2) {
                var logical = operator === "||" || operator === "&&";
                this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression;
                this.operator = operator;
                this.left = left2;
                this.right = right2;
              }
              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, args2) {
                this.type = syntax_1.Syntax.CallExpression;
                this.callee = callee;
                this.arguments = args2;
              }
              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(left2, right2, body) {
                this.type = syntax_1.Syntax.ForInStatement;
                this.left = left2;
                this.right = right2;
                this.body = body;
                this.each = false;
              }
              return ForInStatement2;
            })();
            exports3.ForInStatement = ForInStatement;
            var ForOfStatement = /* @__PURE__ */ (function() {
              function ForOfStatement2(left2, right2, body) {
                this.type = syntax_1.Syntax.ForOfStatement;
                this.left = left2;
                this.right = right2;
                this.body = body;
              }
              return ForOfStatement2;
            })();
            exports3.ForOfStatement = ForOfStatement;
            var ForStatement = /* @__PURE__ */ (function() {
              function ForStatement2(init, test, update, body) {
                this.type = syntax_1.Syntax.ForStatement;
                this.init = init;
                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, args2) {
                this.type = syntax_1.Syntax.NewExpression;
                this.callee = callee;
                this.arguments = args2;
              }
              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, init) {
                this.type = syntax_1.Syntax.VariableDeclarator;
                this.id = id;
                this.init = init;
              }
              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 Node2 = __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 Parser2 = (function() {
              function Parser3(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
                };
              }
              Parser3.prototype.throwError = function(messageFormat) {
                var values = [];
                for (var _i = 1; _i < arguments.length; _i++) {
                  values[_i - 1] = arguments[_i];
                }
                var args2 = Array.prototype.slice.call(arguments, 1);
                var msg = messageFormat.replace(/%(\d)/g, function(whole, idx) {
                  assert_1.assert(idx < args2.length, "Message reference must be in range");
                  return args2[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);
              };
              Parser3.prototype.tolerateError = function(messageFormat) {
                var values = [];
                for (var _i = 1; _i < arguments.length; _i++) {
                  values[_i - 1] = arguments[_i];
                }
                var args2 = Array.prototype.slice.call(arguments, 1);
                var msg = messageFormat.replace(/%(\d)/g, function(whole, idx) {
                  assert_1.assert(idx < args2.length, "Message reference must be in range");
                  return args2[idx];
                });
                var index = this.lastMarker.index;
                var line = this.scanner.lineNumber;
                var column = this.lastMarker.column + 1;
                this.errorHandler.tolerateError(index, line, column, msg);
              };
              Parser3.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);
                }
              };
              Parser3.prototype.throwUnexpectedToken = function(token, message) {
                throw this.unexpectedTokenError(token, message);
              };
              Parser3.prototype.tolerateUnexpectedToken = function(token, message) {
                this.errorHandler.tolerate(this.unexpectedTokenError(token, message));
              };
              Parser3.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);
                    }
                  }
                }
              };
              Parser3.prototype.getTokenRaw = function(token) {
                return this.scanner.source.slice(token.start, token.end);
              };
              Parser3.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;
              };
              Parser3.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;
              };
              Parser3.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;
              };
              Parser3.prototype.createNode = function() {
                return {
                  index: this.startMarker.index,
                  line: this.startMarker.line,
                  column: this.startMarker.column
                };
              };
              Parser3.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
                };
              };
              Parser3.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;
              };
              Parser3.prototype.expect = function(value) {
                var token = this.nextToken();
                if (token.type !== 7 || token.value !== value) {
                  this.throwUnexpectedToken(token);
                }
              };
              Parser3.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(",");
                }
              };
              Parser3.prototype.expectKeyword = function(keyword) {
                var token = this.nextToken();
                if (token.type !== 4 || token.value !== keyword) {
                  this.throwUnexpectedToken(token);
                }
              };
              Parser3.prototype.match = function(value) {
                return this.lookahead.type === 7 && this.lookahead.value === value;
              };
              Parser3.prototype.matchKeyword = function(keyword) {
                return this.lookahead.type === 4 && this.lookahead.value === keyword;
              };
              Parser3.prototype.matchContextualKeyword = function(keyword) {
                return this.lookahead.type === 3 && this.lookahead.value === keyword;
              };
              Parser3.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 === "|=";
              };
              Parser3.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;
              };
              Parser3.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;
              };
              Parser3.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;
                }
              };
              Parser3.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 Node2.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 Node2.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 Node2.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 Node2.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 Node2.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 Node2.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 Node2.ThisExpression());
                      } else if (this.matchKeyword("class")) {
                        expr = this.parseClassExpression();
                      } else {
                        expr = this.throwUnexpectedToken(this.nextToken());
                      }
                    }
                    break;
                  default:
                    expr = this.throwUnexpectedToken(this.nextToken());
                }
                return expr;
              };
              Parser3.prototype.parseSpreadElement = function() {
                var node = this.createNode();
                this.expect("...");
                var arg = this.inheritCoverGrammar(this.parseAssignmentExpression);
                return this.finalize(node, new Node2.SpreadElement(arg));
              };
              Parser3.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 Node2.ArrayExpression(elements));
              };
              Parser3.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;
              };
              Parser3.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 Node2.FunctionExpression(null, params.params, method, isGenerator));
              };
              Parser3.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 Node2.AsyncFunctionExpression(null, params.params, method));
              };
              Parser3.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 Node2.Literal(token.value, raw));
                    break;
                  case 3:
                  case 1:
                  case 5:
                  case 4:
                    key = this.finalize(node, new Node2.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;
              };
              Parser3.prototype.isPropertyKey = function(key, value) {
                return key.type === syntax_1.Syntax.Identifier && key.name === value || key.type === syntax_1.Syntax.Literal && key.value === value;
              };
              Parser3.prototype.parseObjectProperty = function(hasProto) {
                var node = this.createNode();
                var token = this.lookahead;
                var kind;
                var key = null;
                var value = null;
                var computed = false;
                var method = false;
                var shorthand = false;
                var isAsync = false;
                if (token.type === 3) {
                  var id = token.value;
                  this.nextToken();
                  computed = this.match("[");
                  isAsync = !this.hasLineTerminator && id === "async" && !this.match(":") && !this.match("(") && !this.match("*") && !this.match(",");
                  key = isAsync ? this.parseObjectPropertyKey() : this.finalize(node, new Node2.Identifier(id));
                } else if (this.match("*")) {
                  this.nextToken();
                } else {
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                }
                var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
                if (token.type === 3 && !isAsync && token.value === "get" && lookaheadPropertyKey) {
                  kind = "get";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  this.context.allowYield = false;
                  value = this.parseGetterMethod();
                } else if (token.type === 3 && !isAsync && token.value === "set" && lookaheadPropertyKey) {
                  kind = "set";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  value = this.parseSetterMethod();
                } else if (token.type === 7 && token.value === "*" && lookaheadPropertyKey) {
                  kind = "init";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  value = this.parseGeneratorMethod();
                  method = true;
                } else {
                  if (!key) {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                  kind = "init";
                  if (this.match(":") && !isAsync) {
                    if (!computed && this.isPropertyKey(key, "__proto__")) {
                      if (hasProto.value) {
                        this.tolerateError(messages_1.Messages.DuplicateProtoProperty);
                      }
                      hasProto.value = true;
                    }
                    this.nextToken();
                    value = this.inheritCoverGrammar(this.parseAssignmentExpression);
                  } else if (this.match("(")) {
                    value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
                    method = true;
                  } else if (token.type === 3) {
                    var id = this.finalize(node, new Node2.Identifier(token.value));
                    if (this.match("=")) {
                      this.context.firstCoverInitializedNameError = this.lookahead;
                      this.nextToken();
                      shorthand = true;
                      var init = this.isolateCoverGrammar(this.parseAssignmentExpression);
                      value = this.finalize(node, new Node2.AssignmentPattern(id, init));
                    } else {
                      shorthand = true;
                      value = id;
                    }
                  } else {
                    this.throwUnexpectedToken(this.nextToken());
                  }
                }
                return this.finalize(node, new Node2.Property(kind, key, computed, value, method, shorthand));
              };
              Parser3.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 Node2.ObjectExpression(properties));
              };
              Parser3.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 Node2.TemplateElement({ raw, cooked }, token.tail));
              };
              Parser3.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 Node2.TemplateElement({ raw, cooked }, token.tail));
              };
              Parser3.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 Node2.TemplateLiteral(quasis, expressions));
              };
              Parser3.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;
                }
              };
              Parser3.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 Node2.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;
              };
              Parser3.prototype.parseArguments = function() {
                this.expect("(");
                var args2 = [];
                if (!this.match(")")) {
                  while (true) {
                    var expr = this.match("...") ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAssignmentExpression);
                    args2.push(expr);
                    if (this.match(")")) {
                      break;
                    }
                    this.expectCommaSeparator();
                    if (this.match(")")) {
                      break;
                    }
                  }
                }
                this.expect(")");
                return args2;
              };
              Parser3.prototype.isIdentifierName = function(token) {
                return token.type === 3 || token.type === 4 || token.type === 1 || token.type === 5;
              };
              Parser3.prototype.parseIdentifierName = function() {
                var node = this.createNode();
                var token = this.nextToken();
                if (!this.isIdentifierName(token)) {
                  this.throwUnexpectedToken(token);
                }
                return this.finalize(node, new Node2.Identifier(token.value));
              };
              Parser3.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 Node2.MetaProperty(id, property);
                  } else {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                } else {
                  var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression);
                  var args2 = this.match("(") ? this.parseArguments() : [];
                  expr = new Node2.NewExpression(callee, args2);
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                }
                return this.finalize(node, expr);
              };
              Parser3.prototype.parseAsyncArgument = function() {
                var arg = this.parseAssignmentExpression();
                this.context.firstCoverInitializedNameError = null;
                return arg;
              };
              Parser3.prototype.parseAsyncArguments = function() {
                this.expect("(");
                var args2 = [];
                if (!this.match(")")) {
                  while (true) {
                    var expr = this.match("...") ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAsyncArgument);
                    args2.push(expr);
                    if (this.match(")")) {
                      break;
                    }
                    this.expectCommaSeparator();
                    if (this.match(")")) {
                      break;
                    }
                  }
                }
                this.expect(")");
                return args2;
              };
              Parser3.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 Node2.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 Node2.StaticMemberExpression(expr, property));
                  } else if (this.match("(")) {
                    var asyncArrow = maybeAsync && startToken.lineNumber === this.lookahead.lineNumber;
                    this.context.isBindingElement = false;
                    this.context.isAssignmentTarget = false;
                    var args2 = asyncArrow ? this.parseAsyncArguments() : this.parseArguments();
                    expr = this.finalize(this.startNode(startToken), new Node2.CallExpression(expr, args2));
                    if (asyncArrow && this.match("=>")) {
                      for (var i = 0; i < args2.length; ++i) {
                        this.reinterpretExpressionAsPattern(args2[i]);
                      }
                      expr = {
                        type: ArrowParameterPlaceHolder,
                        params: args2,
                        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 Node2.ComputedMemberExpression(expr, property));
                  } else if (this.lookahead.type === 10 && this.lookahead.head) {
                    var quasi = this.parseTemplateLiteral();
                    expr = this.finalize(this.startNode(startToken), new Node2.TaggedTemplateExpression(expr, quasi));
                  } else {
                    break;
                  }
                }
                this.context.allowIn = previousAllowIn;
                return expr;
              };
              Parser3.prototype.parseSuper = function() {
                var node = this.createNode();
                this.expectKeyword("super");
                if (!this.match("[") && !this.match(".")) {
                  this.throwUnexpectedToken(this.lookahead);
                }
                return this.finalize(node, new Node2.Super());
              };
              Parser3.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 Node2.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 Node2.StaticMemberExpression(expr, property));
                  } else if (this.lookahead.type === 10 && this.lookahead.head) {
                    var quasi = this.parseTemplateLiteral();
                    expr = this.finalize(node, new Node2.TaggedTemplateExpression(expr, quasi));
                  } else {
                    break;
                  }
                }
                return expr;
              };
              Parser3.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 Node2.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 Node2.UpdateExpression(operator, expr, prefix));
                    }
                  }
                }
                return expr;
              };
              Parser3.prototype.parseAwaitExpression = function() {
                var node = this.createNode();
                this.nextToken();
                var argument = this.parseUnaryExpression();
                return this.finalize(node, new Node2.AwaitExpression(argument));
              };
              Parser3.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 Node2.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;
              };
              Parser3.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 left2 = expr;
                  var right2 = this.isolateCoverGrammar(this.parseExponentiationExpression);
                  expr = this.finalize(this.startNode(startToken), new Node2.BinaryExpression("**", left2, right2));
                }
                return expr;
              };
              Parser3.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;
              };
              Parser3.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 left2 = expr;
                  var right2 = this.isolateCoverGrammar(this.parseExponentiationExpression);
                  var stack = [left2, token.value, right2];
                  var precedences = [prec];
                  while (true) {
                    prec = this.binaryPrecedence(this.lookahead);
                    if (prec <= 0) {
                      break;
                    }
                    while (stack.length > 2 && prec <= precedences[precedences.length - 1]) {
                      right2 = stack.pop();
                      var operator = stack.pop();
                      precedences.pop();
                      left2 = stack.pop();
                      markers.pop();
                      var node = this.startNode(markers[markers.length - 1]);
                      stack.push(this.finalize(node, new Node2.BinaryExpression(operator, left2, right2)));
                    }
                    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 Node2.BinaryExpression(operator, stack[i - 2], expr));
                    i -= 2;
                    lastMarker = marker;
                  }
                }
                return expr;
              };
              Parser3.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 Node2.ConditionalExpression(expr, consequent, alternate));
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                }
                return expr;
              };
              Parser3.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 Node2.Identifier;
              };
              Parser3.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
                };
              };
              Parser3.prototype.parseAssignmentExpression = function() {
                var expr;
                if (!this.context.allowYield && this.matchKeyword("yield")) {
                  expr = this.parseYieldExpression();
                } else {
                  var startToken = this.lookahead;
                  var token = startToken;
                  expr = this.parseConditionalExpression();
                  if (token.type === 3 && token.lineNumber === this.lookahead.lineNumber && token.value === "async") {
                    if (this.lookahead.type === 3 || this.matchKeyword("yield")) {
                      var arg = this.parsePrimaryExpression();
                      this.reinterpretExpressionAsPattern(arg);
                      expr = {
                        type: ArrowParameterPlaceHolder,
                        params: [arg],
                        async: true
                      };
                    }
                  }
                  if (expr.type === ArrowParameterPlaceHolder || this.match("=>")) {
                    this.context.isAssignmentTarget = false;
                    this.context.isBindingElement = false;
                    var isAsync = expr.async;
                    var list = this.reinterpretAsCoverFormalsList(expr);
                    if (list) {
                      if (this.hasLineTerminator) {
                        this.tolerateUnexpectedToken(this.lookahead);
                      }
                      this.context.firstCoverInitializedNameError = null;
                      var previousStrict = this.context.strict;
                      var previousAllowStrictDirective = this.context.allowStrictDirective;
                      this.context.allowStrictDirective = list.simple;
                      var previousAllowYield = this.context.allowYield;
                      var previousAwait = this.context.await;
                      this.context.allowYield = true;
                      this.context.await = isAsync;
                      var node = this.startNode(startToken);
                      this.expect("=>");
                      var body = void 0;
                      if (this.match("{")) {
                        var previousAllowIn = this.context.allowIn;
                        this.context.allowIn = true;
                        body = this.parseFunctionSourceElements();
                        this.context.allowIn = previousAllowIn;
                      } else {
                        body = this.isolateCoverGrammar(this.parseAssignmentExpression);
                      }
                      var expression = body.type !== syntax_1.Syntax.BlockStatement;
                      if (this.context.strict && list.firstRestricted) {
                        this.throwUnexpectedToken(list.firstRestricted, list.message);
                      }
                      if (this.context.strict && list.stricted) {
                        this.tolerateUnexpectedToken(list.stricted, list.message);
                      }
                      expr = isAsync ? this.finalize(node, new Node2.AsyncArrowFunctionExpression(list.params, body, expression)) : this.finalize(node, new Node2.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 right2 = this.isolateCoverGrammar(this.parseAssignmentExpression);
                      expr = this.finalize(this.startNode(startToken), new Node2.AssignmentExpression(operator, expr, right2));
                      this.context.firstCoverInitializedNameError = null;
                    }
                  }
                }
                return expr;
              };
              Parser3.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 Node2.SequenceExpression(expressions));
                }
                return expr;
              };
              Parser3.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;
              };
              Parser3.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 Node2.BlockStatement(block));
              };
              Parser3.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 init = null;
                if (kind === "const") {
                  if (!this.matchKeyword("in") && !this.matchContextualKeyword("of")) {
                    if (this.match("=")) {
                      this.nextToken();
                      init = 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("=");
                  init = this.isolateCoverGrammar(this.parseAssignmentExpression);
                }
                return this.finalize(node, new Node2.VariableDeclarator(id, init));
              };
              Parser3.prototype.parseBindingList = function(kind, options) {
                var list = [this.parseLexicalBinding(kind, options)];
                while (this.match(",")) {
                  this.nextToken();
                  list.push(this.parseLexicalBinding(kind, options));
                }
                return list;
              };
              Parser3.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";
              };
              Parser3.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 Node2.VariableDeclaration(declarations, kind));
              };
              Parser3.prototype.parseBindingRestElement = function(params, kind) {
                var node = this.createNode();
                this.expect("...");
                var arg = this.parsePattern(params, kind);
                return this.finalize(node, new Node2.RestElement(arg));
              };
              Parser3.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 Node2.ArrayPattern(elements));
              };
              Parser3.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 init = this.finalize(node, new Node2.Identifier(keyToken.value));
                  if (this.match("=")) {
                    params.push(keyToken);
                    shorthand = true;
                    this.nextToken();
                    var expr = this.parseAssignmentExpression();
                    value = this.finalize(this.startNode(keyToken), new Node2.AssignmentPattern(init, expr));
                  } else if (!this.match(":")) {
                    params.push(keyToken);
                    shorthand = true;
                    value = init;
                  } 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 Node2.Property("init", key, computed, value, method, shorthand));
              };
              Parser3.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 Node2.ObjectPattern(properties));
              };
              Parser3.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;
              };
              Parser3.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 right2 = this.isolateCoverGrammar(this.parseAssignmentExpression);
                  this.context.allowYield = previousAllowYield;
                  pattern = this.finalize(this.startNode(startToken), new Node2.AssignmentPattern(pattern, right2));
                }
                return pattern;
              };
              Parser3.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 Node2.Identifier(token.value));
              };
              Parser3.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 init = null;
                if (this.match("=")) {
                  this.nextToken();
                  init = this.isolateCoverGrammar(this.parseAssignmentExpression);
                } else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) {
                  this.expect("=");
                }
                return this.finalize(node, new Node2.VariableDeclarator(id, init));
              };
              Parser3.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;
              };
              Parser3.prototype.parseVariableStatement = function() {
                var node = this.createNode();
                this.expectKeyword("var");
                var declarations = this.parseVariableDeclarationList({ inFor: false });
                this.consumeSemicolon();
                return this.finalize(node, new Node2.VariableDeclaration(declarations, "var"));
              };
              Parser3.prototype.parseEmptyStatement = function() {
                var node = this.createNode();
                this.expect(";");
                return this.finalize(node, new Node2.EmptyStatement());
              };
              Parser3.prototype.parseExpressionStatement = function() {
                var node = this.createNode();
                var expr = this.parseExpression();
                this.consumeSemicolon();
                return this.finalize(node, new Node2.ExpressionStatement(expr));
              };
              Parser3.prototype.parseIfClause = function() {
                if (this.context.strict && this.matchKeyword("function")) {
                  this.tolerateError(messages_1.Messages.StrictFunction);
                }
                return this.parseStatement();
              };
              Parser3.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 Node2.EmptyStatement());
                } else {
                  this.expect(")");
                  consequent = this.parseIfClause();
                  if (this.matchKeyword("else")) {
                    this.nextToken();
                    alternate = this.parseIfClause();
                  }
                }
                return this.finalize(node, new Node2.IfStatement(test, consequent, alternate));
              };
              Parser3.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 Node2.DoWhileStatement(body, test));
              };
              Parser3.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 Node2.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 Node2.WhileStatement(test, body));
              };
              Parser3.prototype.parseForStatement = function() {
                var init = null;
                var test = null;
                var update = null;
                var forIn = true;
                var left2, right2;
                var node = this.createNode();
                this.expectKeyword("for");
                this.expect("(");
                if (this.match(";")) {
                  this.nextToken();
                } else {
                  if (this.matchKeyword("var")) {
                    init = 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");
                      }
                      init = this.finalize(init, new Node2.VariableDeclaration(declarations, "var"));
                      this.nextToken();
                      left2 = init;
                      right2 = this.parseExpression();
                      init = null;
                    } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword("of")) {
                      init = this.finalize(init, new Node2.VariableDeclaration(declarations, "var"));
                      this.nextToken();
                      left2 = init;
                      right2 = this.parseAssignmentExpression();
                      init = null;
                      forIn = false;
                    } else {
                      init = this.finalize(init, new Node2.VariableDeclaration(declarations, "var"));
                      this.expect(";");
                    }
                  } else if (this.matchKeyword("const") || this.matchKeyword("let")) {
                    init = this.createNode();
                    var kind = this.nextToken().value;
                    if (!this.context.strict && this.lookahead.value === "in") {
                      init = this.finalize(init, new Node2.Identifier(kind));
                      this.nextToken();
                      left2 = init;
                      right2 = this.parseExpression();
                      init = 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")) {
                        init = this.finalize(init, new Node2.VariableDeclaration(declarations, kind));
                        this.nextToken();
                        left2 = init;
                        right2 = this.parseExpression();
                        init = null;
                      } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword("of")) {
                        init = this.finalize(init, new Node2.VariableDeclaration(declarations, kind));
                        this.nextToken();
                        left2 = init;
                        right2 = this.parseAssignmentExpression();
                        init = null;
                        forIn = false;
                      } else {
                        this.consumeSemicolon();
                        init = this.finalize(init, new Node2.VariableDeclaration(declarations, kind));
                      }
                    }
                  } else {
                    var initStartToken = this.lookahead;
                    var previousAllowIn = this.context.allowIn;
                    this.context.allowIn = false;
                    init = this.inheritCoverGrammar(this.parseAssignmentExpression);
                    this.context.allowIn = previousAllowIn;
                    if (this.matchKeyword("in")) {
                      if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) {
                        this.tolerateError(messages_1.Messages.InvalidLHSInForIn);
                      }
                      this.nextToken();
                      this.reinterpretExpressionAsPattern(init);
                      left2 = init;
                      right2 = this.parseExpression();
                      init = null;
                    } else if (this.matchContextualKeyword("of")) {
                      if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) {
                        this.tolerateError(messages_1.Messages.InvalidLHSInForLoop);
                      }
                      this.nextToken();
                      this.reinterpretExpressionAsPattern(init);
                      left2 = init;
                      right2 = this.parseAssignmentExpression();
                      init = null;
                      forIn = false;
                    } else {
                      if (this.match(",")) {
                        var initSeq = [init];
                        while (this.match(",")) {
                          this.nextToken();
                          initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
                        }
                        init = this.finalize(this.startNode(initStartToken), new Node2.SequenceExpression(initSeq));
                      }
                      this.expect(";");
                    }
                  }
                }
                if (typeof left2 === "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 Node2.EmptyStatement());
                } else {
                  this.expect(")");
                  var previousInIteration = this.context.inIteration;
                  this.context.inIteration = true;
                  body = this.isolateCoverGrammar(this.parseStatement);
                  this.context.inIteration = previousInIteration;
                }
                return typeof left2 === "undefined" ? this.finalize(node, new Node2.ForStatement(init, test, update, body)) : forIn ? this.finalize(node, new Node2.ForInStatement(left2, right2, body)) : this.finalize(node, new Node2.ForOfStatement(left2, right2, body));
              };
              Parser3.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 Node2.ContinueStatement(label));
              };
              Parser3.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 Node2.BreakStatement(label));
              };
              Parser3.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 Node2.ReturnStatement(argument));
              };
              Parser3.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 Node2.EmptyStatement());
                } else {
                  this.expect(")");
                  body = this.parseStatement();
                }
                return this.finalize(node, new Node2.WithStatement(object, body));
              };
              Parser3.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 Node2.SwitchCase(test, consequent));
              };
              Parser3.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 Node2.SwitchStatement(discriminant, cases));
              };
              Parser3.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 Node2.LabeledStatement(id, body);
                } else {
                  this.consumeSemicolon();
                  statement = new Node2.ExpressionStatement(expr);
                }
                return this.finalize(node, statement);
              };
              Parser3.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 Node2.ThrowStatement(argument));
              };
              Parser3.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 Node2.CatchClause(param, body));
              };
              Parser3.prototype.parseFinallyClause = function() {
                this.expectKeyword("finally");
                return this.parseBlock();
              };
              Parser3.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 Node2.TryStatement(block, handler, finalizer));
              };
              Parser3.prototype.parseDebuggerStatement = function() {
                var node = this.createNode();
                this.expectKeyword("debugger");
                this.consumeSemicolon();
                return this.finalize(node, new Node2.DebuggerStatement());
              };
              Parser3.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;
              };
              Parser3.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 Node2.BlockStatement(body));
              };
              Parser3.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;
                }
              };
              Parser3.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 Node2.RestElement(arg));
              };
              Parser3.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 Node2.Identifier;
                options.params.push(param);
              };
              Parser3.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
                };
              };
              Parser3.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;
              };
              Parser3.prototype.parseFunctionDeclaration = function(identifierIsOptional) {
                var node = this.createNode();
                var isAsync = this.matchContextualKeyword("async");
                if (isAsync) {
                  this.nextToken();
                }
                this.expectKeyword("function");
                var isGenerator = isAsync ? false : this.match("*");
                if (isGenerator) {
                  this.nextToken();
                }
                var message;
                var id = null;
                var firstRestricted = null;
                if (!identifierIsOptional || !this.match("(")) {
                  var token = this.lookahead;
                  id = this.parseVariableIdentifier();
                  if (this.context.strict) {
                    if (this.scanner.isRestrictedWord(token.value)) {
                      this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName);
                    }
                  } else {
                    if (this.scanner.isRestrictedWord(token.value)) {
                      firstRestricted = token;
                      message = messages_1.Messages.StrictFunctionName;
                    } else if (this.scanner.isStrictModeReservedWord(token.value)) {
                      firstRestricted = token;
                      message = messages_1.Messages.StrictReservedWord;
                    }
                  }
                }
                var previousAllowAwait = this.context.await;
                var previousAllowYield = this.context.allowYield;
                this.context.await = isAsync;
                this.context.allowYield = !isGenerator;
                var formalParameters = this.parseFormalParameters(firstRestricted);
                var params = formalParameters.params;
                var stricted = formalParameters.stricted;
                firstRestricted = formalParameters.firstRestricted;
                if (formalParameters.message) {
                  message = formalParameters.message;
                }
                var previousStrict = this.context.strict;
                var previousAllowStrictDirective = this.context.allowStrictDirective;
                this.context.allowStrictDirective = formalParameters.simple;
                var body = this.parseFunctionSourceElements();
                if (this.context.strict && firstRestricted) {
                  this.throwUnexpectedToken(firstRestricted, message);
                }
                if (this.context.strict && stricted) {
                  this.tolerateUnexpectedToken(stricted, message);
                }
                this.context.strict = previousStrict;
                this.context.allowStrictDirective = previousAllowStrictDirective;
                this.context.await = previousAllowAwait;
                this.context.allowYield = previousAllowYield;
                return isAsync ? this.finalize(node, new Node2.AsyncFunctionDeclaration(id, params, body)) : this.finalize(node, new Node2.FunctionDeclaration(id, params, body, isGenerator));
              };
              Parser3.prototype.parseFunctionExpression = function() {
                var node = this.createNode();
                var isAsync = this.matchContextualKeyword("async");
                if (isAsync) {
                  this.nextToken();
                }
                this.expectKeyword("function");
                var isGenerator = isAsync ? false : this.match("*");
                if (isGenerator) {
                  this.nextToken();
                }
                var message;
                var id = null;
                var firstRestricted;
                var previousAllowAwait = this.context.await;
                var previousAllowYield = this.context.allowYield;
                this.context.await = isAsync;
                this.context.allowYield = !isGenerator;
                if (!this.match("(")) {
                  var token = this.lookahead;
                  id = !this.context.strict && !isGenerator && this.matchKeyword("yield") ? this.parseIdentifierName() : this.parseVariableIdentifier();
                  if (this.context.strict) {
                    if (this.scanner.isRestrictedWord(token.value)) {
                      this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName);
                    }
                  } else {
                    if (this.scanner.isRestrictedWord(token.value)) {
                      firstRestricted = token;
                      message = messages_1.Messages.StrictFunctionName;
                    } else if (this.scanner.isStrictModeReservedWord(token.value)) {
                      firstRestricted = token;
                      message = messages_1.Messages.StrictReservedWord;
                    }
                  }
                }
                var formalParameters = this.parseFormalParameters(firstRestricted);
                var params = formalParameters.params;
                var stricted = formalParameters.stricted;
                firstRestricted = formalParameters.firstRestricted;
                if (formalParameters.message) {
                  message = formalParameters.message;
                }
                var previousStrict = this.context.strict;
                var previousAllowStrictDirective = this.context.allowStrictDirective;
                this.context.allowStrictDirective = formalParameters.simple;
                var body = this.parseFunctionSourceElements();
                if (this.context.strict && firstRestricted) {
                  this.throwUnexpectedToken(firstRestricted, message);
                }
                if (this.context.strict && stricted) {
                  this.tolerateUnexpectedToken(stricted, message);
                }
                this.context.strict = previousStrict;
                this.context.allowStrictDirective = previousAllowStrictDirective;
                this.context.await = previousAllowAwait;
                this.context.allowYield = previousAllowYield;
                return isAsync ? this.finalize(node, new Node2.AsyncFunctionExpression(id, params, body)) : this.finalize(node, new Node2.FunctionExpression(id, params, body, isGenerator));
              };
              Parser3.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 Node2.Directive(expr, directive) : new Node2.ExpressionStatement(expr));
              };
              Parser3.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;
              };
              Parser3.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;
              };
              Parser3.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 Node2.FunctionExpression(null, formalParameters.params, method, isGenerator));
              };
              Parser3.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 Node2.RestElement) {
                  this.tolerateError(messages_1.Messages.BadSetterRestParameter);
                }
                var method = this.parsePropertyMethod(formalParameters);
                this.context.allowYield = previousAllowYield;
                return this.finalize(node, new Node2.FunctionExpression(null, formalParameters.params, method, isGenerator));
              };
              Parser3.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 Node2.FunctionExpression(null, params.params, method, isGenerator));
              };
              Parser3.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;
              };
              Parser3.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 Node2.YieldExpression(argument, delegate));
              };
              Parser3.prototype.parseClassElement = function(hasConstructor) {
                var token = this.lookahead;
                var node = this.createNode();
                var kind = "";
                var key = null;
                var value = null;
                var computed = false;
                var method = false;
                var isStatic = false;
                var isAsync = false;
                if (this.match("*")) {
                  this.nextToken();
                } else {
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  var id = key;
                  if (id.name === "static" && (this.qualifiedPropertyName(this.lookahead) || this.match("*"))) {
                    token = this.lookahead;
                    isStatic = true;
                    computed = this.match("[");
                    if (this.match("*")) {
                      this.nextToken();
                    } else {
                      key = this.parseObjectPropertyKey();
                    }
                  }
                  if (token.type === 3 && !this.hasLineTerminator && token.value === "async") {
                    var punctuator = this.lookahead.value;
                    if (punctuator !== ":" && punctuator !== "(" && punctuator !== "*") {
                      isAsync = true;
                      token = this.lookahead;
                      key = this.parseObjectPropertyKey();
                      if (token.type === 3 && token.value === "constructor") {
                        this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync);
                      }
                    }
                  }
                }
                var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
                if (token.type === 3) {
                  if (token.value === "get" && lookaheadPropertyKey) {
                    kind = "get";
                    computed = this.match("[");
                    key = this.parseObjectPropertyKey();
                    this.context.allowYield = false;
                    value = this.parseGetterMethod();
                  } else if (token.value === "set" && lookaheadPropertyKey) {
                    kind = "set";
                    computed = this.match("[");
                    key = this.parseObjectPropertyKey();
                    value = this.parseSetterMethod();
                  }
                } else if (token.type === 7 && token.value === "*" && lookaheadPropertyKey) {
                  kind = "init";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  value = this.parseGeneratorMethod();
                  method = true;
                }
                if (!kind && key && this.match("(")) {
                  kind = "init";
                  value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
                  method = true;
                }
                if (!kind) {
                  this.throwUnexpectedToken(this.lookahead);
                }
                if (kind === "init") {
                  kind = "method";
                }
                if (!computed) {
                  if (isStatic && this.isPropertyKey(key, "prototype")) {
                    this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype);
                  }
                  if (!isStatic && this.isPropertyKey(key, "constructor")) {
                    if (kind !== "method" || !method || value && value.generator) {
                      this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod);
                    }
                    if (hasConstructor.value) {
                      this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor);
                    } else {
                      hasConstructor.value = true;
                    }
                    kind = "constructor";
                  }
                }
                return this.finalize(node, new Node2.MethodDefinition(key, computed, value, kind, isStatic));
              };
              Parser3.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;
              };
              Parser3.prototype.parseClassBody = function() {
                var node = this.createNode();
                var elementList = this.parseClassElementList();
                return this.finalize(node, new Node2.ClassBody(elementList));
              };
              Parser3.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 Node2.ClassDeclaration(id, superClass, classBody));
              };
              Parser3.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 Node2.ClassExpression(id, superClass, classBody));
              };
              Parser3.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 Node2.Module(body));
              };
              Parser3.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 Node2.Script(body));
              };
              Parser3.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 Node2.Literal(token.value, raw));
              };
              Parser3.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 Node2.ImportSpecifier(local, imported));
              };
              Parser3.prototype.parseNamedImports = function() {
                this.expect("{");
                var specifiers = [];
                while (!this.match("}")) {
                  specifiers.push(this.parseImportSpecifier());
                  if (!this.match("}")) {
                    this.expect(",");
                  }
                }
                this.expect("}");
                return specifiers;
              };
              Parser3.prototype.parseImportDefaultSpecifier = function() {
                var node = this.createNode();
                var local = this.parseIdentifierName();
                return this.finalize(node, new Node2.ImportDefaultSpecifier(local));
              };
              Parser3.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 Node2.ImportNamespaceSpecifier(local));
              };
              Parser3.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 Node2.ImportDeclaration(specifiers, src));
              };
              Parser3.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 Node2.ExportSpecifier(local, exported));
              };
              Parser3.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 Node2.ExportDefaultDeclaration(declaration));
                  } else if (this.matchKeyword("class")) {
                    var declaration = this.parseClassDeclaration(true);
                    exportDeclaration = this.finalize(node, new Node2.ExportDefaultDeclaration(declaration));
                  } else if (this.matchContextualKeyword("async")) {
                    var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression();
                    exportDeclaration = this.finalize(node, new Node2.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 Node2.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 Node2.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 Node2.ExportNamedDeclaration(declaration, [], null));
                } else if (this.matchAsyncFunction()) {
                  var declaration = this.parseFunctionDeclaration();
                  exportDeclaration = this.finalize(node, new Node2.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 Node2.ExportNamedDeclaration(null, specifiers, source));
                }
                return exportDeclaration;
              };
              return Parser3;
            })();
            exports3.Parser = Parser2;
          },
          /* 9 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            function assert(condition, message) {
              if (!condition) {
                throw new Error("ASSERT: " + message);
              }
            }
            exports3.assert = assert;
          },
          /* 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 (base) {
                  if (Object.create && Object.defineProperty) {
                    error = Object.create(base);
                    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(offset) {
                var comments = [];
                var start, loc;
                if (this.trackComment) {
                  comments = [];
                  start = this.index - offset;
                  loc = {
                    start: {
                      line: this.lineNumber,
                      column: this.index - this.lineStart - offset
                    },
                    end: {}
                  };
                }
                while (!this.eof()) {
                  var ch = this.source.charCodeAt(this.index);
                  ++this.index;
                  if (character_1.Character.isLineTerminator(ch)) {
                    if (this.trackComment) {
                      loc.end = {
                        line: this.lineNumber,
                        column: this.index - this.lineStart - 1
                      };
                      var entry = {
                        multiLine: false,
                        slice: [start + offset, this.index - 1],
                        range: [start, this.index - 1],
                        loc
                      };
                      comments.push(entry);
                    }
                    if (ch === 13 && this.source.charCodeAt(this.index) === 10) {
                      ++this.index;
                    }
                    ++this.lineNumber;
                    this.lineStart = this.index;
                    return comments;
                  }
                }
                if (this.trackComment) {
                  loc.end = {
                    line: this.lineNumber,
                    column: this.index - this.lineStart
                  };
                  var entry = {
                    multiLine: false,
                    slice: [start + offset, this.index],
                    range: [start, this.index],
                    loc
                  };
                  comments.push(entry);
                }
                return comments;
              };
              Scanner2.prototype.skipMultiLineComment = function() {
                var comments = [];
                var start, loc;
                if (this.trackComment) {
                  comments = [];
                  start = this.index - 2;
                  loc = {
                    start: {
                      line: this.lineNumber,
                      column: this.index - this.lineStart - 2
                    },
                    end: {}
                  };
                }
                while (!this.eof()) {
                  var ch = this.source.charCodeAt(this.index);
                  if (character_1.Character.isLineTerminator(ch)) {
                    if (ch === 13 && this.source.charCodeAt(this.index + 1) === 10) {
                      ++this.index;
                    }
                    ++this.lineNumber;
                    ++this.index;
                    this.lineStart = this.index;
                  } else if (ch === 42) {
                    if (this.source.charCodeAt(this.index + 1) === 47) {
                      this.index += 2;
                      if (this.trackComment) {
                        loc.end = {
                          line: this.lineNumber,
                          column: this.index - this.lineStart
                        };
                        var entry = {
                          multiLine: true,
                          slice: [start + 2, this.index - 2],
                          range: [start, this.index],
                          loc
                        };
                        comments.push(entry);
                      }
                      return comments;
                    }
                    ++this.index;
                  } else {
                    ++this.index;
                  }
                }
                if (this.trackComment) {
                  loc.end = {
                    line: this.lineNumber,
                    column: this.index - this.lineStart
                  };
                  var entry = {
                    multiLine: true,
                    slice: [start + 2, this.index],
                    range: [start, this.index],
                    loc
                  };
                  comments.push(entry);
                }
                this.tolerateUnexpectedToken();
                return comments;
              };
              Scanner2.prototype.scanComments = function() {
                var comments;
                if (this.trackComment) {
                  comments = [];
                }
                var start = this.index === 0;
                while (!this.eof()) {
                  var ch = this.source.charCodeAt(this.index);
                  if (character_1.Character.isWhiteSpace(ch)) {
                    ++this.index;
                  } else if (character_1.Character.isLineTerminator(ch)) {
                    ++this.index;
                    if (ch === 13 && this.source.charCodeAt(this.index) === 10) {
                      ++this.index;
                    }
                    ++this.lineNumber;
                    this.lineStart = this.index;
                    start = true;
                  } else if (ch === 47) {
                    ch = this.source.charCodeAt(this.index + 1);
                    if (ch === 47) {
                      this.index += 2;
                      var comment = this.skipSingleLineComment(2);
                      if (this.trackComment) {
                        comments = comments.concat(comment);
                      }
                      start = true;
                    } else if (ch === 42) {
                      this.index += 2;
                      var comment = this.skipMultiLineComment();
                      if (this.trackComment) {
                        comments = comments.concat(comment);
                      }
                    } else {
                      break;
                    }
                  } else if (start && ch === 45) {
                    if (this.source.charCodeAt(this.index + 1) === 45 && this.source.charCodeAt(this.index + 2) === 62) {
                      this.index += 3;
                      var comment = this.skipSingleLineComment(3);
                      if (this.trackComment) {
                        comments = comments.concat(comment);
                      }
                    } else {
                      break;
                    }
                  } else if (ch === 60 && !this.isModule) {
                    if (this.source.slice(this.index + 1, this.index + 4) === "!--") {
                      this.index += 4;
                      var comment = this.skipSingleLineComment(4);
                      if (this.trackComment) {
                        comments = comments.concat(comment);
                      }
                    } else {
                      break;
                    }
                  } else {
                    break;
                  }
                }
                return comments;
              };
              Scanner2.prototype.isFutureReservedWord = function(id) {
                switch (id) {
                  case "enum":
                  case "export":
                  case "import":
                  case "super":
                    return true;
                  default:
                    return false;
                }
              };
              Scanner2.prototype.isStrictModeReservedWord = function(id) {
                switch (id) {
                  case "implements":
                  case "interface":
                  case "package":
                  case "private":
                  case "protected":
                  case "public":
                  case "static":
                  case "yield":
                  case "let":
                    return true;
                  default:
                    return false;
                }
              };
              Scanner2.prototype.isRestrictedWord = function(id) {
                return id === "eval" || id === "arguments";
              };
              Scanner2.prototype.isKeyword = function(id) {
                switch (id.length) {
                  case 2:
                    return id === "if" || id === "in" || id === "do";
                  case 3:
                    return id === "var" || id === "for" || id === "new" || id === "try" || id === "let";
                  case 4:
                    return id === "this" || id === "else" || id === "case" || id === "void" || id === "with" || id === "enum";
                  case 5:
                    return id === "while" || id === "break" || id === "catch" || id === "throw" || id === "const" || id === "yield" || id === "class" || id === "super";
                  case 6:
                    return id === "return" || id === "typeof" || id === "delete" || id === "switch" || id === "export" || id === "import";
                  case 7:
                    return id === "default" || id === "finally" || id === "extends";
                  case 8:
                    return id === "function" || id === "continue" || id === "debugger";
                  case 10:
                    return id === "instanceof";
                  default:
                    return false;
                }
              };
              Scanner2.prototype.codePointAt = function(i) {
                var cp = this.source.charCodeAt(i);
                if (cp >= 55296 && cp <= 56319) {
                  var second = this.source.charCodeAt(i + 1);
                  if (second >= 56320 && second <= 57343) {
                    var first = cp;
                    cp = (first - 55296) * 1024 + second - 56320 + 65536;
                  }
                }
                return cp;
              };
              Scanner2.prototype.scanHexEscape = function(prefix) {
                var len = prefix === "u" ? 4 : 2;
                var code = 0;
                for (var i = 0; i < len; ++i) {
                  if (!this.eof() && character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
                    code = code * 16 + hexValue(this.source[this.index++]);
                  } else {
                    return null;
                  }
                }
                return String.fromCharCode(code);
              };
              Scanner2.prototype.scanUnicodeCodePointEscape = function() {
                var ch = this.source[this.index];
                var code = 0;
                if (ch === "}") {
                  this.throwUnexpectedToken();
                }
                while (!this.eof()) {
                  ch = this.source[this.index++];
                  if (!character_1.Character.isHexDigit(ch.charCodeAt(0))) {
                    break;
                  }
                  code = code * 16 + hexValue(ch);
                }
                if (code > 1114111 || ch !== "}") {
                  this.throwUnexpectedToken();
                }
                return character_1.Character.fromCodePoint(code);
              };
              Scanner2.prototype.getIdentifier = function() {
                var start = this.index++;
                while (!this.eof()) {
                  var ch = this.source.charCodeAt(this.index);
                  if (ch === 92) {
                    this.index = start;
                    return this.getComplexIdentifier();
                  } else if (ch >= 55296 && ch < 57343) {
                    this.index = start;
                    return this.getComplexIdentifier();
                  }
                  if (character_1.Character.isIdentifierPart(ch)) {
                    ++this.index;
                  } else {
                    break;
                  }
                }
                return this.source.slice(start, this.index);
              };
              Scanner2.prototype.getComplexIdentifier = function() {
                var cp = this.codePointAt(this.index);
                var id = character_1.Character.fromCodePoint(cp);
                this.index += id.length;
                var ch;
                if (cp === 92) {
                  if (this.source.charCodeAt(this.index) !== 117) {
                    this.throwUnexpectedToken();
                  }
                  ++this.index;
                  if (this.source[this.index] === "{") {
                    ++this.index;
                    ch = this.scanUnicodeCodePointEscape();
                  } else {
                    ch = this.scanHexEscape("u");
                    if (ch === null || ch === "\\" || !character_1.Character.isIdentifierStart(ch.charCodeAt(0))) {
                      this.throwUnexpectedToken();
                    }
                  }
                  id = ch;
                }
                while (!this.eof()) {
                  cp = this.codePointAt(this.index);
                  if (!character_1.Character.isIdentifierPart(cp)) {
                    break;
                  }
                  ch = character_1.Character.fromCodePoint(cp);
                  id += ch;
                  this.index += ch.length;
                  if (cp === 92) {
                    id = id.substr(0, id.length - 1);
                    if (this.source.charCodeAt(this.index) !== 117) {
                      this.throwUnexpectedToken();
                    }
                    ++this.index;
                    if (this.source[this.index] === "{") {
                      ++this.index;
                      ch = this.scanUnicodeCodePointEscape();
                    } else {
                      ch = this.scanHexEscape("u");
                      if (ch === null || ch === "\\" || !character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
                        this.throwUnexpectedToken();
                      }
                    }
                    id += ch;
                  }
                }
                return id;
              };
              Scanner2.prototype.octalToDecimal = function(ch) {
                var octal = ch !== "0";
                var code = octalValue(ch);
                if (!this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
                  octal = true;
                  code = code * 8 + octalValue(this.source[this.index++]);
                  if ("0123".indexOf(ch) >= 0 && !this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
                    code = code * 8 + octalValue(this.source[this.index++]);
                  }
                }
                return {
                  code,
                  octal
                };
              };
              Scanner2.prototype.scanIdentifier = function() {
                var type;
                var start = this.index;
                var id = this.source.charCodeAt(start) === 92 ? this.getComplexIdentifier() : this.getIdentifier();
                if (id.length === 1) {
                  type = 3;
                } else if (this.isKeyword(id)) {
                  type = 4;
                } else if (id === "null") {
                  type = 5;
                } else if (id === "true" || id === "false") {
                  type = 1;
                } else {
                  type = 3;
                }
                if (type !== 3 && start + id.length !== this.index) {
                  var restore = this.index;
                  this.index = start;
                  this.tolerateUnexpectedToken(messages_1.Messages.InvalidEscapedReservedWord);
                  this.index = restore;
                }
                return {
                  type,
                  value: id,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanPunctuator = function() {
                var start = this.index;
                var str = this.source[this.index];
                switch (str) {
                  case "(":
                  case "{":
                    if (str === "{") {
                      this.curlyStack.push("{");
                    }
                    ++this.index;
                    break;
                  case ".":
                    ++this.index;
                    if (this.source[this.index] === "." && this.source[this.index + 1] === ".") {
                      this.index += 2;
                      str = "...";
                    }
                    break;
                  case "}":
                    ++this.index;
                    this.curlyStack.pop();
                    break;
                  case ")":
                  case ";":
                  case ",":
                  case "[":
                  case "]":
                  case ":":
                  case "?":
                  case "~":
                    ++this.index;
                    break;
                  default:
                    str = this.source.substr(this.index, 4);
                    if (str === ">>>=") {
                      this.index += 4;
                    } else {
                      str = str.substr(0, 3);
                      if (str === "===" || str === "!==" || str === ">>>" || str === "<<=" || str === ">>=" || str === "**=") {
                        this.index += 3;
                      } else {
                        str = str.substr(0, 2);
                        if (str === "&&" || str === "||" || str === "==" || str === "!=" || str === "+=" || str === "-=" || str === "*=" || str === "/=" || str === "++" || str === "--" || str === "<<" || str === ">>" || str === "&=" || str === "|=" || str === "^=" || str === "%=" || str === "<=" || str === ">=" || str === "=>" || str === "**") {
                          this.index += 2;
                        } else {
                          str = this.source[this.index];
                          if ("<>=!+-*%&|^/".indexOf(str) >= 0) {
                            ++this.index;
                          }
                        }
                      }
                    }
                }
                if (this.index === start) {
                  this.throwUnexpectedToken();
                }
                return {
                  type: 7,
                  value: str,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanHexLiteral = function(start) {
                var num = "";
                while (!this.eof()) {
                  if (!character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
                    break;
                  }
                  num += this.source[this.index++];
                }
                if (num.length === 0) {
                  this.throwUnexpectedToken();
                }
                if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
                  this.throwUnexpectedToken();
                }
                return {
                  type: 6,
                  value: parseInt("0x" + num, 16),
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanBinaryLiteral = function(start) {
                var num = "";
                var ch;
                while (!this.eof()) {
                  ch = this.source[this.index];
                  if (ch !== "0" && ch !== "1") {
                    break;
                  }
                  num += this.source[this.index++];
                }
                if (num.length === 0) {
                  this.throwUnexpectedToken();
                }
                if (!this.eof()) {
                  ch = this.source.charCodeAt(this.index);
                  if (character_1.Character.isIdentifierStart(ch) || character_1.Character.isDecimalDigit(ch)) {
                    this.throwUnexpectedToken();
                  }
                }
                return {
                  type: 6,
                  value: parseInt(num, 2),
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanOctalLiteral = function(prefix, start) {
                var num = "";
                var octal = false;
                if (character_1.Character.isOctalDigit(prefix.charCodeAt(0))) {
                  octal = true;
                  num = "0" + this.source[this.index++];
                } else {
                  ++this.index;
                }
                while (!this.eof()) {
                  if (!character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
                    break;
                  }
                  num += this.source[this.index++];
                }
                if (!octal && num.length === 0) {
                  this.throwUnexpectedToken();
                }
                if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index)) || character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                  this.throwUnexpectedToken();
                }
                return {
                  type: 6,
                  value: parseInt(num, 8),
                  octal,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.isImplicitOctalLiteral = function() {
                for (var i = this.index + 1; i < this.length; ++i) {
                  var ch = this.source[i];
                  if (ch === "8" || ch === "9") {
                    return false;
                  }
                  if (!character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
                    return true;
                  }
                }
                return true;
              };
              Scanner2.prototype.scanNumericLiteral = function() {
                var start = this.index;
                var ch = this.source[start];
                assert_1.assert(character_1.Character.isDecimalDigit(ch.charCodeAt(0)) || ch === ".", "Numeric literal must start with a decimal digit or a decimal point");
                var num = "";
                if (ch !== ".") {
                  num = this.source[this.index++];
                  ch = this.source[this.index];
                  if (num === "0") {
                    if (ch === "x" || ch === "X") {
                      ++this.index;
                      return this.scanHexLiteral(start);
                    }
                    if (ch === "b" || ch === "B") {
                      ++this.index;
                      return this.scanBinaryLiteral(start);
                    }
                    if (ch === "o" || ch === "O") {
                      return this.scanOctalLiteral(ch, start);
                    }
                    if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
                      if (this.isImplicitOctalLiteral()) {
                        return this.scanOctalLiteral(ch, start);
                      }
                    }
                  }
                  while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                    num += this.source[this.index++];
                  }
                  ch = this.source[this.index];
                }
                if (ch === ".") {
                  num += this.source[this.index++];
                  while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                    num += this.source[this.index++];
                  }
                  ch = this.source[this.index];
                }
                if (ch === "e" || ch === "E") {
                  num += this.source[this.index++];
                  ch = this.source[this.index];
                  if (ch === "+" || ch === "-") {
                    num += this.source[this.index++];
                  }
                  if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                    while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                      num += this.source[this.index++];
                    }
                  } else {
                    this.throwUnexpectedToken();
                  }
                }
                if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
                  this.throwUnexpectedToken();
                }
                return {
                  type: 6,
                  value: parseFloat(num),
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanStringLiteral = function() {
                var start = this.index;
                var quote = this.source[start];
                assert_1.assert(quote === "'" || quote === '"', "String literal must starts with a quote");
                ++this.index;
                var octal = false;
                var str = "";
                while (!this.eof()) {
                  var ch = this.source[this.index++];
                  if (ch === quote) {
                    quote = "";
                    break;
                  } else if (ch === "\\") {
                    ch = this.source[this.index++];
                    if (!ch || !character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                      switch (ch) {
                        case "u":
                          if (this.source[this.index] === "{") {
                            ++this.index;
                            str += this.scanUnicodeCodePointEscape();
                          } else {
                            var unescaped_1 = this.scanHexEscape(ch);
                            if (unescaped_1 === null) {
                              this.throwUnexpectedToken();
                            }
                            str += unescaped_1;
                          }
                          break;
                        case "x":
                          var unescaped = this.scanHexEscape(ch);
                          if (unescaped === null) {
                            this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
                          }
                          str += unescaped;
                          break;
                        case "n":
                          str += "\n";
                          break;
                        case "r":
                          str += "\r";
                          break;
                        case "t":
                          str += "	";
                          break;
                        case "b":
                          str += "\b";
                          break;
                        case "f":
                          str += "\f";
                          break;
                        case "v":
                          str += "\v";
                          break;
                        case "8":
                        case "9":
                          str += ch;
                          this.tolerateUnexpectedToken();
                          break;
                        default:
                          if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
                            var octToDec = this.octalToDecimal(ch);
                            octal = octToDec.octal || octal;
                            str += String.fromCharCode(octToDec.code);
                          } else {
                            str += ch;
                          }
                          break;
                      }
                    } else {
                      ++this.lineNumber;
                      if (ch === "\r" && this.source[this.index] === "\n") {
                        ++this.index;
                      }
                      this.lineStart = this.index;
                    }
                  } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                    break;
                  } else {
                    str += ch;
                  }
                }
                if (quote !== "") {
                  this.index = start;
                  this.throwUnexpectedToken();
                }
                return {
                  type: 8,
                  value: str,
                  octal,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanTemplate = function() {
                var cooked = "";
                var terminated = false;
                var start = this.index;
                var head = this.source[start] === "`";
                var tail = false;
                var rawOffset = 2;
                ++this.index;
                while (!this.eof()) {
                  var ch = this.source[this.index++];
                  if (ch === "`") {
                    rawOffset = 1;
                    tail = true;
                    terminated = true;
                    break;
                  } else if (ch === "$") {
                    if (this.source[this.index] === "{") {
                      this.curlyStack.push("${");
                      ++this.index;
                      terminated = true;
                      break;
                    }
                    cooked += ch;
                  } else if (ch === "\\") {
                    ch = this.source[this.index++];
                    if (!character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                      switch (ch) {
                        case "n":
                          cooked += "\n";
                          break;
                        case "r":
                          cooked += "\r";
                          break;
                        case "t":
                          cooked += "	";
                          break;
                        case "u":
                          if (this.source[this.index] === "{") {
                            ++this.index;
                            cooked += this.scanUnicodeCodePointEscape();
                          } else {
                            var restore = this.index;
                            var unescaped_2 = this.scanHexEscape(ch);
                            if (unescaped_2 !== null) {
                              cooked += unescaped_2;
                            } else {
                              this.index = restore;
                              cooked += ch;
                            }
                          }
                          break;
                        case "x":
                          var unescaped = this.scanHexEscape(ch);
                          if (unescaped === null) {
                            this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
                          }
                          cooked += unescaped;
                          break;
                        case "b":
                          cooked += "\b";
                          break;
                        case "f":
                          cooked += "\f";
                          break;
                        case "v":
                          cooked += "\v";
                          break;
                        default:
                          if (ch === "0") {
                            if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                              this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
                            }
                            cooked += "\0";
                          } else if (character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
                            this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
                          } else {
                            cooked += ch;
                          }
                          break;
                      }
                    } else {
                      ++this.lineNumber;
                      if (ch === "\r" && this.source[this.index] === "\n") {
                        ++this.index;
                      }
                      this.lineStart = this.index;
                    }
                  } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                    ++this.lineNumber;
                    if (ch === "\r" && this.source[this.index] === "\n") {
                      ++this.index;
                    }
                    this.lineStart = this.index;
                    cooked += "\n";
                  } else {
                    cooked += ch;
                  }
                }
                if (!terminated) {
                  this.throwUnexpectedToken();
                }
                if (!head) {
                  this.curlyStack.pop();
                }
                return {
                  type: 10,
                  value: this.source.slice(start + 1, this.index - rawOffset),
                  cooked,
                  head,
                  tail,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.testRegExp = function(pattern, flags) {
                var astralSubstitute = "\uFFFF";
                var tmp = pattern;
                var self2 = this;
                if (flags.indexOf("u") >= 0) {
                  tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function($0, $1, $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 regex = previous !== null;
                switch (previous) {
                  case "this":
                  case "]":
                    regex = false;
                    break;
                  case ")":
                    var keyword = this.values[this.paren - 1];
                    regex = keyword === "if" || keyword === "while" || keyword === "for" || keyword === "with";
                    break;
                  case "}":
                    regex = false;
                    if (this.values[this.curly - 3] === "function") {
                      var check = this.values[this.curly - 4];
                      regex = check ? !this.beforeFunctionExpression(check) : false;
                    } else if (this.values[this.curly - 4] === "function") {
                      var check = this.values[this.curly - 5];
                      regex = check ? !this.beforeFunctionExpression(check) : true;
                    }
                    break;
                  default:
                    break;
                }
                return regex;
              };
              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, config2) {
                this.errorHandler = new error_handler_1.ErrorHandler();
                this.errorHandler.tolerant = config2 ? typeof config2.tolerant === "boolean" && config2.tolerant : false;
                this.scanner = new scanner_1.Scanner(code, this.errorHandler);
                this.scanner.trackComment = config2 ? typeof config2.comment === "boolean" && config2.comment : false;
                this.trackRange = config2 ? typeof config2.range === "boolean" && config2.range : false;
                this.trackLoc = config2 ? typeof config2.loc === "boolean" && config2.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/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: () => __classPrivateFieldGet,
  __classPrivateFieldIn: () => __classPrivateFieldIn,
  __classPrivateFieldSet: () => __classPrivateFieldSet,
  __createBinding: () => __createBinding,
  __decorate: () => __decorate,
  __disposeResources: () => __disposeResources,
  __esDecorate: () => __esDecorate,
  __exportStar: () => __exportStar,
  __extends: () => __extends,
  __generator: () => __generator,
  __importDefault: () => __importDefault,
  __importStar: () => __importStar,
  __makeTemplateObject: () => __makeTemplateObject,
  __metadata: () => __metadata,
  __param: () => __param,
  __propKey: () => __propKey,
  __read: () => __read,
  __rest: () => __rest,
  __rewriteRelativeImportExtension: () => __rewriteRelativeImportExtension,
  __runInitializers: () => __runInitializers,
  __setFunctionName: () => __setFunctionName,
  __spread: () => __spread,
  __spreadArray: () => __spreadArray,
  __spreadArrays: () => __spreadArrays,
  __values: () => __values,
  default: () => tslib_es6_default
});
function __extends(d, b) {
  if (typeof b !== "function" && b !== null)
    throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  extendStatics(d, b);
  function __() {
    this.constructor = d;
  }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __rest(s, e) {
  var t = {};
  for (var 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, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
}
function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
  function accept(f) {
    if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
    return f;
  }
  var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
  var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
  var _, done = false;
  for (var i = decorators.length - 1; i >= 0; i--) {
    var context = {};
    for (var 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 (_ = accept(result.get)) descriptor.get = _;
      if (_ = accept(result.set)) descriptor.set = _;
      if (_ = accept(result.init)) initializers.unshift(_);
    } else if (_ = accept(result)) {
      if (kind === "field") initializers.unshift(_);
      else descriptor[key] = _;
    }
  }
  if (target) Object.defineProperty(target, contextIn.name, descriptor);
  done = true;
}
function __runInitializers(thisArg, initializers, value) {
  var useValue = arguments.length > 2;
  for (var i = 0; i < initializers.length; i++) {
    value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
  }
  return useValue ? value : void 0;
}
function __propKey(x) {
  return typeof x === "symbol" ? x : "".concat(x);
}
function __setFunctionName(f, name, prefix) {
  if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
  return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
}
function __metadata(metadataKey, metadataValue) {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve5) {
      resolve5(value);
    });
  }
  return new (P || (P = Promise))(function(resolve5, 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 ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator(thisArg, body) {
  var _ = { label: 0, sent: function() {
    if (t[0] & 1) throw t[1];
    return t[1];
  }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
  return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n) {
    return function(v) {
      return step([n, v]);
    };
  }
  function step(op) {
    if (f) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_ = 0)), _) try {
      if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
      if (y = 0, t) op = [op[0] & 2, t.value];
      switch (op[0]) {
        case 0:
        case 1:
          t = op;
          break;
        case 4:
          _.label++;
          return { value: op[1], done: false };
        case 5:
          _.label++;
          y = op[1];
          op = [0];
          continue;
        case 7:
          op = _.ops.pop();
          _.trys.pop();
          continue;
        default:
          if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _ = 0;
            continue;
          }
          if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
            _.label = op[1];
            break;
          }
          if (op[0] === 6 && _.label < t[1]) {
            _.label = t[1];
            t = op;
            break;
          }
          if (t && _.label < t[2]) {
            _.label = t[2];
            _.ops.push(op);
            break;
          }
          if (t[2]) _.ops.pop();
          _.trys.pop();
          continue;
      }
      op = body.call(thisArg, _);
    } catch (e) {
      op = [6, e];
      y = 0;
    } finally {
      f = t = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
}
function __exportStar(m, o) {
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
}
function __values(o) {
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  if (m) return m.call(o);
  if (o && typeof o.length === "number") return {
    next: function() {
      if (o && i >= o.length) o = void 0;
      return { value: o && o[i++], done: !o };
    }
  };
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
  var m = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m) return o;
  var i = m.call(o), r, ar = [], e;
  try {
    while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  } catch (error) {
    e = { error };
  } finally {
    try {
      if (r && !r.done && (m = i["return"])) m.call(i);
    } finally {
      if (e) throw e.error;
    }
  }
  return ar;
}
function __spread() {
  for (var ar = [], i = 0; i < arguments.length; i++)
    ar = ar.concat(__read(arguments[i]));
  return ar;
}
function __spreadArrays() {
  for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
  for (var r = Array(s), k = 0, i = 0; i < il; i++)
    for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
      r[k] = a[j];
  return r;
}
function __spreadArray(to, from, pack) {
  if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
    if (ar || !(i in from)) {
      if (!ar) ar = Array.prototype.slice.call(from, 0, i);
      ar[i] = from[i];
    }
  }
  return to.concat(ar || Array.prototype.slice.call(from));
}
function __await(v) {
  return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var g = generator.apply(thisArg, _arguments || []), i, q = [];
  return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() {
    return this;
  }, i;
  function awaitReturn(f) {
    return function(v) {
      return Promise.resolve(v).then(f, reject);
    };
  }
  function verb(n, f) {
    if (g[n]) {
      i[n] = function(v) {
        return new Promise(function(a, b) {
          q.push([n, v, a, b]) > 1 || resume(n, v);
        });
      };
      if (f) i[n] = f(i[n]);
    }
  }
  function resume(n, v) {
    try {
      step(g[n](v));
    } catch (e) {
      settle(q[0][3], e);
    }
  }
  function step(r) {
    r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
  }
  function fulfill(value) {
    resume("next", value);
  }
  function reject(value) {
    resume("throw", value);
  }
  function settle(f, v) {
    if (f(v), q.shift(), q.length) resume(q[0][0], q[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(v) {
      return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v;
    } : f;
  }
}
function __asyncValues(o) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var m = o[Symbol.asyncIterator], i;
  return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
    return this;
  }, i);
  function verb(n) {
    i[n] = o[n] && function(v) {
      return new Promise(function(resolve5, reject) {
        v = o[n](v), settle(resolve5, reject, v.done, v.value);
      });
    };
  }
  function settle(resolve5, reject, d, v) {
    Promise.resolve(v).then(function(v2) {
      resolve5({ value: v2, done: d });
    }, reject);
  }
}
function __makeTemplateObject(cooked, raw) {
  if (Object.defineProperty) {
    Object.defineProperty(cooked, "raw", { value: raw });
  } else {
    cooked.raw = raw;
  }
  return cooked;
}
function __importStar(mod) {
  if (mod && mod.__esModule) return mod;
  var result = {};
  if (mod != null) {
    for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  }
  __setModuleDefault(result, mod);
  return result;
}
function __importDefault(mod) {
  return mod && mod.__esModule ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, state, kind, f) {
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
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(env2, 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);
      }
    };
    env2.stack.push({ value, dispose, async });
  } else if (async) {
    env2.stack.push({ async: true });
  }
  return value;
}
function __disposeResources(env2) {
  function fail(e) {
    env2.error = env2.hasError ? new _SuppressedError(e, env2.error, "An error was suppressed during disposal.") : e;
    env2.hasError = true;
  }
  var r, s = 0;
  function next() {
    while (r = env2.stack.pop()) {
      try {
        if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
        if (r.dispose) {
          var result = r.dispose.call(r.value);
          if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
            fail(e);
            return next();
          });
        } else s |= 1;
      } catch (e) {
        fail(e);
      }
    }
    if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
    if (env2.hasError) throw env2.error;
  }
  return next();
}
function __rewriteRelativeImportExtension(path2, preserveJsx) {
  if (typeof path2 === "string" && /^\.\.?\//.test(path2)) {
    return path2.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
      return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
    });
  }
  return path2;
}
var extendStatics, __assign, __createBinding, __setModuleDefault, ownKeys, _SuppressedError, tslib_es6_default;
var init_tslib_es6 = __esm({
  "node_modules/tslib/tslib.es6.mjs"() {
    init_prefix();
    extendStatics = function(d, b) {
      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
        d2.__proto__ = b2;
      } || function(d2, b2) {
        for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
      };
      return extendStatics(d, b);
    };
    __assign = function() {
      __assign = Object.assign || function __assign2(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
          s = arguments[i];
          for (var 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, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    __setModuleDefault = Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    };
    ownKeys = function(o) {
      ownKeys = Object.getOwnPropertyNames || function(o2) {
        var ar = [];
        for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
        return ar;
      };
      return ownKeys(o);
    };
    _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(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,
      __classPrivateFieldSet,
      __classPrivateFieldIn,
      __addDisposableResource,
      __disposeResources,
      __rewriteRelativeImportExtension
    };
  }
});

// node_modules/ast-types/lib/types.js
var require_types2 = __commonJS({
  "node_modules/ast-types/lib/types.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Def = void 0;
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var Op = Object.prototype;
    var objToStr = Op.toString;
    var hasOwn = Op.hasOwnProperty;
    var BaseType = (
      /** @class */
      (function() {
        function BaseType2() {
        }
        BaseType2.prototype.assert = function(value, deep) {
          if (!this.check(value, deep)) {
            var str = shallowStringify(value);
            throw new Error(str + " does not match type " + this);
          }
          return true;
        };
        BaseType2.prototype.arrayOf = function() {
          var elemType = this;
          return new ArrayType(elemType);
        };
        return BaseType2;
      })()
    );
    var ArrayType = (
      /** @class */
      (function(_super) {
        tslib_1.__extends(ArrayType2, _super);
        function ArrayType2(elemType) {
          var _this = _super.call(this) || this;
          _this.elemType = elemType;
          _this.kind = "ArrayType";
          return _this;
        }
        ArrayType2.prototype.toString = function() {
          return "[" + this.elemType + "]";
        };
        ArrayType2.prototype.check = function(value, deep) {
          var _this = this;
          return Array.isArray(value) && value.every(function(elem) {
            return _this.elemType.check(elem, deep);
          });
        };
        return ArrayType2;
      })(BaseType)
    );
    var IdentityType = (
      /** @class */
      (function(_super) {
        tslib_1.__extends(IdentityType2, _super);
        function IdentityType2(value) {
          var _this = _super.call(this) || this;
          _this.value = value;
          _this.kind = "IdentityType";
          return _this;
        }
        IdentityType2.prototype.toString = function() {
          return String(this.value);
        };
        IdentityType2.prototype.check = function(value, deep) {
          var result = value === this.value;
          if (!result && typeof deep === "function") {
            deep(this, value);
          }
          return result;
        };
        return IdentityType2;
      })(BaseType)
    );
    var ObjectType = (
      /** @class */
      (function(_super) {
        tslib_1.__extends(ObjectType2, _super);
        function ObjectType2(fields) {
          var _this = _super.call(this) || this;
          _this.fields = fields;
          _this.kind = "ObjectType";
          return _this;
        }
        ObjectType2.prototype.toString = function() {
          return "{ " + this.fields.join(", ") + " }";
        };
        ObjectType2.prototype.check = function(value, deep) {
          return objToStr.call(value) === objToStr.call({}) && this.fields.every(function(field) {
            return field.type.check(value[field.name], deep);
          });
        };
        return ObjectType2;
      })(BaseType)
    );
    var OrType = (
      /** @class */
      (function(_super) {
        tslib_1.__extends(OrType2, _super);
        function OrType2(types) {
          var _this = _super.call(this) || this;
          _this.types = types;
          _this.kind = "OrType";
          return _this;
        }
        OrType2.prototype.toString = function() {
          return this.types.join(" | ");
        };
        OrType2.prototype.check = function(value, deep) {
          return this.types.some(function(type) {
            return type.check(value, deep);
          });
        };
        return OrType2;
      })(BaseType)
    );
    var PredicateType = (
      /** @class */
      (function(_super) {
        tslib_1.__extends(PredicateType2, _super);
        function PredicateType2(name, predicate) {
          var _this = _super.call(this) || this;
          _this.name = name;
          _this.predicate = predicate;
          _this.kind = "PredicateType";
          return _this;
        }
        PredicateType2.prototype.toString = function() {
          return this.name;
        };
        PredicateType2.prototype.check = function(value, deep) {
          var result = this.predicate(value, deep);
          if (!result && typeof deep === "function") {
            deep(this, value);
          }
          return result;
        };
        return PredicateType2;
      })(BaseType)
    );
    var Def = (
      /** @class */
      (function() {
        function Def2(type, typeName) {
          this.type = type;
          this.typeName = typeName;
          this.baseNames = [];
          this.ownFields = /* @__PURE__ */ Object.create(null);
          this.allSupertypes = /* @__PURE__ */ Object.create(null);
          this.supertypeList = [];
          this.allFields = /* @__PURE__ */ Object.create(null);
          this.fieldNames = [];
          this.finalized = false;
          this.buildable = false;
          this.buildParams = [];
        }
        Def2.prototype.isSupertypeOf = function(that) {
          if (that instanceof Def2) {
            if (this.finalized !== true || that.finalized !== true) {
              throw new Error("");
            }
            return hasOwn.call(that.allSupertypes, this.typeName);
          } else {
            throw new Error(that + " is not a Def");
          }
        };
        Def2.prototype.checkAllFields = function(value, deep) {
          var allFields = this.allFields;
          if (this.finalized !== true) {
            throw new Error("" + this.typeName);
          }
          function checkFieldByName(name) {
            var field = allFields[name];
            var type = field.type;
            var child = field.getValue(value);
            return type.check(child, deep);
          }
          return value !== null && typeof value === "object" && Object.keys(allFields).every(checkFieldByName);
        };
        Def2.prototype.bases = function() {
          var supertypeNames = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            supertypeNames[_i] = arguments[_i];
          }
          var bases = this.baseNames;
          if (this.finalized) {
            if (supertypeNames.length !== bases.length) {
              throw new Error("");
            }
            for (var i = 0; i < supertypeNames.length; i++) {
              if (supertypeNames[i] !== bases[i]) {
                throw new Error("");
              }
            }
            return this;
          }
          supertypeNames.forEach(function(baseName) {
            if (bases.indexOf(baseName) < 0) {
              bases.push(baseName);
            }
          });
          return this;
        };
        return Def2;
      })()
    );
    exports2.Def = Def;
    var Field = (
      /** @class */
      (function() {
        function Field2(name, type, defaultFn, hidden) {
          this.name = name;
          this.type = type;
          this.defaultFn = defaultFn;
          this.hidden = !!hidden;
        }
        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 types = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            types[_i] = arguments[_i];
          }
          return new OrType(types.map(function(type) {
            return Type.from(type);
          }));
        },
        from: function(value, name) {
          if (value instanceof ArrayType || value instanceof IdentityType || value instanceof ObjectType || value instanceof OrType || value instanceof PredicateType) {
            return value;
          }
          if (value instanceof Def) {
            return value.type;
          }
          if (isArray.check(value)) {
            if (value.length !== 1) {
              throw new Error("only one element type is permitted for typed arrays");
            }
            return new ArrayType(Type.from(value[0]));
          }
          if (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 hasOwn.call(defCache, typeName) ? defCache[typeName] : defCache[typeName] = new DefImpl(typeName);
        },
        hasDef: function(typeName) {
          return hasOwn.call(defCache, typeName);
        }
      };
      var builtInCtorFns = [];
      var builtInCtorTypes = [];
      function defBuiltInType(name, example) {
        var objStr = objToStr.call(example);
        var type = new PredicateType(name, function(value) {
          return objToStr.call(value) === objStr;
        });
        if (example && typeof example.constructor === "function") {
          builtInCtorFns.push(example.constructor);
          builtInCtorTypes.push(type);
        }
        return type;
      }
      var isString = defBuiltInType("string", "truthy");
      var isFunction2 = defBuiltInType("function", function() {
      });
      var isArray = 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 isNull = defBuiltInType("null", null);
      var isUndefined = defBuiltInType("undefined", void 0);
      var builtInTypes = {
        string: isString,
        function: isFunction2,
        array: isArray,
        object: isObject,
        RegExp: isRegExp,
        Date: isDate,
        number: isNumber,
        boolean: isBoolean2,
        null: isNull,
        undefined: isUndefined
      };
      var defCache = /* @__PURE__ */ Object.create(null);
      function defFromValue(value) {
        if (value && typeof value === "object") {
          var type = value.type;
          if (typeof type === "string" && hasOwn.call(defCache, type)) {
            var d = defCache[type];
            if (d.finalized) {
              return d;
            }
          }
        }
        return null;
      }
      var DefImpl = (
        /** @class */
        (function(_super) {
          tslib_1.__extends(DefImpl2, _super);
          function DefImpl2(typeName) {
            var _this = _super.call(this, new PredicateType(typeName, function(value, deep) {
              return _this.check(value, deep);
            }), typeName) || this;
            return _this;
          }
          DefImpl2.prototype.check = function(value, deep) {
            if (this.finalized !== true) {
              throw new Error("prematurely checking unfinalized type " + this.typeName);
            }
            if (value === null || typeof value !== "object") {
              return false;
            }
            var vDef = defFromValue(value);
            if (!vDef) {
              if (this.typeName === "SourceLocation" || this.typeName === "Position") {
                return this.checkAllFields(value, deep);
              }
              return false;
            }
            if (deep && vDef === this) {
              return this.checkAllFields(value, deep);
            }
            if (!this.isSupertypeOf(vDef)) {
              return false;
            }
            if (!deep) {
              return true;
            }
            return vDef.checkAllFields(value, deep) && this.checkAllFields(value, false);
          };
          DefImpl2.prototype.build = function() {
            var _this = this;
            var buildParams = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              buildParams[_i] = arguments[_i];
            }
            this.buildParams = buildParams;
            if (this.buildable) {
              return this;
            }
            this.field("type", String, function() {
              return _this.typeName;
            });
            this.buildable = true;
            var addParam = function(built, param, arg, isArgAvailable) {
              if (hasOwn.call(built, param))
                return;
              var all = _this.allFields;
              if (!hasOwn.call(all, param)) {
                throw new Error("" + param);
              }
              var field = all[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 all[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 args2 = [];
              for (var _i2 = 0; _i2 < arguments.length; _i2++) {
                args2[_i2] = arguments[_i2];
              }
              var argc = args2.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, args2[i], true);
                } else {
                  addParam(built, param, null, false);
                }
              });
              Object.keys(_this.allFields).forEach(function(param) {
                addParam(built, param, null, false);
              });
              if (built.type !== _this.typeName) {
                throw new Error("");
              }
              return built;
            };
            builder.from = function(obj) {
              if (!_this.finalized) {
                throw new Error("attempting to instantiate unfinalized type " + _this.typeName);
              }
              var built = Object.create(nodePrototype);
              Object.keys(_this.allFields).forEach(function(param) {
                if (hasOwn.call(obj, param)) {
                  addParam(built, param, obj[param], true);
                } else {
                  addParam(built, param, null, false);
                }
              });
              if (built.type !== _this.typeName) {
                throw new Error("");
              }
              return built;
            };
            Object.defineProperty(builders, getBuilderName(this.typeName), {
              enumerable: true,
              value: builder
            });
            return this;
          };
          DefImpl2.prototype.field = function(name, type, defaultFn, hidden) {
            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, hidden);
            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();
                  extend(allFields, def.allFields);
                  extend(allSupertypes, def.allSupertypes);
                } else {
                  var message = "unknown supertype name " + JSON.stringify(name) + " for subtype " + JSON.stringify(_this.typeName);
                  throw new Error(message);
                }
              });
              extend(allFields, this.ownFields);
              allSupertypes[this.typeName] = this;
              this.fieldNames.length = 0;
              for (var fieldName in allFields) {
                if (hasOwn.call(allFields, fieldName) && !allFields[fieldName].hidden) {
                  this.fieldNames.push(fieldName);
                }
              }
              Object.defineProperty(namedTypes, this.typeName, {
                enumerable: true,
                value: this.type
              });
              this.finalized = true;
              populateSupertypeList(this.typeName, this.supertypeList);
              if (this.buildable && this.supertypeList.lastIndexOf("Expression") >= 0) {
                wrapExpressionBuilderWithStatement(this.typeName);
              }
            }
          };
          return DefImpl2;
        })(Def)
      );
      function getSupertypeNames(typeName) {
        if (!hasOwn.call(defCache, typeName)) {
          throw new Error("");
        }
        var d = defCache[typeName];
        if (d.finalized !== true) {
          throw new Error("");
        }
        return d.supertypeList.slice(1);
      }
      function computeSupertypeLookupTable(candidates) {
        var table = {};
        var typeNames = Object.keys(defCache);
        var typeNameCount = typeNames.length;
        for (var i = 0; i < typeNameCount; ++i) {
          var typeName = typeNames[i];
          var d = defCache[typeName];
          if (d.finalized !== true) {
            throw new Error("" + typeName);
          }
          for (var j = 0; j < d.supertypeList.length; ++j) {
            var superTypeName = d.supertypeList[j];
            if (hasOwn.call(candidates, superTypeName)) {
              table[typeName] = superTypeName;
              break;
            }
          }
        }
        return table;
      }
      var builders = /* @__PURE__ */ Object.create(null);
      var nodePrototype = {};
      function defineMethod(name, func) {
        var old = nodePrototype[name];
        if (isUndefined.check(func)) {
          delete nodePrototype[name];
        } else {
          isFunction2.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 d = defFromValue(object);
        if (d) {
          return d.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 d = defFromValue(object);
        if (d) {
          var field = d.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 args2 = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args2[_i] = arguments[_i];
          }
          return builders.expressionStatement(wrapped.apply(builders, args2));
        };
        builder.from = function() {
          var args2 = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args2[_i] = arguments[_i];
          }
          return builders.expressionStatement(wrapped.from.apply(builders, args2));
        };
        builders[wrapperName] = builder;
      }
      function populateSupertypeList(typeName, list) {
        list.length = 0;
        list.push(typeName);
        var lastSeen = /* @__PURE__ */ Object.create(null);
        for (var pos = 0; pos < list.length; ++pos) {
          typeName = list[pos];
          var d = defCache[typeName];
          if (d.finalized !== true) {
            throw new Error("");
          }
          if (hasOwn.call(lastSeen, typeName)) {
            delete list[lastSeen[typeName]];
          }
          lastSeen[typeName] = pos;
          list.push.apply(list, d.baseNames);
        }
        for (var to = 0, from = to, len = list.length; from < len; ++from) {
          if (hasOwn.call(list, from)) {
            list[to++] = list[from];
          }
        }
        list.length = to;
      }
      function extend(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/ast-types/lib/path.js
var require_path = __commonJS({
  "node_modules/ast-types/lib/path.js"(exports2, module2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types2());
    var Op = Object.prototype;
    var hasOwn = Op.hasOwnProperty;
    function pathPlugin(fork) {
      var types = fork.use(types_1.default);
      var isArray = types.builtInTypes.array;
      var isNumber = types.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(path2) {
        return path2.__childCache || (path2.__childCache = /* @__PURE__ */ Object.create(null));
      }
      function getChildPath(path2, name) {
        var cache = getChildCache(path2);
        var actualChildValue = path2.getValueProperty(name);
        var childPath = cache[name];
        if (!hasOwn.call(cache, name) || // Ensure consistency between cache and reality.
        childPath.value !== actualChildValue) {
          childPath = cache[name] = new path2.constructor(actualChildValue, path2, 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 path2 = this;
        var count = names.length;
        for (var i = 0; i < count; ++i) {
          path2 = getChildPath(path2, names[i]);
        }
        return path2;
      };
      Pp.each = function each(callback, context) {
        var childPaths = [];
        var len = this.value.length;
        var i = 0;
        for (var i = 0; i < len; ++i) {
          if (hasOwn.call(this.value, i)) {
            childPaths[i] = this.get(i);
          }
        }
        context = context || this;
        for (i = 0; i < len; ++i) {
          if (hasOwn.call(childPaths, i)) {
            callback.call(context, childPaths[i]);
          }
        }
      };
      Pp.map = function 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(path2, offset, start, end) {
        isArray.assert(path2.value);
        if (offset === 0) {
          return emptyMoves;
        }
        var length = path2.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(path2);
        for (var i = start; i < end; ++i) {
          if (hasOwn.call(path2.value, i)) {
            var childPath = path2.get(i);
            if (childPath.name !== i) {
              throw new Error("");
            }
            var newIndex = i + offset;
            childPath.name = newIndex;
            moves[newIndex] = childPath;
            delete cache[i];
          }
        }
        delete cache.length;
        return function() {
          for (var newIndex2 in moves) {
            var childPath2 = moves[newIndex2];
            if (childPath2.name !== +newIndex2) {
              throw new Error("");
            }
            cache[newIndex2] = childPath2;
            path2.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 args2 = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args2[_i] = arguments[_i];
        }
        var move = getMoves(this, args2.length);
        var result = this.value.unshift.apply(this.value, args2);
        move();
        return result;
      };
      Pp.push = function push() {
        var args2 = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args2[_i] = arguments[_i];
        }
        isArray.assert(this.value);
        delete getChildCache(this).length;
        return this.value.push.apply(this.value, args2);
      };
      Pp.pop = function pop() {
        isArray.assert(this.value);
        var cache = getChildCache(this);
        delete cache[this.value.length - 1];
        delete cache.length;
        return this.value.pop();
      };
      Pp.insertAt = function insertAt(index) {
        var argc = arguments.length;
        var move = getMoves(this, argc - 1, index);
        if (move === emptyMoves && argc <= 1) {
          return this;
        }
        index = Math.max(index, 0);
        for (var i = 1; i < argc; ++i) {
          this.value[index + i - 1] = arguments[i];
        }
        move();
        return this;
      };
      Pp.insertBefore = function insertBefore() {
        var args2 = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args2[_i] = arguments[_i];
        }
        var pp = this.parentPath;
        var argc = args2.length;
        var insertAtArgs = [this.name];
        for (var i = 0; i < argc; ++i) {
          insertAtArgs.push(args2[i]);
        }
        return pp.insertAt.apply(pp, insertAtArgs);
      };
      Pp.insertAfter = function insertAfter() {
        var args2 = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args2[_i] = arguments[_i];
        }
        var pp = this.parentPath;
        var argc = args2.length;
        var insertAtArgs = [this.name + 1];
        for (var i = 0; i < argc; ++i) {
          insertAtArgs.push(args2[i]);
        }
        return pp.insertAt.apply(pp, insertAtArgs);
      };
      function repairRelationshipWithParent(path2) {
        if (!(path2 instanceof Path)) {
          throw new Error("");
        }
        var pp = path2.parentPath;
        if (!pp) {
          return path2;
        }
        var parentValue = pp.value;
        var parentCache = getChildCache(pp);
        if (parentValue[path2.name] === path2.value) {
          parentCache[path2.name] = path2;
        } else if (isArray.check(parentValue)) {
          var i = parentValue.indexOf(path2.value);
          if (i >= 0) {
            parentCache[path2.name = i] = path2;
          }
        } else {
          parentValue[path2.name] = path2.value;
          parentCache[path2.name] = path2;
        }
        if (parentValue[path2.name] !== path2.value) {
          throw new Error("");
        }
        if (path2.parentPath.get(path2.name) !== path2) {
          throw new Error("");
        }
        return path2;
      }
      Pp.replace = function replace(replacement) {
        var results = [];
        var parentValue = this.parentPath.value;
        var parentCache = getChildCache(this.parentPath);
        var count = arguments.length;
        repairRelationshipWithParent(this);
        if (isArray.check(parentValue)) {
          var originalLength = parentValue.length;
          var move = getMoves(this.parentPath, count - 1, this.name + 1);
          var spliceArgs = [this.name, 1];
          for (var i = 0; i < count; ++i) {
            spliceArgs.push(arguments[i]);
          }
          var splicedOut = parentValue.splice.apply(parentValue, spliceArgs);
          if (splicedOut[0] !== this.value) {
            throw new Error("");
          }
          if (parentValue.length !== originalLength - 1 + count) {
            throw new Error("");
          }
          move();
          if (count === 0) {
            delete this.value;
            delete parentCache[this.name];
            this.__childCache = null;
          } else {
            if (parentValue[this.name] !== replacement) {
              throw new Error("");
            }
            if (this.value !== replacement) {
              this.value = replacement;
              this.__childCache = null;
            }
            for (i = 0; i < count; ++i) {
              results.push(this.parentPath.get(this.name + i));
            }
            if (results[0] !== this) {
              throw new Error("");
            }
          }
        } else if (count === 1) {
          if (this.value !== replacement) {
            this.__childCache = null;
          }
          this.value = parentValue[this.name] = replacement;
          results.push(this);
        } else if (count === 0) {
          delete parentValue[this.name];
          delete this.value;
          this.__childCache = null;
        } else {
          throw new Error("Could not replace path");
        }
        return results;
      };
      return Path;
    }
    exports2.default = pathPlugin;
    module2.exports = exports2["default"];
  }
});

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

// node_modules/ast-types/lib/node-path.js
var require_node_path = __commonJS({
  "node_modules/ast-types/lib/node-path.js"(exports2, module2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types2());
    var path_1 = tslib_1.__importDefault(require_path());
    var scope_1 = tslib_1.__importDefault(require_scope());
    function nodePathPlugin(fork) {
      var types = fork.use(types_1.default);
      var n = types.namedTypes;
      var b = types.builders;
      var isNumber = types.builtInTypes.number;
      var isArray = types.builtInTypes.array;
      var Path = fork.use(path_1.default);
      var Scope = fork.use(scope_1.default);
      var NodePath = function NodePath2(value, parentPath, name) {
        if (!(this instanceof NodePath2)) {
          throw new Error("NodePath constructor cannot be invoked without 'new'");
        }
        Path.call(this, value, parentPath, name);
      };
      var NPp = NodePath.prototype = Object.create(Path.prototype, {
        constructor: {
          value: NodePath,
          enumerable: false,
          writable: true,
          configurable: true
        }
      });
      Object.defineProperties(NPp, {
        node: {
          get: function() {
            Object.defineProperty(this, "node", {
              configurable: true,
              value: this._computeNode()
            });
            return this.node;
          }
        },
        parent: {
          get: function() {
            Object.defineProperty(this, "parent", {
              configurable: true,
              value: this._computeParent()
            });
            return this.parent;
          }
        },
        scope: {
          get: function() {
            Object.defineProperty(this, "scope", {
              configurable: true,
              value: this._computeScope()
            });
            return this.scope;
          }
        }
      });
      NPp.replace = function() {
        delete this.node;
        delete this.parent;
        delete this.scope;
        return Path.prototype.replace.apply(this, arguments);
      };
      NPp.prune = function() {
        var remainingNodePath = this.parent;
        this.replace();
        return cleanUpNodesAfterPrune(remainingNodePath);
      };
      NPp._computeNode = function() {
        var value = this.value;
        if (n.Node.check(value)) {
          return value;
        }
        var pp = this.parentPath;
        return pp && pp.node || null;
      };
      NPp._computeParent = function() {
        var value = this.value;
        var pp = this.parentPath;
        if (!n.Node.check(value)) {
          while (pp && !n.Node.check(pp.value)) {
            pp = pp.parentPath;
          }
          if (pp) {
            pp = pp.parentPath;
          }
        }
        while (pp && !n.Node.check(pp.value)) {
          pp = pp.parentPath;
        }
        return pp || null;
      };
      NPp._computeScope = function() {
        var value = this.value;
        var pp = this.parentPath;
        var scope = pp && pp.scope;
        if (n.Node.check(value) && Scope.isEstablishedBy(value)) {
          scope = new Scope(this, scope);
        }
        return scope || null;
      };
      NPp.getValueProperty = function(name) {
        return types.getFieldValue(this.value, name);
      };
      NPp.needsParens = function(assumeExpressionContext) {
        var pp = this.parentPath;
        if (!pp) {
          return false;
        }
        var node = this.value;
        if (!n.Expression.check(node)) {
          return false;
        }
        if (node.type === "Identifier") {
          return false;
        }
        while (!n.Node.check(pp.value)) {
          pp = pp.parentPath;
          if (!pp) {
            return false;
          }
        }
        var parent = pp.value;
        switch (node.type) {
          case "UnaryExpression":
          case "SpreadElement":
          case "SpreadProperty":
            return parent.type === "MemberExpression" && this.name === "object" && parent.object === node;
          case "BinaryExpression":
          case "LogicalExpression":
            switch (parent.type) {
              case "CallExpression":
                return this.name === "callee" && parent.callee === node;
              case "UnaryExpression":
              case "SpreadElement":
              case "SpreadProperty":
                return true;
              case "MemberExpression":
                return this.name === "object" && parent.object === node;
              case "BinaryExpression":
              case "LogicalExpression": {
                var n_1 = node;
                var po = parent.operator;
                var pp_1 = PRECEDENCE[po];
                var no = n_1.operator;
                var np = PRECEDENCE[no];
                if (pp_1 > np) {
                  return true;
                }
                if (pp_1 === np && this.name === "right") {
                  if (parent.right !== n_1) {
                    throw new Error("Nodes must be equal");
                  }
                  return true;
                }
              }
              default:
                return false;
            }
          case "SequenceExpression":
            switch (parent.type) {
              case "ForStatement":
                return false;
              case "ExpressionStatement":
                return this.name !== "expression";
              default:
                return true;
            }
          case "YieldExpression":
            switch (parent.type) {
              case "BinaryExpression":
              case "LogicalExpression":
              case "UnaryExpression":
              case "SpreadElement":
              case "SpreadProperty":
              case "CallExpression":
              case "MemberExpression":
              case "NewExpression":
              case "ConditionalExpression":
              case "YieldExpression":
                return true;
              default:
                return false;
            }
          case "Literal":
            return parent.type === "MemberExpression" && isNumber.check(node.value) && this.name === "object" && parent.object === node;
          case "AssignmentExpression":
          case "ConditionalExpression":
            switch (parent.type) {
              case "UnaryExpression":
              case "SpreadElement":
              case "SpreadProperty":
              case "BinaryExpression":
              case "LogicalExpression":
                return true;
              case "CallExpression":
                return this.name === "callee" && parent.callee === node;
              case "ConditionalExpression":
                return this.name === "test" && parent.test === node;
              case "MemberExpression":
                return this.name === "object" && parent.object === node;
              default:
                return false;
            }
          default:
            if (parent.type === "NewExpression" && this.name === "callee" && parent.callee === node) {
              return containsCallExpression(node);
            }
        }
        if (assumeExpressionContext !== true && !this.canBeFirstInStatement() && this.firstInStatement())
          return true;
        return false;
      };
      function isBinary(node) {
        return n.BinaryExpression.check(node) || n.LogicalExpression.check(node);
      }
      function isUnaryLike(node) {
        return n.UnaryExpression.check(node) || n.SpreadElement && n.SpreadElement.check(node) || n.SpreadProperty && n.SpreadProperty.check(node);
      }
      var PRECEDENCE = {};
      [
        ["||"],
        ["&&"],
        ["|"],
        ["^"],
        ["&"],
        ["==", "===", "!=", "!=="],
        ["<", ">", "<=", ">=", "in", "instanceof"],
        [">>", "<<", ">>>"],
        ["+", "-"],
        ["*", "/", "%"]
      ].forEach(function(tier, i) {
        tier.forEach(function(op) {
          PRECEDENCE[op] = i;
        });
      });
      function containsCallExpression(node) {
        if (n.CallExpression.check(node)) {
          return true;
        }
        if (isArray.check(node)) {
          return node.some(containsCallExpression);
        }
        if (n.Node.check(node)) {
          return types.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(path2) {
        for (var node, parent; path2.parent; path2 = path2.parent) {
          node = path2.node;
          parent = path2.parent.node;
          if (n.BlockStatement.check(parent) && path2.parent.name === "body" && path2.name === 0) {
            if (parent.body[0] !== node) {
              throw new Error("Nodes must be equal");
            }
            return true;
          }
          if (n.ExpressionStatement.check(parent) && path2.name === "expression") {
            if (parent.expression !== node) {
              throw new Error("Nodes must be equal");
            }
            return true;
          }
          if (n.SequenceExpression.check(parent) && path2.parent.name === "expressions" && path2.name === 0) {
            if (parent.expressions[0] !== node) {
              throw new Error("Nodes must be equal");
            }
            continue;
          }
          if (n.CallExpression.check(parent) && path2.name === "callee") {
            if (parent.callee !== node) {
              throw new Error("Nodes must be equal");
            }
            continue;
          }
          if (n.MemberExpression.check(parent) && path2.name === "object") {
            if (parent.object !== node) {
              throw new Error("Nodes must be equal");
            }
            continue;
          }
          if (n.ConditionalExpression.check(parent) && path2.name === "test") {
            if (parent.test !== node) {
              throw new Error("Nodes must be equal");
            }
            continue;
          }
          if (isBinary(parent) && path2.name === "left") {
            if (parent.left !== node) {
              throw new Error("Nodes must be equal");
            }
            continue;
          }
          if (n.UnaryExpression.check(parent) && !parent.prefix && path2.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/ast-types/lib/path-visitor.js
var require_path_visitor = __commonJS({
  "node_modules/ast-types/lib/path-visitor.js"(exports2, module2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types2());
    var node_path_1 = tslib_1.__importDefault(require_node_path());
    var hasOwn = Object.prototype.hasOwnProperty;
    function pathVisitorPlugin(fork) {
      var types = fork.use(types_1.default);
      var NodePath = fork.use(node_path_1.default);
      var isArray = types.builtInTypes.array;
      var isObject = types.builtInTypes.object;
      var isFunction2 = types.builtInTypes.function;
      var undefined2;
      var PathVisitor = function PathVisitor2() {
        if (!(this instanceof PathVisitor2)) {
          throw new Error("PathVisitor constructor cannot be invoked without 'new'");
        }
        this._reusableContextStack = [];
        this._methodNameTable = computeMethodNameTable(this);
        this._shouldVisitComments = hasOwn.call(this._methodNameTable, "Block") || hasOwn.call(this._methodNameTable, "Line");
        this.Context = makeContextConstructor(this);
        this._visiting = false;
        this._changeReported = false;
      };
      function computeMethodNameTable(visitor) {
        var typeNames = /* @__PURE__ */ Object.create(null);
        for (var methodName in visitor) {
          if (/^visit[A-Z]/.test(methodName)) {
            typeNames[methodName.slice("visit".length)] = true;
          }
        }
        var supertypeTable = types.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 (isFunction2.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;
        extend(Vp, methods);
        extend(Visitor, PathVisitor);
        isFunction2.assert(Visitor.fromMethodsObject);
        isFunction2.assert(Visitor.visit);
        return new Visitor();
      };
      function extend(target, source) {
        for (var property in source) {
          if (hasOwn.call(source, property)) {
            target[property] = source[property];
          }
        }
        return target;
      }
      PathVisitor.visit = function visit(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 args2 = new Array(argc);
        for (var i = 0; i < argc; ++i) {
          args2[i] = arguments[i];
        }
        if (!(args2[0] instanceof NodePath)) {
          args2[0] = new NodePath({ root: args2[0] }).get("root");
        }
        this.reset.apply(this, args2);
        var didNotThrow;
        try {
          var root = this.visitWithoutReset(args2[0]);
          didNotThrow = true;
        } finally {
          this._visiting = false;
          if (!didNotThrow && this._abortRequested) {
            return args2[0].value;
          }
        }
        return root;
      };
      PVp.AbortRequest = function AbortRequest() {
      };
      PVp.abort = function() {
        var visitor = this;
        visitor._abortRequested = true;
        var request = new visitor.AbortRequest();
        request.cancel = function() {
          visitor._abortRequested = false;
        };
        throw request;
      };
      PVp.reset = function(_path2) {
      };
      PVp.visitWithoutReset = function(path2) {
        if (this instanceof this.Context) {
          return this.visitor.visitWithoutReset(path2);
        }
        if (!(path2 instanceof NodePath)) {
          throw new Error("");
        }
        var value = path2.value;
        var methodName = value && typeof value === "object" && typeof value.type === "string" && this._methodNameTable[value.type];
        if (methodName) {
          var context = this.acquireContext(path2);
          try {
            return context.invokeVisitorMethod(methodName);
          } finally {
            this.releaseContext(context);
          }
        } else {
          return visitChildren(path2, this);
        }
      };
      function visitChildren(path2, visitor) {
        if (!(path2 instanceof NodePath)) {
          throw new Error("");
        }
        if (!(visitor instanceof PathVisitor)) {
          throw new Error("");
        }
        var value = path2.value;
        if (isArray.check(value)) {
          path2.each(visitor.visitWithoutReset, visitor);
        } else if (!isObject.check(value)) {
        } else {
          var childNames = types.getFieldNames(value);
          if (visitor._shouldVisitComments && value.comments && childNames.indexOf("comments") < 0) {
            childNames.push("comments");
          }
          var childCount = childNames.length;
          var childPaths = [];
          for (var i = 0; i < childCount; ++i) {
            var childName = childNames[i];
            if (!hasOwn.call(value, childName)) {
              value[childName] = types.getFieldValue(value, childName);
            }
            childPaths.push(path2.get(childName));
          }
          for (var i = 0; i < childCount; ++i) {
            visitor.visitWithoutReset(childPaths[i]);
          }
        }
        return path2.value;
      }
      PVp.acquireContext = function(path2) {
        if (this._reusableContextStack.length === 0) {
          return new this.Context(path2);
        }
        return this._reusableContextStack.pop().reset(path2);
      };
      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(path2) {
          if (!(this instanceof Context)) {
            throw new Error("");
          }
          if (!(this instanceof PathVisitor)) {
            throw new Error("");
          }
          if (!(path2 instanceof NodePath)) {
            throw new Error("");
          }
          Object.defineProperty(this, "visitor", {
            value: visitor,
            writable: false,
            enumerable: true,
            configurable: false
          });
          this.currentPath = path2;
          this.needToCallTraverse = true;
          Object.seal(this);
        }
        if (!(visitor instanceof PathVisitor)) {
          throw new Error("");
        }
        var Cp = Context.prototype = Object.create(visitor);
        Cp.constructor = Context;
        extend(Cp, sharedContextProtoMethods);
        return Context;
      }
      var sharedContextProtoMethods = /* @__PURE__ */ Object.create(null);
      sharedContextProtoMethods.reset = function reset(path2) {
        if (!(this instanceof this.Context)) {
          throw new Error("");
        }
        if (!(path2 instanceof NodePath)) {
          throw new Error("");
        }
        this.currentPath = path2;
        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 path2 = this.currentPath;
        return path2 && path2.value;
      };
      sharedContextProtoMethods.traverse = function traverse(path2, newVisitor) {
        if (!(this instanceof this.Context)) {
          throw new Error("");
        }
        if (!(path2 instanceof NodePath)) {
          throw new Error("");
        }
        if (!(this.currentPath instanceof NodePath)) {
          throw new Error("");
        }
        this.needToCallTraverse = false;
        return visitChildren(path2, PathVisitor.fromMethodsObject(newVisitor || this.visitor));
      };
      sharedContextProtoMethods.visit = function visit(path2, newVisitor) {
        if (!(this instanceof this.Context)) {
          throw new Error("");
        }
        if (!(path2 instanceof NodePath)) {
          throw new Error("");
        }
        if (!(this.currentPath instanceof NodePath)) {
          throw new Error("");
        }
        this.needToCallTraverse = false;
        return PathVisitor.fromMethodsObject(newVisitor || this.visitor).visitWithoutReset(path2);
      };
      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/ast-types/lib/equiv.js
var require_equiv = __commonJS({
  "node_modules/ast-types/lib/equiv.js"(exports2, module2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types2());
    function default_1(fork) {
      var types = fork.use(types_1.default);
      var getFieldNames = types.getFieldNames;
      var getFieldValue = types.getFieldValue;
      var isArray = types.builtInTypes.array;
      var isObject = types.builtInTypes.object;
      var isDate = types.builtInTypes.Date;
      var isRegExp = types.builtInTypes.RegExp;
      var hasOwn = Object.prototype.hasOwnProperty;
      function astNodesAreEquivalent(a, b, problemPath) {
        if (isArray.check(problemPath)) {
          problemPath.length = 0;
        } else {
          problemPath = null;
        }
        return areEquivalent(a, b, problemPath);
      }
      astNodesAreEquivalent.assert = function(a, b) {
        var problemPath = [];
        if (!astNodesAreEquivalent(a, b, problemPath)) {
          if (problemPath.length === 0) {
            if (a !== b) {
              throw new Error("Nodes must be equal");
            }
          } else {
            throw new Error("Nodes differ in the following path: " + problemPath.map(subscriptForProperty).join(""));
          }
        }
      };
      function subscriptForProperty(property) {
        if (/[_$a-z][_$a-z0-9]*/i.test(property)) {
          return "." + property;
        }
        return "[" + JSON.stringify(property) + "]";
      }
      function areEquivalent(a, b, problemPath) {
        if (a === b) {
          return true;
        }
        if (isArray.check(a)) {
          return arraysAreEquivalent(a, b, problemPath);
        }
        if (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) {
        isArray.assert(a);
        var aLength = a.length;
        if (!isArray.check(b) || b.length !== aLength) {
          if (problemPath) {
            problemPath.push("length");
          }
          return false;
        }
        for (var i = 0; i < aLength; ++i) {
          if (problemPath) {
            problemPath.push(i);
          }
          if (i in a !== i in b) {
            return false;
          }
          if (!areEquivalent(a[i], b[i], problemPath)) {
            return false;
          }
          if (problemPath) {
            var problemPathTail = problemPath.pop();
            if (problemPathTail !== i) {
              throw new Error("" + problemPathTail);
            }
          }
        }
        return true;
      }
      function objectsAreEquivalent(a, b, problemPath) {
        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 (!hasOwn.call(seenNames, name)) {
            problemPath.push(name);
            return false;
          }
          delete seenNames[name];
        }
        for (name in seenNames) {
          problemPath.push(name);
          break;
        }
        return false;
      }
      return astNodesAreEquivalent;
    }
    exports2.default = default_1;
    module2.exports = exports2["default"];
  }
});

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

// node_modules/ast-types/lib/shared.js
var require_shared = __commonJS({
  "node_modules/ast-types/lib/shared.js"(exports2, module2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types2());
    function default_1(fork) {
      var types = fork.use(types_1.default);
      var Type = types.Type;
      var builtin = types.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/ast-types/def/core.js
var require_core = __commonJS({
  "node_modules/ast-types/def/core.js"(exports2, module2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types2());
    var shared_1 = tslib_1.__importDefault(require_shared());
    function default_1(fork) {
      var types = fork.use(types_1.default);
      var Type = types.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/ast-types/def/es6.js
var require_es6 = __commonJS({
  "node_modules/ast-types/def/es6.js"(exports2, module2) {
    "use strict";
    init_prefix();
    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_types2());
    var shared_1 = tslib_1.__importDefault(require_shared());
    function default_1(fork) {
      fork.use(core_1.default);
      var types = fork.use(types_1.default);
      var def = types.Type.def;
      var or = types.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/ast-types/def/es7.js
var require_es7 = __commonJS({
  "node_modules/ast-types/def/es7.js"(exports2, module2) {
    "use strict";
    init_prefix();
    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_types2());
    var shared_1 = tslib_1.__importDefault(require_shared());
    function default_1(fork) {
      fork.use(es6_1.default);
      var types = fork.use(types_1.default);
      var def = types.Type.def;
      var or = types.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/ast-types/def/es2020.js
var require_es2020 = __commonJS({
  "node_modules/ast-types/def/es2020.js"(exports2, module2) {
    "use strict";
    init_prefix();
    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_types2());
    function default_1(fork) {
      fork.use(es7_1.default);
      var types = fork.use(types_1.default);
      var def = types.Type.def;
      def("ImportExpression").bases("Expression").build("source").field("source", def("Expression"));
    }
    exports2.default = default_1;
    module2.exports = exports2["default"];
  }
});

// node_modules/ast-types/def/jsx.js
var require_jsx = __commonJS({
  "node_modules/ast-types/def/jsx.js"(exports2, module2) {
    "use strict";
    init_prefix();
    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_types2());
    var shared_1 = tslib_1.__importDefault(require_shared());
    function default_1(fork) {
      fork.use(es7_1.default);
      var types = fork.use(types_1.default);
      var def = types.Type.def;
      var or = types.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/ast-types/def/type-annotations.js
var require_type_annotations = __commonJS({
  "node_modules/ast-types/def/type-annotations.js"(exports2, module2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types2());
    var shared_1 = tslib_1.__importDefault(require_shared());
    function default_1(fork) {
      var types = fork.use(types_1.default);
      var def = types.Type.def;
      var or = types.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/ast-types/def/flow.js
var require_flow = __commonJS({
  "node_modules/ast-types/def/flow.js"(exports2, module2) {
    "use strict";
    init_prefix();
    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_types2());
    var shared_1 = tslib_1.__importDefault(require_shared());
    function default_1(fork) {
      fork.use(es7_1.default);
      fork.use(type_annotations_1.default);
      var types = fork.use(types_1.default);
      var def = types.Type.def;
      var or = types.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/ast-types/def/esprima.js
var require_esprima2 = __commonJS({
  "node_modules/ast-types/def/esprima.js"(exports2, module2) {
    "use strict";
    init_prefix();
    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_types2());
    var shared_1 = tslib_1.__importDefault(require_shared());
    function default_1(fork) {
      fork.use(es7_1.default);
      var types = fork.use(types_1.default);
      var defaults = fork.use(shared_1.default).defaults;
      var def = types.Type.def;
      var or = types.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/ast-types/def/babel-core.js
var require_babel_core = __commonJS({
  "node_modules/ast-types/def/babel-core.js"(exports2, module2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types2());
    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 types = fork.use(types_1.default);
      var defaults = fork.use(shared_1.default).defaults;
      var def = types.Type.def;
      var or = types.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/ast-types/def/babel.js
var require_babel = __commonJS({
  "node_modules/ast-types/def/babel.js"(exports2, module2) {
    "use strict";
    init_prefix();
    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/ast-types/def/typescript.js
var require_typescript = __commonJS({
  "node_modules/ast-types/def/typescript.js"(exports2, module2) {
    "use strict";
    init_prefix();
    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_types2());
    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 types = fork.use(types_1.default);
      var n = types.namedTypes;
      var def = types.Type.def;
      var or = types.Type.or;
      var defaults = fork.use(shared_1.default).defaults;
      var StringLiteral = types.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/ast-types/def/es-proposals.js
var require_es_proposals = __commonJS({
  "node_modules/ast-types/def/es-proposals.js"(exports2, module2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types2());
    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 types = fork.use(types_1.default);
      var Type = types.Type;
      var def = types.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/ast-types/gen/namedTypes.js
var require_namedTypes = __commonJS({
  "node_modules/ast-types/gen/namedTypes.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.namedTypes = void 0;
    var namedTypes;
    /* @__PURE__ */ (function(namedTypes2) {
    })(namedTypes = exports2.namedTypes || (exports2.namedTypes = {}));
  }
});

// node_modules/ast-types/main.js
var require_main = __commonJS({
  "node_modules/ast-types/main.js"(exports2) {
    "use strict";
    init_prefix();
    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 _a2 = 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 = _a2.astNodesAreEquivalent;
    var builders = _a2.builders;
    var builtInTypes = _a2.builtInTypes;
    var defineMethod = _a2.defineMethod;
    var eachField = _a2.eachField;
    var finalize = _a2.finalize;
    var getBuilderName = _a2.getBuilderName;
    var getFieldNames = _a2.getFieldNames;
    var getFieldValue = _a2.getFieldValue;
    var getSupertypeNames = _a2.getSupertypeNames;
    var n = _a2.namedTypes;
    var NodePath = _a2.NodePath;
    var Path = _a2.Path;
    var PathVisitor = _a2.PathVisitor;
    var someField = _a2.someField;
    var Type = _a2.Type;
    var use = _a2.use;
    var visit = _a2.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 = visit;
    Object.assign(namedTypes_1.namedTypes, n);
  }
});

// node_modules/degenerator/dist/degenerator.js
var require_degenerator = __commonJS({
  "node_modules/degenerator/dist/degenerator.js"(exports2) {
    "use strict";
    init_prefix();
    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(path2) {
            if (path2.node.declarations) {
              for (let i = 0; i < path2.node.declarations.length; i++) {
                const declaration = path2.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(path2) {
            if (ast_types_1.namedTypes.Identifier.check(path2.node.left) && ast_types_1.namedTypes.Identifier.check(path2.node.right) && checkName(path2.node.right.name, names) && !checkName(path2.node.left.name, names)) {
              names.push(path2.node.left.name);
            }
            return false;
          },
          visitFunction(path2) {
            if (path2.node.id) {
              let shouldDegenerate = false;
              (0, ast_types_1.visit)(path2.node, {
                visitCallExpression(path3) {
                  if (checkNames(path3.node, names)) {
                    shouldDegenerate = true;
                  }
                  return false;
                }
              });
              if (!shouldDegenerate) {
                return false;
              }
              path2.node.async = true;
              if (!checkName(path2.node.id.name, names)) {
                names.push(path2.node.id.name);
              }
            }
            this.traverse(path2);
          }
        });
      } while (lastNamesLength !== names.length);
      (0, ast_types_1.visit)(ast, {
        visitCallExpression(path2) {
          if (checkNames(path2.node, names)) {
            const delegate = false;
            const { name, parent: { node: pNode } } = path2;
            const expr = ast_types_1.builders.awaitExpression(path2.node, delegate);
            if (ast_types_1.namedTypes.CallExpression.check(pNode)) {
              pNode.arguments[name] = expr;
            } else {
              pNode[name] = expr;
            }
          }
          this.traverse(path2);
        }
      });
      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/degenerator/dist/compile.js
var require_compile = __commonJS({
  "node_modules/degenerator/dist/compile.js"(exports2) {
    "use strict";
    init_prefix();
    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, (...args2) => {
            const result = value(...args2.map((arg) => quickJSHandleToHost(vm, arg)));
            vm.runtime.executePendingJobs();
            return hostToQuickJSHandle(vm, result);
          });
          fnHandle.consume((handle) => vm.setProp(vm.global, name, handle));
        }
      }
      const fnResult = vm.evalCode(`${compiled};${returnName}`, options.filename);
      const fn = vm.unwrapResult(fnResult);
      const t = vm.typeof(fn);
      if (t !== "function") {
        throw new Error(`Expected a "function" named \`${returnName}\` to be defined, but got "${t}"`);
      }
      const r = async function(...args2) {
        let promiseHandle;
        let resolvedHandle;
        try {
          const result = vm.callFunction(fn, vm.undefined, ...args2.map((arg) => hostToQuickJSHandle(vm, arg)));
          promiseHandle = vm.unwrapResult(result);
          const resolvedResultP = vm.resolvePromise(promiseHandle);
          vm.runtime.executePendingJobs();
          const resolvedResult = await resolvedResultP;
          resolvedHandle = vm.unwrapResult(resolvedResult);
          return quickJSHandleToHost(vm, resolvedHandle);
        } catch (err) {
          if (err && typeof err === "object" && "cause" in err && err.cause) {
            if (typeof err.cause === "object" && "stack" in err.cause && "name" in err.cause && "message" in err.cause && typeof err.cause.stack === "string" && typeof err.cause.name === "string" && typeof err.cause.message === "string") {
              err.cause.stack = `${err.cause.name}: ${err.cause.message}
${err.cause.stack}`;
            }
            throw err.cause;
          }
          throw err;
        } finally {
          promiseHandle?.dispose();
          resolvedHandle?.dispose();
        }
      };
      Object.defineProperty(r, "toString", {
        value: () => compiled,
        enumerable: false
      });
      return r;
    }
    exports2.compile = compile;
    function quickJSHandleToHost(vm, val) {
      return vm.dump(val);
    }
    function hostToQuickJSHandle(vm, val) {
      if (typeof val === "undefined") {
        return vm.undefined;
      } else if (val === null) {
        return vm.null;
      } else if (typeof val === "string") {
        return vm.newString(val);
      } else if (typeof val === "number") {
        return vm.newNumber(val);
      } else if (typeof val === "bigint") {
        return vm.newBigInt(val);
      } else if (typeof val === "boolean") {
        return val ? vm.true : vm.false;
      } else if (util_1.types.isPromise(val)) {
        const promise = vm.newPromise();
        promise.settled.then(vm.runtime.executePendingJobs);
        val.then((r) => {
          promise.resolve(hostToQuickJSHandle(vm, r));
        }, (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/degenerator/dist/index.js
var require_dist7 = __commonJS({
  "node_modules/degenerator/dist/index.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    __exportStar2(require_degenerator(), exports2);
    __exportStar2(require_compile(), exports2);
  }
});

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

// node_modules/pac-resolver/dist/dnsDomainIs.js
var require_dnsDomainIs = __commonJS({
  "node_modules/pac-resolver/dist/dnsDomainIs.js"(exports2) {
    "use strict";
    init_prefix();
    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/pac-resolver/dist/dnsDomainLevels.js
var require_dnsDomainLevels = __commonJS({
  "node_modules/pac-resolver/dist/dnsDomainLevels.js"(exports2) {
    "use strict";
    init_prefix();
    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/pac-resolver/dist/util.js
var require_util5 = __commonJS({
  "node_modules/pac-resolver/dist/util.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isGMT = exports2.dnsLookup = void 0;
    var dns_1 = require("dns");
    function dnsLookup(host, opts) {
      return new Promise((resolve5, reject) => {
        (0, dns_1.lookup)(host, opts, (err, res) => {
          if (err) {
            reject(err);
          } else {
            resolve5(res);
          }
        });
      });
    }
    exports2.dnsLookup = dnsLookup;
    function isGMT(v) {
      return v === "GMT";
    }
    exports2.isGMT = isGMT;
  }
});

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

// node_modules/netmask/dist/netmask4.js
var require_netmask4 = __commonJS({
  "node_modules/netmask/dist/netmask4.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Netmask4Impl = void 0;
    exports2.ip2long = ip2long;
    exports2.long2ip = long2ip;
    function long2ip(long) {
      const a = (long & 255 << 24) >>> 24;
      const b = (long & 255 << 16) >>> 16;
      const c = (long & 255 << 8) >>> 8;
      const d = long & 255;
      return [a, b, c, d].join(".");
    }
    var chr0 = "0".charCodeAt(0);
    var chra = "a".charCodeAt(0);
    var chrA = "A".charCodeAt(0);
    function parseNum(s) {
      let n = 0;
      let base = 10;
      let dmax = "9";
      let i = 0;
      if (s.length > 1 && s[i] === "0") {
        if (s[i + 1] === "x" || s[i + 1] === "X") {
          i += 2;
          base = 16;
        } else if ("0" <= s[i + 1] && s[i + 1] <= "9") {
          i++;
          base = 8;
          dmax = "7";
        }
      }
      const start = i;
      while (i < s.length) {
        if ("0" <= s[i] && s[i] <= dmax) {
          n = n * base + (s.charCodeAt(i) - chr0) >>> 0;
        } else if (base === 16) {
          if ("a" <= s[i] && s[i] <= "f") {
            n = n * base + (10 + s.charCodeAt(i) - chra) >>> 0;
          } else if ("A" <= s[i] && s[i] <= "F") {
            n = n * base + (10 + s.charCodeAt(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];
    }
    function ip2long(ip) {
      const b = [];
      for (let i = 0; i <= 3; i++) {
        if (ip.length === 0) {
          break;
        }
        if (i > 0) {
          if (ip[0] !== ".") {
            throw new Error("Invalid IP");
          }
          ip = ip.substring(1);
        }
        const [n, c] = parseNum(ip);
        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");
      }
    }
    var Netmask4Impl = class _Netmask4Impl {
      constructor(net, mask) {
        if (typeof net !== "string") {
          throw new Error("Missing `net' parameter");
        }
        let maskStr = mask;
        if (!maskStr) {
          const parts = net.split("/", 2);
          net = parts[0];
          maskStr = parts[1];
        }
        if (!maskStr) {
          maskStr = 32;
        }
        if (typeof maskStr === "string" && maskStr.indexOf(".") > -1) {
          try {
            this.maskLong = ip2long(maskStr);
          } catch (error) {
            throw new Error("Invalid mask: " + maskStr);
          }
          this.bitmask = NaN;
          for (let i = 32; i >= 0; i--) {
            if (this.maskLong === 4294967295 << 32 - i >>> 0) {
              this.bitmask = i;
              break;
            }
          }
        } else if (maskStr || maskStr === 0) {
          this.bitmask = parseInt(maskStr, 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(net) & this.maskLong) >>> 0;
        } catch (error) {
          throw new Error("Invalid net address: " + net);
        }
        if (!(this.bitmask <= 32)) {
          throw new Error("Invalid mask for ip4: " + maskStr);
        }
        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;
      }
      contains(ip) {
        if (typeof ip === "string" && (ip.indexOf("/") > 0 || ip.split(".").length !== 4)) {
          ip = new _Netmask4Impl(ip);
        }
        if (ip instanceof _Netmask4Impl) {
          return this.contains(ip.base) && this.contains(ip.broadcast || ip.last);
        } else {
          return (ip2long(ip) & this.maskLong) >>> 0 === (this.netLong & this.maskLong) >>> 0;
        }
      }
      next(count = 1) {
        return new _Netmask4Impl(long2ip(this.netLong + this.size * count), this.mask);
      }
      forEach(fn) {
        let long = ip2long(this.first);
        const lastLong = ip2long(this.last);
        let index = 0;
        while (long <= lastLong) {
          fn(long2ip(long), long, index);
          index++;
          long++;
        }
      }
      toString() {
        return this.base + "/" + this.bitmask;
      }
    };
    exports2.Netmask4Impl = Netmask4Impl;
  }
});

// node_modules/netmask/dist/netmask6.js
var require_netmask6 = __commonJS({
  "node_modules/netmask/dist/netmask6.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Netmask6Impl = void 0;
    exports2.ip6bigint = ip6bigint;
    exports2.bigint2ip6 = bigint2ip6;
    var netmask4_1 = require_netmask4();
    var MAX_IPV6 = (1n << 128n) - 1n;
    function ip6bigint(ip) {
      const zoneIdx = ip.indexOf("%");
      if (zoneIdx !== -1) {
        ip = ip.substring(0, zoneIdx);
      }
      const lastColon = ip.lastIndexOf(":");
      if (lastColon !== -1 && ip.indexOf(".", lastColon) !== -1) {
        const ipv4Part = ip.substring(lastColon + 1);
        const ipv4Long = (0, netmask4_1.ip2long)(ipv4Part);
        const ipv6Prefix = ip.substring(0, lastColon + 1) + "0:0";
        const prefixVal = parseIPv6Pure(ipv6Prefix);
        return prefixVal & ~0xffffffffn | BigInt(ipv4Long);
      }
      return parseIPv6Pure(ip);
    }
    function parseIPv6Pure(ip) {
      const doubleColonIdx = ip.indexOf("::");
      let groups;
      if (doubleColonIdx !== -1) {
        const left2 = ip.substring(0, doubleColonIdx);
        const right2 = ip.substring(doubleColonIdx + 2);
        const leftGroups = left2 === "" ? [] : left2.split(":");
        const rightGroups = right2 === "" ? [] : right2.split(":");
        const missing = 8 - leftGroups.length - rightGroups.length;
        if (missing < 0) {
          throw new Error("Invalid IPv6: too many groups");
        }
        groups = [...leftGroups, ...Array(missing).fill("0"), ...rightGroups];
      } else {
        groups = ip.split(":");
      }
      if (groups.length !== 8) {
        throw new Error("Invalid IPv6: expected 8 groups, got " + groups.length);
      }
      let result = 0n;
      for (let i = 0; i < 8; i++) {
        const g = groups[i];
        if (g.length === 0 || g.length > 4) {
          throw new Error('Invalid IPv6: bad group "' + g + '"');
        }
        const val = parseInt(g, 16);
        if (isNaN(val) || val < 0 || val > 65535) {
          throw new Error('Invalid IPv6: bad group "' + g + '"');
        }
        result = result << 16n | BigInt(val);
      }
      return result;
    }
    function bigint2ip6(n) {
      if (n < 0n || n > MAX_IPV6) {
        throw new Error("Invalid IPv6 address value");
      }
      const groups = [];
      for (let i = 0; i < 8; i++) {
        groups.unshift(Number(n & 0xffffn));
        n >>= 16n;
      }
      let bestStart = -1;
      let bestLen = 0;
      let curStart = -1;
      let curLen = 0;
      for (let i = 0; i < 8; i++) {
        if (groups[i] === 0) {
          if (curStart === -1) {
            curStart = i;
            curLen = 1;
          } else {
            curLen++;
          }
        } else {
          if (curLen > bestLen && curLen >= 2) {
            bestStart = curStart;
            bestLen = curLen;
          }
          curStart = -1;
          curLen = 0;
        }
      }
      if (curLen > bestLen && curLen >= 2) {
        bestStart = curStart;
        bestLen = curLen;
      }
      if (bestStart !== -1 && bestStart + bestLen === 8 && bestStart > 0) {
        const before = groups.slice(0, bestStart).map((g) => g.toString(16));
        return before.join(":") + "::";
      } else if (bestStart === 0) {
        const after = groups.slice(bestLen).map((g) => g.toString(16));
        return "::" + after.join(":");
      } else if (bestStart > 0) {
        const before = groups.slice(0, bestStart).map((g) => g.toString(16));
        const after = groups.slice(bestStart + bestLen).map((g) => g.toString(16));
        return before.join(":") + "::" + after.join(":");
      } else {
        return groups.map((g) => g.toString(16)).join(":");
      }
    }
    var Netmask6Impl = class _Netmask6Impl {
      constructor(net, mask) {
        if (typeof net !== "string") {
          throw new Error("Missing `net' parameter");
        }
        let prefixLen = mask;
        if (prefixLen === void 0 || prefixLen === null) {
          const slashIdx = net.indexOf("/");
          if (slashIdx !== -1) {
            prefixLen = parseInt(net.substring(slashIdx + 1), 10);
            net = net.substring(0, slashIdx);
          } else {
            prefixLen = 128;
          }
        }
        if (isNaN(prefixLen) || prefixLen < 0 || prefixLen > 128) {
          throw new Error("Invalid mask for IPv6: " + prefixLen);
        }
        this.bitmask = prefixLen;
        if (this.bitmask === 0) {
          this.maskBigint = 0n;
        } else {
          this.maskBigint = MAX_IPV6 >> BigInt(128 - this.bitmask) << BigInt(128 - this.bitmask);
        }
        try {
          this.netBigint = ip6bigint(net) & this.maskBigint;
        } catch (error) {
          throw new Error("Invalid IPv6 net address: " + net);
        }
        this.size = Number(1n << BigInt(128 - this.bitmask));
        this.base = bigint2ip6(this.netBigint);
        this.mask = bigint2ip6(this.maskBigint);
        this.hostmask = bigint2ip6(~this.maskBigint & MAX_IPV6);
        this.first = this.base;
        this.last = bigint2ip6(this.netBigint + (1n << BigInt(128 - this.bitmask)) - 1n);
        this.broadcast = void 0;
      }
      contains(ip) {
        if (typeof ip === "string") {
          if (ip.indexOf("/") > 0) {
            ip = new _Netmask6Impl(ip);
          }
        }
        if (ip instanceof _Netmask6Impl) {
          return this.contains(ip.base) && this.contains(ip.last);
        } else {
          const addr = ip6bigint(ip);
          return (addr & this.maskBigint) === this.netBigint;
        }
      }
      next(count = 1) {
        const sizeBig = 1n << BigInt(128 - this.bitmask);
        return new _Netmask6Impl(bigint2ip6(this.netBigint + sizeBig * BigInt(count)), this.bitmask);
      }
      forEach(fn) {
        let addr = this.netBigint;
        const sizeBig = 1n << BigInt(128 - this.bitmask);
        const lastAddr = this.netBigint + sizeBig - 1n;
        let index = 0;
        while (addr <= lastAddr) {
          fn(bigint2ip6(addr), Number(addr), index);
          index++;
          addr++;
        }
      }
      toString() {
        return this.base + "/" + this.bitmask;
      }
    };
    exports2.Netmask6Impl = Netmask6Impl;
  }
});

// node_modules/netmask/dist/netmask.js
var require_netmask = __commonJS({
  "node_modules/netmask/dist/netmask.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.long2ip = exports2.ip2long = exports2.Netmask = void 0;
    var netmask4_1 = require_netmask4();
    Object.defineProperty(exports2, "ip2long", { enumerable: true, get: function() {
      return netmask4_1.ip2long;
    } });
    Object.defineProperty(exports2, "long2ip", { enumerable: true, get: function() {
      return netmask4_1.long2ip;
    } });
    var netmask6_1 = require_netmask6();
    var Netmask = class _Netmask {
      constructor(net, mask) {
        if (typeof net !== "string") {
          throw new Error("Missing `net' parameter");
        }
        const addrPart = net.indexOf("/") !== -1 ? net.substring(0, net.indexOf("/")) : net;
        if (addrPart.indexOf(":") !== -1) {
          this._impl = new netmask6_1.Netmask6Impl(net, mask);
        } else {
          this._impl = new netmask4_1.Netmask4Impl(net, mask);
        }
        this.base = this._impl.base;
        this.mask = this._impl.mask;
        this.hostmask = this._impl.hostmask;
        this.bitmask = this._impl.bitmask;
        this.size = this._impl.size;
        this.first = this._impl.first;
        this.last = this._impl.last;
        this.broadcast = this._impl.broadcast;
        if (this._impl instanceof netmask4_1.Netmask4Impl) {
          this.maskLong = this._impl.maskLong;
          this.netLong = this._impl.netLong;
        } else {
          this.maskLong = 0;
          this.netLong = 0;
        }
      }
      contains(ip) {
        if (typeof ip === "string") {
          if (ip.indexOf("/") > 0) {
            ip = new _Netmask(ip);
          } else if (ip.indexOf(":") === -1 && ip.split(".").length !== 4) {
            ip = new _Netmask(ip);
          }
        }
        if (ip instanceof _Netmask) {
          return this.contains(ip.base) && this.contains(ip.broadcast || ip.last);
        }
        return this._impl.contains(ip);
      }
      next(count = 1) {
        const nextImpl = this._impl.next(count);
        const result = new _Netmask(nextImpl.base, nextImpl.bitmask);
        return result;
      }
      /** @deprecated */
      forEach(fn) {
        this._impl.forEach(fn);
      }
      toString() {
        return this._impl.toString();
      }
    };
    exports2.Netmask = Netmask;
  }
});

// node_modules/pac-resolver/dist/isInNet.js
var require_isInNet = __commonJS({
  "node_modules/pac-resolver/dist/isInNet.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var netmask_1 = require_netmask();
    var util_1 = require_util5();
    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/pac-resolver/dist/isPlainHostName.js
var require_isPlainHostName = __commonJS({
  "node_modules/pac-resolver/dist/isPlainHostName.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    function isPlainHostName(host) {
      return !/\./.test(host);
    }
    exports2.default = isPlainHostName;
  }
});

// node_modules/pac-resolver/dist/isResolvable.js
var require_isResolvable = __commonJS({
  "node_modules/pac-resolver/dist/isResolvable.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var util_1 = require_util5();
    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/pac-resolver/dist/localHostOrDomainIs.js
var require_localHostOrDomainIs = __commonJS({
  "node_modules/pac-resolver/dist/localHostOrDomainIs.js"(exports2) {
    "use strict";
    init_prefix();
    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/pac-resolver/dist/ip.js
var require_ip = __commonJS({
  "node_modules/pac-resolver/dist/ip.js"(exports2) {
    "use strict";
    init_prefix();
    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 all = 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 !all.length ? exports2.ip.loopback(family) : all[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/pac-resolver/dist/myIpAddress.js
var require_myIpAddress = __commonJS({
  "node_modules/pac-resolver/dist/myIpAddress.js"(exports2) {
    "use strict";
    init_prefix();
    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((resolve5, reject) => {
        const socket = net_1.default.connect({ host: "8.8.8.8", port: 53 });
        const onError = () => {
          resolve5(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") {
            resolve5(addr);
          } else if (addr.address) {
            resolve5(addr.address);
          } else {
            reject(new Error("Expected a `string`"));
          }
        });
      });
    }
    exports2.default = myIpAddress;
  }
});

// node_modules/pac-resolver/dist/shExpMatch.js
var require_shExpMatch = __commonJS({
  "node_modules/pac-resolver/dist/shExpMatch.js"(exports2) {
    "use strict";
    init_prefix();
    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/pac-resolver/dist/timeRange.js
var require_timeRange = __commonJS({
  "node_modules/pac-resolver/dist/timeRange.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    function timeRange() {
      const args2 = Array.prototype.slice.call(arguments);
      const lastArg = args2.pop();
      const useGMTzone = lastArg === "GMT";
      const currentDate = /* @__PURE__ */ new Date();
      if (!useGMTzone) {
        args2.push(lastArg);
      }
      let result = false;
      const noOfArgs = args2.length;
      const numericArgs = args2.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/pac-resolver/dist/weekdayRange.js
var require_weekdayRange = __commonJS({
  "node_modules/pac-resolver/dist/weekdayRange.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var util_1 = require_util5();
    var weekdays = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
    function weekdayRange(wd1, wd2, gmt) {
      let useGMTzone = false;
      let wd1Index = -1;
      let wd2Index = -1;
      let wd2IsGmt = false;
      if ((0, util_1.isGMT)(gmt)) {
        useGMTzone = true;
      } else if ((0, util_1.isGMT)(wd2)) {
        useGMTzone = true;
        wd2IsGmt = true;
      }
      wd1Index = weekdays.indexOf(wd1);
      if (!wd2IsGmt && isWeekday(wd2)) {
        wd2Index = weekdays.indexOf(wd2);
      }
      const todaysDay = getTodaysDay(useGMTzone);
      let result;
      if (wd2Index < 0) {
        result = todaysDay === wd1Index;
      } else if (wd1Index <= wd2Index) {
        result = valueInRange(wd1Index, todaysDay, wd2Index);
      } else {
        result = valueInRange(wd1Index, todaysDay, 6) || valueInRange(0, todaysDay, wd2Index);
      }
      return result;
    }
    exports2.default = weekdayRange;
    function getTodaysDay(gmt) {
      return gmt ? (/* @__PURE__ */ new Date()).getUTCDay() : (/* @__PURE__ */ new Date()).getDay();
    }
    function valueInRange(start, value, finish) {
      return start <= value && value <= finish;
    }
    function isWeekday(v) {
      if (!v)
        return false;
      return weekdays.includes(v);
    }
  }
});

// node_modules/pac-resolver/dist/index.js
var require_dist8 = __commonJS({
  "node_modules/pac-resolver/dist/index.js"(exports2) {
    "use strict";
    init_prefix();
    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(url, _host) {
        const urlObj = typeof url === "string" ? new URL(url) : url;
        const host = _host || urlObj.hostname;
        if (!host) {
          throw new TypeError("Could not determine `host`");
        }
        return resolver(urlObj.href, host);
      }
      Object.defineProperty(FindProxyForURL, "toString", {
        value: () => resolver.toString(),
        enumerable: false
      });
      return FindProxyForURL;
    }
    exports2.createPacResolver = createPacResolver;
    exports2.sandbox = Object.freeze({
      alert: (message = "") => console.log("%s", message),
      dateRange: dateRange_1.default,
      dnsDomainIs: dnsDomainIs_1.default,
      dnsDomainLevels: dnsDomainLevels_1.default,
      dnsResolve: dnsResolve_1.default,
      isInNet: isInNet_1.default,
      isPlainHostName: isPlainHostName_1.default,
      isResolvable: isResolvable_1.default,
      localHostOrDomainIs: localHostOrDomainIs_1.default,
      myIpAddress: myIpAddress_1.default,
      shExpMatch: shExpMatch_1.default,
      timeRange: timeRange_1.default,
      weekdayRange: weekdayRange_1.default
    });
    function isAsyncFunction(v) {
      if (typeof v !== "function")
        return false;
      if (v.constructor.name === "AsyncFunction")
        return true;
      if (String(v).indexOf("__awaiter(") !== -1)
        return true;
      return Boolean(v.async);
    }
  }
});

// node_modules/@tootallnate/quickjs-emscripten/dist/esmHelpers.js
var require_esmHelpers = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/esmHelpers.js"(exports2) {
    "use strict";
    init_prefix();
    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/@tootallnate/quickjs-emscripten/dist/debug.js
var require_debug2 = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/debug.js"(exports2) {
    "use strict";
    init_prefix();
    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/@tootallnate/quickjs-emscripten/dist/errors.js
var require_errors = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/errors.js"(exports2) {
    "use strict";
    init_prefix();
    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/@tootallnate/quickjs-emscripten/dist/asyncify-helpers.js
var require_asyncify_helpers = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/asyncify-helpers.js"(exports2) {
    "use strict";
    init_prefix();
    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 (...args2) => {
        const generator = fn.call(that, AwaitYield, ...args2);
        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/@tootallnate/quickjs-emscripten/dist/lifetime.js
var require_lifetime = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/lifetime.js"(exports2) {
    "use strict";
    init_prefix();
    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 Scope = class _Scope {
      constructor() {
        this._disposables = new Lifetime(/* @__PURE__ */ new Set());
      }
      /**
       * Run `block` with a new Scope instance that will be disposed after the block returns.
       * Inside `block`, call `scope.manage` on each lifetime you create to have the lifetime
       * automatically disposed after the block returns.
       *
       * @warning Do not use with async functions. Instead, use [[withScopeAsync]].
       */
      static withScope(block) {
        const scope = new _Scope();
        let blockError;
        try {
          return block(scope);
        } catch (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 = Scope;
  }
});

// node_modules/@tootallnate/quickjs-emscripten/dist/deferred-promise.js
var require_deferred_promise = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/deferred-promise.js"(exports2) {
    "use strict";
    init_prefix();
    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(args2) {
        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 = args2.context;
        this.owner = args2.context.runtime;
        this.handle = args2.promiseHandle;
        this.settled = new Promise((resolve5) => {
          this.onSettled = resolve5;
        });
        this.resolveHandle = args2.resolveHandle;
        this.rejectHandle = args2.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/@tootallnate/quickjs-emscripten/dist/memory.js
var require_memory = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/memory.js"(exports2) {
    "use strict";
    init_prefix();
    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/@tootallnate/quickjs-emscripten/dist/types-ffi.js
var require_types_ffi = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/types-ffi.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.EvalFlags = exports2.assertSync = void 0;
    function assertSync(fn) {
      return function mustBeSync(...args2) {
        const result = fn(...args2);
        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/@tootallnate/quickjs-emscripten/dist/types.js
var require_types3 = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/types.js"(exports2) {
    "use strict";
    init_prefix();
    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/@tootallnate/quickjs-emscripten/dist/context.js
var require_context = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/context.js"(exports2) {
    "use strict";
    init_prefix();
    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_types3();
    var ContextMemory = class extends memory_1.ModuleMemory {
      /** @private */
      constructor(args2) {
        super(args2.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);
        };
        args2.ownedLifetimes?.forEach((lifetime) => this.scope.manage(lifetime));
        this.owner = args2.owner;
        this.module = args2.module;
        this.ffi = args2.ffi;
        this.rt = args2.rt;
        this.ctx = this.scope.manage(args2.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(args2) {
        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 = args2.runtime;
        this.module = args2.module;
        this.ffi = args2.ffi;
        this.rt = args2.rt;
        this.ctx = args2.ctx;
        this.memory = new ContextMemory({
          ...args2,
          owner: this.runtime
        });
        args2.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((resolve5) => {
          lifetime_1.Scope.withScope((scope) => {
            const resolveHandle = scope.manage(this.newFunction("resolve", (value) => {
              resolve5({ value: value && value.dup() });
            }));
            const rejectHandle = scope.manage(this.newFunction("reject", (error) => {
              resolve5({ 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, ...args2) {
        this.runtime.assertOwned(func);
        const resultPtr = this.memory.toPointerArray(args2).consume((argsArrayPtr) => this.ffi.QTS_Call(this.ctx.value, func.value, thisVal.value, args2.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/@tootallnate/quickjs-emscripten/dist/runtime.js
var require_runtime = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/runtime.js"(exports2) {
    "use strict";
    init_prefix();
    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_types3();
    var QuickJSRuntime = class {
      /** @private */
      constructor(args2) {
        this.scope = new lifetime_1.Scope();
        this.contextMap = /* @__PURE__ */ new Map();
        this.cToHostCallbacks = {
          shouldInterrupt: (rt) => {
            if (rt !== this.rt.value) {
              throw new Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");
            }
            const fn = this.interruptHandler;
            if (!fn) {
              throw new Error("QuickJSContext had no interrupt handler");
            }
            return fn(this) ? 1 : 0;
          },
          loadModuleSource: (0, asyncify_helpers_1.maybeAsyncFn)(this, function* (awaited, rt, ctx, moduleName) {
            const moduleLoader = this.moduleLoader;
            if (!moduleLoader) {
              throw new Error("Runtime has no module loader");
            }
            if (rt !== this.rt.value) {
              throw new Error("Runtime pointer mismatch");
            }
            const context = this.contextMap.get(ctx) ?? this.newContext({
              contextPointer: ctx
            });
            try {
              const result = yield* awaited(moduleLoader(moduleName, context));
              if (typeof result === "object" && "error" in result && result.error) {
                (0, debug_1.debugLog)("cToHostLoadModule: loader returned error", result.error);
                throw result.error;
              }
              const moduleSource = typeof result === "string" ? result : "value" in result ? result.value : result;
              return this.memory.newHeapCharPointer(moduleSource).value;
            } catch (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;
            }
          })
        };
        args2.ownedLifetimes?.forEach((lifetime) => this.scope.manage(lifetime));
        this.module = args2.module;
        this.memory = new memory_1.ModuleMemory(this.module);
        this.ffi = args2.ffi;
        this.rt = args2.rt;
        this.callbacks = args2.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/@tootallnate/quickjs-emscripten/dist/module.js
var require_module = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/module.js"(exports2) {
    "use strict";
    init_prefix();
    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_types3();
    var QuickJSEmscriptenModuleCallbacks = class {
      constructor(args2) {
        this.callFunction = args2.callFunction;
        this.shouldInterrupt = args2.shouldInterrupt;
        this.loadModuleSource = args2.loadModuleSource;
        this.normalizeModule = args2.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, moduleName) => this.handleAsyncify(asyncify, () => {
            try {
              const runtimeCallbacks = this.runtimeCallbacks.get(rt);
              if (!runtimeCallbacks) {
                throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);
              }
              const loadModule = runtimeCallbacks.loadModuleSource;
              if (!loadModule) {
                throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);
              }
              return loadModule(rt, ctx, moduleName);
            } catch (error) {
              console.error("[C to host module loader error: returning null]", error);
              return 0;
            }
          }),
          normalizeModule: (asyncify, rt, ctx, moduleBaseName, moduleName) => this.handleAsyncify(asyncify, () => {
            try {
              const runtimeCallbacks = this.runtimeCallbacks.get(rt);
              if (!runtimeCallbacks) {
                throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);
              }
              const normalizeModule = runtimeCallbacks.normalizeModule;
              if (!normalizeModule) {
                throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);
              }
              return normalizeModule(rt, ctx, moduleBaseName, moduleName);
            } catch (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/@tootallnate/quickjs-emscripten/dist/context-asyncify.js
var require_context_asyncify = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/context-asyncify.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.QuickJSAsyncContext = void 0;
    var context_1 = require_context();
    var debug_1 = require_debug2();
    var types_1 = require_types3();
    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/@tootallnate/quickjs-emscripten/dist/runtime-asyncify.js
var require_runtime_asyncify = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/runtime-asyncify.js"(exports2) {
    "use strict";
    init_prefix();
    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_types3();
    var QuickJSAsyncRuntime = class extends runtime_1.QuickJSRuntime {
      /** @private */
      constructor(args2) {
        super(args2);
      }
      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/@tootallnate/quickjs-emscripten/dist/module-asyncify.js
var require_module_asyncify = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/module-asyncify.js"(exports2) {
    "use strict";
    init_prefix();
    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/@tootallnate/quickjs-emscripten/dist/generated/ffi.WASM_RELEASE_SYNC.js
var require_ffi_WASM_RELEASE_SYNC = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/generated/ffi.WASM_RELEASE_SYNC.js"(exports2) {
    "use strict";
    init_prefix();
    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/@tootallnate/quickjs-emscripten/dist/generated/emscripten-module.WASM_RELEASE_SYNC.js
var require_emscripten_module_WASM_RELEASE_SYNC = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/generated/emscripten-module.WASM_RELEASE_SYNC.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var QuickJSRaw = (() => {
      var _scriptDir = typeof document !== "undefined" && document.currentScript ? document.currentScript.src : void 0;
      if (typeof __filename !== "undefined")
        _scriptDir = _scriptDir || __filename;
      return (function(QuickJSRaw2 = {}) {
        var a;
        a || (a = typeof QuickJSRaw2 !== "undefined" ? QuickJSRaw2 : {});
        var m, n;
        a.ready = new Promise(function(b, c) {
          m = b;
          n = c;
        });
        var p = Object.assign({}, a), t = "./this.program", u = "object" == typeof window, v = "function" == typeof importScripts, w = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, x = "", y, z, A;
        if (w) {
          var fs2 = require("fs"), B = require("path");
          x = v ? B.dirname(x) + "/" : global.__original_dirname + "/";
          y = (b, c) => {
            var d = C(b);
            if (d)
              return c ? d : d.toString();
            b = b.startsWith("file://") ? new URL(b) : B.normalize(b);
            return fs2.readFileSync(b, c ? void 0 : "utf8");
          };
          A = (b) => {
            b = y(b, true);
            b.buffer || (b = new Uint8Array(b));
            return b;
          };
          z = (b, c, d) => {
            var e = C(b);
            e && c(e);
            b = b.startsWith("file://") ? new URL(b) : B.normalize(b);
            fs2.readFile(b, function(f, g) {
              f ? d(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 || v)
          v ? x = self.location.href : "undefined" != typeof document && document.currentScript && (x = document.currentScript.src), _scriptDir && (x = _scriptDir), 0 !== x.indexOf("blob:") ? x = x.substr(0, x.replace(/[?#].*/, "").lastIndexOf("/") + 1) : x = "", y = (b) => {
            try {
              var c = new XMLHttpRequest();
              c.open("GET", b, false);
              c.send(null);
              return c.responseText;
            } catch (f) {
              if (b = C(b)) {
                c = [];
                for (var d = 0; d < b.length; d++) {
                  var e = b[d];
                  255 < e && (e &= 255);
                  c.push(String.fromCharCode(e));
                }
                return c.join("");
              }
              throw f;
            }
          }, v && (A = (b) => {
            try {
              var c = new XMLHttpRequest();
              c.open("GET", b, false);
              c.responseType = "arraybuffer";
              c.send(null);
              return new Uint8Array(c.response);
            } catch (d) {
              if (b = C(b))
                return b;
              throw d;
            }
          }), z = (b, c, d) => {
            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) : d();
              }
            };
            e.onerror = d;
            e.send(null);
          };
        var aa = a.print || console.log.bind(console), D = a.printErr || console.warn.bind(console);
        Object.assign(a, 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 G, H = false, I, J, K, L;
        function M() {
          var b = G.buffer;
          a.HEAP8 = I = new Int8Array(b);
          a.HEAP16 = new Int16Array(b);
          a.HEAP32 = K = new Int32Array(b);
          a.HEAPU8 = J = new Uint8Array(b);
          a.HEAPU16 = new Uint16Array(b);
          a.HEAPU32 = L = new Uint32Array(b);
          a.HEAPF32 = new Float32Array(b);
          a.HEAPF64 = new Float64Array(b);
        }
        var ba = [], ca = [], da = [];
        function ea() {
          var b = a.preRun.shift();
          ba.unshift(b);
        }
        var N = 0, O = null, P = null;
        function F(b) {
          if (a.onAbort)
            a.onAbort(b);
          b = "Aborted(" + b + ")";
          D(b);
          H = true;
          b = new WebAssembly.RuntimeError(b + ". Build with -sASSERTIONS for more info.");
          n(b);
          throw b;
        }
        var Q = "data:application/octet-stream;base64,", R;
        R = "data:application/octet-stream;base64, ";
        if (!R.startsWith(Q)) {
          var fa = R;
          R = a.locateFile ? a.locateFile(fa, x) : x + 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 (d) {
            F(d);
          }
        }
        function ia(b) {
          if (!E && (u || v)) {
            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 (z)
              return new Promise(function(c, d) {
                z(b, function(e) {
                  c(new Uint8Array(e));
                }, d);
              });
          }
          return Promise.resolve().then(function() {
            return ha(b);
          });
        }
        function ja(b, c, d) {
          return ia(b).then(function(e) {
            return WebAssembly.instantiate(e, c);
          }).then(function(e) {
            return e;
          }).then(d, function(e) {
            D("failed to asynchronously prepare wasm: " + e);
            F(e);
          });
        }
        function ka(b, c) {
          var d = R;
          return E || "function" != typeof WebAssembly.instantiateStreaming || d.startsWith(Q) || d.startsWith("file://") || w || "function" != typeof fetch ? ja(d, b, c) : fetch(d, { 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(d, 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, d) {
          var e = c + d;
          for (d = c; b[d] && !(d >= e); )
            ++d;
          if (16 < d - c && b.buffer && la)
            return la.decode(b.subarray(c, d));
          for (e = ""; c < d; ) {
            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 h = b[c++] & 63;
                f = 224 == (f & 240) ? (f & 15) << 12 | g << 6 | h : (f & 7) << 18 | g << 12 | h << 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 T(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 U(b) {
          for (var c = 0, d = 0; d < b.length; ++d) {
            var e = b.charCodeAt(d);
            127 >= e ? c++ : 2047 >= e ? c += 2 : 55296 <= e && 57343 >= e ? (c += 4, ++d) : c += 3;
          }
          return c;
        }
        function V(b, c, d) {
          var e = J;
          if (!(0 < d))
            return 0;
          var f = c;
          d = c + d - 1;
          for (var g = 0; g < b.length; ++g) {
            var h = b.charCodeAt(g);
            if (55296 <= h && 57343 >= h) {
              var k = b.charCodeAt(++g);
              h = 65536 + ((h & 1023) << 10) | k & 1023;
            }
            if (127 >= h) {
              if (c >= d)
                break;
              e[c++] = h;
            } else {
              if (2047 >= h) {
                if (c + 1 >= d)
                  break;
                e[c++] = 192 | h >> 6;
              } else {
                if (65535 >= h) {
                  if (c + 2 >= d)
                    break;
                  e[c++] = 224 | h >> 12;
                } else {
                  if (c + 3 >= d)
                    break;
                  e[c++] = 240 | h >> 18;
                  e[c++] = 128 | h >> 12 & 63;
                }
                e[c++] = 128 | h >> 6 & 63;
              }
              e[c++] = 128 | h & 63;
            }
          }
          e[c] = 0;
          return c - f;
        }
        function qa(b) {
          var c = U(b) + 1, d = ra(c);
          d && V(b, d, c);
          return d;
        }
        var W = {};
        function sa() {
          if (!X) {
            var b = { USER: "web_user", LOGNAME: "web_user", PATH: "/", PWD: "/", HOME: "/home/web_user", LANG: ("object" == typeof navigator && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8", _: t || "./this.program" }, c;
            for (c in W)
              void 0 === W[c] ? delete b[c] : b[c] = W[c];
            var d = [];
            for (c in b)
              d.push(c + "=" + b[c]);
            X = d;
          }
          return X;
        }
        var X, ta = [null, [], []];
        function ua(b, c, d, e) {
          var f = { string: (l) => {
            var q = 0;
            if (null !== l && void 0 !== l && 0 !== l) {
              q = U(l) + 1;
              var ma = Y(q);
              V(l, ma, q);
              q = ma;
            }
            return q;
          }, array: (l) => {
            var q = Y(l.length);
            I.set(l, q);
            return q;
          } };
          b = a["_" + b];
          var g = [], h = 0;
          if (e)
            for (var k = 0; k < e.length; k++) {
              var r = f[d[k]];
              r ? (0 === h && (h = va()), g[k] = r(e[k])) : g[k] = e[k];
            }
          d = b.apply(null, g);
          return d = (function(l) {
            0 !== h && wa(h);
            return "string" === c ? T(l) : "boolean" === c ? !!l : l;
          })(d);
        }
        var xa = "function" == typeof atob ? atob : function(b) {
          var c = "", d = 0;
          b = b.replace(/[^A-Za-z0-9\+\/=]/g, "");
          do {
            var e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(b.charAt(d++));
            var f = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(b.charAt(d++));
            var g = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(b.charAt(d++));
            var h = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(b.charAt(d++));
            e = e << 2 | f >> 4;
            f = (f & 15) << 4 | g >> 2;
            var k = (g & 3) << 6 | h;
            c += String.fromCharCode(e);
            64 !== g && (c += String.fromCharCode(f));
            64 !== h && (c += String.fromCharCode(k));
          } while (d < b.length);
          return c;
        };
        function C(b) {
          if (b.startsWith(Q)) {
            b = b.slice(Q.length);
            if ("boolean" == typeof w && w) {
              var c = Buffer.from(b, "base64");
              c = new Uint8Array(c.buffer, c.byteOffset, c.byteLength);
            } else
              try {
                var d = xa(b), e = new Uint8Array(d.length);
                for (b = 0; b < d.length; ++b)
                  e[b] = d.charCodeAt(b);
                c = e;
              } catch (f) {
                throw Error("Converting base64 string to bytes failed.");
              }
            return c;
          }
        }
        var ya = {
          a: function(b, c, d, e) {
            F("Assertion failed: " + T(b) + ", at: " + [c ? T(c) : "unknown filename", d, e ? T(e) : "unknown function"]);
          },
          l: function(b, c) {
            b = new Date(1e3 * (L[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 d = b.getFullYear();
            K[c + 28 >> 2] = (0 !== d % 4 || 0 === d % 100 && 0 !== d % 400 ? pa : oa)[b.getMonth()] + b.getDate() - 1 | 0;
            K[c + 36 >> 2] = -(60 * b.getTimezoneOffset());
            d = new Date(b.getFullYear(), 6, 1).getTimezoneOffset();
            var e = new Date(b.getFullYear(), 0, 1).getTimezoneOffset();
            K[c + 32 >> 2] = (d != e && b.getTimezoneOffset() == Math.min(e, d)) | 0;
          },
          k: function(b, c, d) {
            function e(r) {
              return (r = r.toTimeString().match(/\(([A-Za-z ]+)\)$/)) ? r[1] : "GMT";
            }
            var f = (/* @__PURE__ */ new Date()).getFullYear(), g = new Date(f, 0, 1), h = new Date(f, 6, 1);
            f = g.getTimezoneOffset();
            var k = h.getTimezoneOffset();
            L[b >> 2] = 60 * Math.max(f, k);
            K[c >> 2] = Number(f != k);
            b = e(g);
            c = e(h);
            b = qa(b);
            c = qa(c);
            k < f ? (L[d >> 2] = b, L[d + 4 >> 2] = c) : (L[d >> 2] = c, L[d + 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 d = 1; 4 >= d; d *= 2) {
              var e = c * (1 + 0.2 / d);
              e = Math.min(e, b + 100663296);
              var f = Math, g = f.min;
              e = Math.max(b, e);
              e += (65536 - e % 65536) % 65536;
              a: {
                var h = G.buffer;
                try {
                  G.grow(g.call(f, 2147483648, e) - h.byteLength + 65535 >>> 16);
                  M();
                  var k = 1;
                  break a;
                } catch (r) {
                }
                k = void 0;
              }
              if (k)
                return true;
            }
            return false;
          },
          e: function(b, c) {
            var d = 0;
            sa().forEach(function(e, f) {
              var g = c + d;
              f = L[b + 4 * f >> 2] = g;
              for (g = 0; g < e.length; ++g)
                I[f++ >> 0] = e.charCodeAt(g);
              I[f >> 0] = 0;
              d += e.length + 1;
            });
            return 0;
          },
          f: function(b, c) {
            var d = sa();
            L[b >> 2] = d.length;
            var e = 0;
            d.forEach(function(f) {
              e += f.length + 1;
            });
            L[c >> 2] = e;
            return 0;
          },
          d: function() {
            return 52;
          },
          i: function() {
            return 70;
          },
          c: function(b, c, d, e) {
            for (var f = 0, g = 0; g < d; g++) {
              var h = L[c >> 2], k = L[c + 4 >> 2];
              c += 8;
              for (var r = 0; r < k; r++) {
                var l = J[h + r], q = ta[b];
                0 === l || 10 === l ? ((1 === b ? aa : D)(na(q, 0)), q.length = 0) : q.push(l);
              }
              f += k;
            }
            L[e >> 2] = f;
            return 0;
          },
          o: function(b, c, d, e, f) {
            return a.callbacks.callFunction(void 0, b, c, d, e, f);
          },
          n: function(b) {
            return a.callbacks.shouldInterrupt(void 0, b);
          },
          h: function(b, c, d) {
            d = T(d);
            return a.callbacks.loadModuleSource(void 0, b, c, d);
          },
          g: function(b, c, d, e) {
            d = T(d);
            e = T(e);
            return a.callbacks.normalizeModule(void 0, b, c, d, e);
          }
        };
        (function() {
          function b(d) {
            d = d.exports;
            a.asm = d;
            G = a.asm.p;
            M();
            ca.unshift(a.asm.q);
            N--;
            a.monitorRunDependencies && a.monitorRunDependencies(N);
            if (0 == N && (null !== O && (clearInterval(O), O = null), P)) {
              var e = P;
              P = null;
              e();
            }
            return d;
          }
          var c = { a: ya };
          N++;
          a.monitorRunDependencies && a.monitorRunDependencies(N);
          if (a.instantiateWasm)
            try {
              return a.instantiateWasm(c, b);
            } catch (d) {
              D("Module.instantiateWasm callback failed with error: " + d), n(d);
            }
          ka(c, function(d) {
            b(d.instance);
          }).catch(n);
          return {};
        })();
        var ra = a._malloc = function() {
          return (ra = a._malloc = a.asm.r).apply(null, arguments);
        };
        a._QTS_Throw = function() {
          return (a._QTS_Throw = a.asm.s).apply(null, arguments);
        };
        a._QTS_NewError = function() {
          return (a._QTS_NewError = a.asm.t).apply(null, arguments);
        };
        a._QTS_RuntimeSetMemoryLimit = function() {
          return (a._QTS_RuntimeSetMemoryLimit = a.asm.u).apply(null, arguments);
        };
        a._QTS_RuntimeComputeMemoryUsage = function() {
          return (a._QTS_RuntimeComputeMemoryUsage = a.asm.v).apply(null, arguments);
        };
        a._QTS_RuntimeDumpMemoryUsage = function() {
          return (a._QTS_RuntimeDumpMemoryUsage = a.asm.w).apply(null, arguments);
        };
        a._QTS_RecoverableLeakCheck = function() {
          return (a._QTS_RecoverableLeakCheck = a.asm.x).apply(null, arguments);
        };
        a._QTS_BuildIsSanitizeLeak = function() {
          return (a._QTS_BuildIsSanitizeLeak = a.asm.y).apply(null, arguments);
        };
        a._QTS_RuntimeSetMaxStackSize = function() {
          return (a._QTS_RuntimeSetMaxStackSize = a.asm.z).apply(null, arguments);
        };
        a._QTS_GetUndefined = function() {
          return (a._QTS_GetUndefined = a.asm.A).apply(null, arguments);
        };
        a._QTS_GetNull = function() {
          return (a._QTS_GetNull = a.asm.B).apply(null, arguments);
        };
        a._QTS_GetFalse = function() {
          return (a._QTS_GetFalse = a.asm.C).apply(null, arguments);
        };
        a._QTS_GetTrue = function() {
          return (a._QTS_GetTrue = a.asm.D).apply(null, arguments);
        };
        a._QTS_NewRuntime = function() {
          return (a._QTS_NewRuntime = a.asm.E).apply(null, arguments);
        };
        a._QTS_FreeRuntime = function() {
          return (a._QTS_FreeRuntime = a.asm.F).apply(null, arguments);
        };
        a._QTS_NewContext = function() {
          return (a._QTS_NewContext = a.asm.G).apply(null, arguments);
        };
        a._QTS_FreeContext = function() {
          return (a._QTS_FreeContext = a.asm.H).apply(null, arguments);
        };
        a._QTS_FreeValuePointer = function() {
          return (a._QTS_FreeValuePointer = a.asm.I).apply(null, arguments);
        };
        a._free = function() {
          return (a._free = a.asm.J).apply(null, arguments);
        };
        a._QTS_FreeValuePointerRuntime = function() {
          return (a._QTS_FreeValuePointerRuntime = a.asm.K).apply(null, arguments);
        };
        a._QTS_FreeVoidPointer = function() {
          return (a._QTS_FreeVoidPointer = a.asm.L).apply(null, arguments);
        };
        a._QTS_FreeCString = function() {
          return (a._QTS_FreeCString = a.asm.M).apply(null, arguments);
        };
        a._QTS_DupValuePointer = function() {
          return (a._QTS_DupValuePointer = a.asm.N).apply(null, arguments);
        };
        a._QTS_NewObject = function() {
          return (a._QTS_NewObject = a.asm.O).apply(null, arguments);
        };
        a._QTS_NewObjectProto = function() {
          return (a._QTS_NewObjectProto = a.asm.P).apply(null, arguments);
        };
        a._QTS_NewArray = function() {
          return (a._QTS_NewArray = a.asm.Q).apply(null, arguments);
        };
        a._QTS_NewFloat64 = function() {
          return (a._QTS_NewFloat64 = a.asm.R).apply(null, arguments);
        };
        a._QTS_GetFloat64 = function() {
          return (a._QTS_GetFloat64 = a.asm.S).apply(null, arguments);
        };
        a._QTS_NewString = function() {
          return (a._QTS_NewString = a.asm.T).apply(null, arguments);
        };
        a._QTS_GetString = function() {
          return (a._QTS_GetString = a.asm.U).apply(null, arguments);
        };
        a._QTS_NewSymbol = function() {
          return (a._QTS_NewSymbol = a.asm.V).apply(null, arguments);
        };
        a._QTS_GetSymbolDescriptionOrKey = function() {
          return (a._QTS_GetSymbolDescriptionOrKey = a.asm.W).apply(null, arguments);
        };
        a._QTS_IsGlobalSymbol = function() {
          return (a._QTS_IsGlobalSymbol = a.asm.X).apply(null, arguments);
        };
        a._QTS_IsJobPending = function() {
          return (a._QTS_IsJobPending = a.asm.Y).apply(null, arguments);
        };
        a._QTS_ExecutePendingJob = function() {
          return (a._QTS_ExecutePendingJob = a.asm.Z).apply(null, arguments);
        };
        a._QTS_GetProp = function() {
          return (a._QTS_GetProp = a.asm._).apply(null, arguments);
        };
        a._QTS_SetProp = function() {
          return (a._QTS_SetProp = a.asm.$).apply(null, arguments);
        };
        a._QTS_DefineProp = function() {
          return (a._QTS_DefineProp = a.asm.aa).apply(null, arguments);
        };
        a._QTS_Call = function() {
          return (a._QTS_Call = a.asm.ba).apply(null, arguments);
        };
        a._QTS_ResolveException = function() {
          return (a._QTS_ResolveException = a.asm.ca).apply(null, arguments);
        };
        a._QTS_Dump = function() {
          return (a._QTS_Dump = a.asm.da).apply(null, arguments);
        };
        a._QTS_Eval = function() {
          return (a._QTS_Eval = a.asm.ea).apply(null, arguments);
        };
        a._QTS_Typeof = function() {
          return (a._QTS_Typeof = a.asm.fa).apply(null, arguments);
        };
        a._QTS_GetGlobalObject = function() {
          return (a._QTS_GetGlobalObject = a.asm.ga).apply(null, arguments);
        };
        a._QTS_NewPromiseCapability = function() {
          return (a._QTS_NewPromiseCapability = a.asm.ha).apply(null, arguments);
        };
        a._QTS_TestStringArg = function() {
          return (a._QTS_TestStringArg = a.asm.ia).apply(null, arguments);
        };
        a._QTS_BuildIsDebug = function() {
          return (a._QTS_BuildIsDebug = a.asm.ja).apply(null, arguments);
        };
        a._QTS_BuildIsAsyncify = function() {
          return (a._QTS_BuildIsAsyncify = a.asm.ka).apply(null, arguments);
        };
        a._QTS_NewFunction = function() {
          return (a._QTS_NewFunction = a.asm.la).apply(null, arguments);
        };
        a._QTS_ArgvGetJSValueConstPointer = function() {
          return (a._QTS_ArgvGetJSValueConstPointer = a.asm.ma).apply(null, arguments);
        };
        a._QTS_RuntimeEnableInterruptHandler = function() {
          return (a._QTS_RuntimeEnableInterruptHandler = a.asm.na).apply(null, arguments);
        };
        a._QTS_RuntimeDisableInterruptHandler = function() {
          return (a._QTS_RuntimeDisableInterruptHandler = a.asm.oa).apply(null, arguments);
        };
        a._QTS_RuntimeEnableModuleLoader = function() {
          return (a._QTS_RuntimeEnableModuleLoader = a.asm.pa).apply(null, arguments);
        };
        a._QTS_RuntimeDisableModuleLoader = function() {
          return (a._QTS_RuntimeDisableModuleLoader = a.asm.qa).apply(null, arguments);
        };
        function va() {
          return (va = a.asm.sa).apply(null, arguments);
        }
        function wa() {
          return (wa = a.asm.ta).apply(null, arguments);
        }
        function Y() {
          return (Y = a.asm.ua).apply(null, arguments);
        }
        a.___start_em_js = 74916;
        a.___stop_em_js = 75818;
        a.cwrap = function(b, c, d, e) {
          var f = !d || d.every((g) => "number" === g || "boolean" === g);
          return "string" !== c && f && !e ? a["_" + b] : function() {
            return ua(b, c, d, arguments);
          };
        };
        a.UTF8ToString = T;
        a.stringToUTF8 = function(b, c, d) {
          return V(b, c, d);
        };
        a.lengthBytesUTF8 = U;
        var Z;
        P = function za() {
          Z || Aa();
          Z || (P = za);
        };
        function Aa() {
          function b() {
            if (!Z && (Z = true, a.calledRun = true, !H)) {
              S(ca);
              m(a);
              if (a.onRuntimeInitialized)
                a.onRuntimeInitialized();
              if (a.postRun)
                for ("function" == typeof a.postRun && (a.postRun = [a.postRun]); a.postRun.length; ) {
                  var 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/@tootallnate/quickjs-emscripten/dist/variants.js
var require_variants = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/variants.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RELEASE_ASYNC = exports2.DEBUG_ASYNC = exports2.RELEASE_SYNC = exports2.DEBUG_SYNC = exports2.memoizePromiseFactory = exports2.newQuickJSAsyncWASMModule = exports2.newQuickJSWASMModule = void 0;
    var esmHelpers_1 = require_esmHelpers();
    async function newQuickJSWASMModule(variant = exports2.RELEASE_SYNC) {
      const [wasmModuleLoader, QuickJSFFI, { QuickJSWASMModule }] = await Promise.all([
        variant.importModuleLoader(),
        variant.importFFI(),
        Promise.resolve().then(() => __importStar2(require_module())).then(esmHelpers_1.unwrapTypescript)
      ]);
      const wasmModule = await wasmModuleLoader();
      wasmModule.type = "sync";
      const ffi = new QuickJSFFI(wasmModule);
      return new QuickJSWASMModule(wasmModule, ffi);
    }
    exports2.newQuickJSWASMModule = newQuickJSWASMModule;
    async function newQuickJSAsyncWASMModule(variant = exports2.RELEASE_ASYNC) {
      const [wasmModuleLoader, QuickJSAsyncFFI, { QuickJSAsyncWASMModule }] = await Promise.all([
        variant.importModuleLoader(),
        variant.importFFI(),
        Promise.resolve().then(() => __importStar2(require_module_asyncify())).then(esmHelpers_1.unwrapTypescript)
      ]);
      const wasmModule = await wasmModuleLoader();
      wasmModule.type = "async";
      const ffi = new QuickJSAsyncFFI(wasmModule);
      return new QuickJSAsyncWASMModule(wasmModule, ffi);
    }
    exports2.newQuickJSAsyncWASMModule = newQuickJSAsyncWASMModule;
    function memoizePromiseFactory(fn) {
      let 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/@tootallnate/quickjs-emscripten/dist/vm-interface.js
var require_vm_interface = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/vm-interface.js"(exports2) {
    "use strict";
    init_prefix();
    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/@tootallnate/quickjs-emscripten/dist/module-test.js
var require_module_test = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/module-test.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.TestQuickJSWASMModule = void 0;
    var errors_1 = require_errors();
    var lifetime_1 = require_lifetime();
    var TestQuickJSWASMModule = class {
      constructor(parent) {
        this.parent = parent;
        this.contexts = /* @__PURE__ */ new Set();
        this.runtimes = /* @__PURE__ */ new Set();
      }
      newRuntime(options) {
        const runtime = this.parent.newRuntime({
          ...options,
          ownedLifetimes: [
            new lifetime_1.Lifetime(void 0, void 0, () => this.runtimes.delete(runtime)),
            ...options?.ownedLifetimes ?? []
          ]
        });
        this.runtimes.add(runtime);
        return runtime;
      }
      newContext(options) {
        const context = this.parent.newContext({
          ...options,
          ownedLifetimes: [
            new lifetime_1.Lifetime(void 0, void 0, () => this.contexts.delete(context)),
            ...options?.ownedLifetimes ?? []
          ]
        });
        this.contexts.add(context);
        return context;
      }
      evalCode(code, options) {
        return this.parent.evalCode(code, options);
      }
      disposeAll() {
        const allDisposables = [...this.contexts, ...this.runtimes];
        this.runtimes.clear();
        this.contexts.clear();
        allDisposables.forEach((d) => {
          if (d.alive) {
            d.dispose();
          }
        });
      }
      assertNoMemoryAllocated() {
        const leaksDetected = this.getFFI().QTS_RecoverableLeakCheck();
        if (leaksDetected) {
          throw new errors_1.QuickJSMemoryLeakDetected("Leak sanitizer detected un-freed memory");
        }
        if (this.contexts.size > 0) {
          throw new errors_1.QuickJSMemoryLeakDetected(`${this.contexts.size} contexts leaked`);
        }
        if (this.runtimes.size > 0) {
          throw new errors_1.QuickJSMemoryLeakDetected(`${this.runtimes.size} runtimes leaked`);
        }
      }
      /** @private */
      getFFI() {
        return this.parent.getFFI();
      }
    };
    exports2.TestQuickJSWASMModule = TestQuickJSWASMModule;
  }
});

// node_modules/@tootallnate/quickjs-emscripten/dist/index.js
var require_dist9 = __commonJS({
  "node_modules/@tootallnate/quickjs-emscripten/dist/index.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, 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/pac-proxy-agent/dist/index.js
var require_dist10 = __commonJS({
  "node_modules/pac-proxy-agent/dist/index.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PacProxyAgent = void 0;
    var net = __importStar2(require("net"));
    var tls = __importStar2(require("tls"));
    var crypto = __importStar2(require("crypto"));
    var events_1 = require("events");
    var debug_1 = __importDefault2(require_src());
    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 debug = (0, debug_1.default)("pac-proxy-agent");
    var setServernameFromNonIpHost = (options) => {
      if (options.servername === void 0 && options.host && !net.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, ""));
        debug("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 = crypto.createHash("sha1").update(code).digest("hex");
          if (this.resolver && this.resolverHash === hash) {
            debug("Same sha1 hash for code - contents have not changed, reusing previous proxy resolver");
            return this.resolver;
          }
          debug("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") {
            debug("Got ENOTMODIFIED response, reusing previous proxy resolver");
            return this.resolver;
          }
          throw err;
        }
      }
      /**
       * Loads the contents of the PAC proxy file.
       *
       * @api private
       */
      async loadPacFile() {
        debug("Loading PAC file: %o", this.uri);
        const rs = await (0, get_uri_1.getUri)(this.uri, { ...this.opts, cache: this.cache });
        debug("Got `Readable` instance for URI");
        this.cache = rs;
        const buf = await (0, agent_base_1.toBuffer)(rs);
        debug("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 && net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
        const defaultPort = secureEndpoint ? 443 : 80;
        const url = Object.assign(new url_1.URL(req.path, `${protocol}//${host}`), defaultPort ? void 0 : { port: opts.port });
        debug("url: %s", url);
        let result = await resolver(url);
        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+/);
          debug("Attempting to use proxy: %o", proxy);
          if (type === "DIRECT") {
            if (secureEndpoint) {
              socket = tls.connect(setServernameFromNonIpHost(opts));
            } else {
              socket = net.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 net.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) {
            debug("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/proxy-agent/dist/index.js
var require_dist11 = __commonJS({
  "node_modules/proxy-agent/dist/index.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ProxyAgent = exports2.proxies = void 0;
    var http = __importStar2(require("http"));
    var https = __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_src());
    var proxy_from_env_1 = require_proxy_from_env();
    var debug = (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(v) {
      return Object.keys(exports2.proxies).includes(v);
    }
    var ProxyAgent = class extends agent_base_1.Agent {
      constructor(opts) {
        super(opts);
        this.cache = new lru_cache_1.default({
          max: 20,
          dispose: (agent) => agent.destroy()
        });
        debug("Creating new ProxyAgent instance: %o", opts);
        this.connectOpts = opts;
        this.httpAgent = opts?.httpAgent || new http.Agent(opts);
        this.httpsAgent = opts?.httpsAgent || new https.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 url = new url_1.URL(req.path, `${protocol}//${host}`).href;
        const proxy = await this.getProxyForUrl(url, req);
        if (!proxy) {
          debug("Proxy not enabled for URL: %o", url);
          return secureEndpoint ? this.httpsAgent : this.httpAgent;
        }
        debug("Request URL: %o", url);
        debug("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 {
          debug("Cache hit for proxy URL: %o", proxy);
        }
        return agent;
      }
      destroy() {
        for (const agent of this.cache.values()) {
          agent.destroy();
        }
        super.destroy();
      }
    };
    exports2.ProxyAgent = ProxyAgent;
  }
});

// node_modules/@puppeteer/browsers/lib/cjs/httpUtil.js
var require_httpUtil = __commonJS({
  "node_modules/@puppeteer/browsers/lib/cjs/httpUtil.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
      var ownKeys2 = function(o) {
        ownKeys2 = 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 ownKeys2(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]);
        }
        __setModuleDefault2(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.headHttpRequest = headHttpRequest;
    exports2.httpRequest = httpRequest;
    exports2.downloadFile = downloadFile;
    exports2.getJSON = getJSON;
    exports2.getText = getText2;
    var node_fs_1 = require("node:fs");
    var http = __importStar2(require("node:http"));
    var https = __importStar2(require("node:https"));
    var node_url_1 = require("node:url");
    var proxy_agent_1 = require_dist11();
    function headHttpRequest(url) {
      return new Promise((resolve5) => {
        const request = httpRequest(url, "HEAD", (response) => {
          response.resume();
          resolve5(response.statusCode === 200);
        }, false);
        request.on("error", () => {
          resolve5(false);
        });
      });
    }
    function httpRequest(url, method, response, keepAlive = true) {
      const options = {
        protocol: url.protocol,
        hostname: url.hostname,
        port: url.port,
        path: url.pathname + url.search,
        method,
        headers: keepAlive ? { Connection: "keep-alive" } : void 0,
        auth: (0, node_url_1.urlToHttpOptions)(url).auth,
        agent: new proxy_agent_1.ProxyAgent()
      };
      const requestCallback = (res) => {
        if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
          httpRequest(new node_url_1.URL(res.headers.location), method, response);
          res.resume();
        } else {
          response(res);
        }
      };
      const request = options.protocol === "https:" ? https.request(options, requestCallback) : http.request(options, requestCallback);
      request.end();
      return request;
    }
    function downloadFile(url, destinationPath, progressCallback) {
      return new Promise((resolve5, reject) => {
        let downloadedBytes = 0;
        let totalBytes = 0;
        function onData(chunk) {
          downloadedBytes += chunk.length;
          progressCallback(downloadedBytes, totalBytes);
        }
        const request = httpRequest(url, "GET", (response) => {
          if (response.statusCode !== 200) {
            const error = new Error(`Download failed: server returned code ${response.statusCode}. URL: ${url}`);
            response.resume();
            reject(error);
            return;
          }
          const file = (0, node_fs_1.createWriteStream)(destinationPath);
          file.on("close", () => {
            return resolve5();
          });
          file.on("error", (error) => {
            return reject(error);
          });
          response.pipe(file);
          totalBytes = parseInt(response.headers["content-length"], 10);
          if (progressCallback) {
            response.on("data", onData);
          }
        });
        request.on("error", (error) => {
          return reject(error);
        });
      });
    }
    async function getJSON(url) {
      const text = await getText2(url);
      try {
        return JSON.parse(text);
      } catch {
        throw new Error("Could not parse JSON from " + url.toString());
      }
    }
    function getText2(url) {
      return new Promise((resolve5, reject) => {
        const request = httpRequest(url, "GET", (response) => {
          let data = "";
          if (response.statusCode && response.statusCode >= 400) {
            return reject(new Error(`Got status code ${response.statusCode}`));
          }
          response.on("data", (chunk) => {
            data += chunk;
          });
          response.on("end", () => {
            try {
              return resolve5(String(data));
            } catch {
              return reject(new Error(`Failed to read text response from ${url}`));
            }
          });
        }, false);
        request.on("error", (err) => {
          reject(err);
        });
      });
    }
  }
});

// node_modules/@puppeteer/browsers/lib/cjs/browser-data/chrome.js
var require_chrome = __commonJS({
  "node_modules/@puppeteer/browsers/lib/cjs/browser-data/chrome.js"(exports2) {
    "use strict";
    init_prefix();
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.resolveDownloadUrl = resolveDownloadUrl;
    exports2.resolveDownloadPath = resolveDownloadPath;
    exports2.relativeExecutablePath = relativeExecutablePath;
    exports2.changeBaseVersionUrlForTesting = changeBaseVersionUrlForTesting;
    exports2.resetBaseVersionUrlForTesting = resetBaseVersionUrlForTesting;
    exports2.getLastKnownGoodReleaseForChannel = getLastKnownGoodReleaseForChannel;
    exports2.getLastKnownGoodReleaseForMilestone = getLastKnownGoodReleaseForMilestone;
    exports2.getLastKnownGoodReleaseForBuild = getLastKnownGoodReleaseForBuild;
    exports2.resolveBuildId = resolveBuildId;
    exports2.resolveSystemExecutablePaths = resolveSystemExecutablePaths;
    exports2.resolveDefaultUserDataDir = resolveDefaultUserDataDir;
    exports2.compareVersions = compareVersions;
    var node_child_process_1 = require("node:child_process");
    var node_os_1 = __importDefault2(require("node:os"));
    var node_path_1 = __importDefault2(require("node:path"));
    var semver_1 = __importDefault2(require_semver2());
    var httpUtil_js_1 = require_httpUtil();
    var types_js_1 = require_types();
    function folder(platform) {
      switch (platform) {
        case types_js_1.BrowserPlatform.LINUX_ARM:
        case types_js_1.BrowserPlatform.LINUX:
          return "linux64";
        case types_js_1.BrowserPlatform.MAC_ARM:
          return "mac-arm64";
        case types_js_1.BrowserPlatform.MAC:
          return "mac-x64";
        case types_js_1.BrowserPlatform.WIN32:
          return "win32";
        case types_js_1.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 types_js_1.BrowserPlatform.MAC:
        case types_js_1.BrowserPlatform.MAC_ARM:
          return node_path_1.default.join("chrome-" + folder(platform), "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing");
        case types_js_1.BrowserPlatform.LINUX_ARM:
        case types_js_1.BrowserPlatform.LINUX:
          return node_path_1.default.join("chrome-linux64", "chrome");
        case types_js_1.BrowserPlatform.WIN32:
        case types_js_1.BrowserPlatform.WIN64:
          return node_path_1.default.join("chrome-" + folder(platform), "chrome.exe");
      }
    }
    var baseVersionUrl = "https://googlechromelabs.github.io/chrome-for-testing";
    function changeBaseVersionUrlForTesting(url) {
      baseVersionUrl = url;
    }
    function resetBaseVersionUrlForTesting() {
      baseVersionUrl = "https://googlechromelabs.github.io/chrome-for-testing";
    }
    async function getLastKnownGoodReleaseForChannel(channel) {
      const data = await (0, httpUtil_js_1.getJSON)(new URL(`${baseVersionUrl}/last-known-good-versions.json`));
      for (const channel2 of Object.keys(data.channels)) {
        data.channels[channel2.toLowerCase()] = data.channels[channel2];
        delete data.channels[channel2];
      }
      return data.channels[channel];
    }
    async function getLastKnownGoodReleaseForMilestone(milestone) {
      const data = await (0, httpUtil_js_1.getJSON)(new URL(`${baseVersionUrl}/latest-versions-per-milestone.json`));
      return data.milestones[milestone];
    }
    async function getLastKnownGoodReleaseForBuild(buildPrefix) {
      const data = await (0, httpUtil_js_1.getJSON)(new URL(`${baseVersionUrl}/latest-patch-versions-per-build.json`));
      return data.builds[buildPrefix];
    }
    async function resolveBuildId(channel) {
      if (Object.values(types_js_1.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;
    }
    var WINDOWS_ENV_PARAM_NAMES = [
      "PROGRAMFILES",
      "ProgramW6432",
      "ProgramFiles(x86)",
      // https://source.chromium.org/chromium/chromium/src/+/main:chrome/installer/mini_installer/README.md
      "LOCALAPPDATA"
    ];
    function getChromeWindowsLocation(channel, locationsPrefixes) {
      if (locationsPrefixes.size === 0) {
        throw new Error("Non of the common Windows Env variables were set");
      }
      let suffix;
      switch (channel) {
        case types_js_1.ChromeReleaseChannel.STABLE:
          suffix = "Google\\Chrome\\Application\\chrome.exe";
          break;
        case types_js_1.ChromeReleaseChannel.BETA:
          suffix = "Google\\Chrome Beta\\Application\\chrome.exe";
          break;
        case types_js_1.ChromeReleaseChannel.CANARY:
          suffix = "Google\\Chrome SxS\\Application\\chrome.exe";
          break;
        case types_js_1.ChromeReleaseChannel.DEV:
          suffix = "Google\\Chrome Dev\\Application\\chrome.exe";
          break;
      }
      return [...locationsPrefixes.values()].map((l) => {
        return node_path_1.default.win32.join(l, suffix);
      });
    }
    function getWslVariable(variable) {
      try {
        const result = (0, node_child_process_1.execSync)(`cmd.exe /c echo %${variable.toLocaleUpperCase()}%`, {
          // We need to ignore the stderr as cmd.exe
          // prints a message about wrong UNC path not supported.
          stdio: ["ignore", "pipe", "ignore"],
          encoding: "utf-8"
        }).trim();
        if (result) {
          return result;
        }
      } catch {
      }
      return;
    }
    function getWslLocation(channel) {
      const wslVersion = (0, node_child_process_1.execSync)("wslinfo --version", {
        stdio: ["ignore", "pipe", "ignore"],
        encoding: "utf-8"
      }).trim();
      if (!wslVersion) {
        throw new Error("Not in WSL or unsupported version of WSL.");
      }
      const wslPrefixes = /* @__PURE__ */ new Set();
      for (const name of WINDOWS_ENV_PARAM_NAMES) {
        const wslPrefix = getWslVariable(name);
        if (wslPrefix) {
          wslPrefixes.add(wslPrefix);
        }
      }
      const windowsPath = getChromeWindowsLocation(channel, wslPrefixes);
      return windowsPath.map((path2) => {
        return (0, node_child_process_1.execSync)(`wslpath "${path2}"`).toString().trim();
      });
    }
    function getChromeLinuxOrWslLocation(channel) {
      const locations = [];
      switch (channel) {
        case types_js_1.ChromeReleaseChannel.STABLE:
          locations.push("/opt/google/chrome/chrome");
          break;
        case types_js_1.ChromeReleaseChannel.BETA:
          locations.push("/opt/google/chrome-beta/chrome");
          break;
        case types_js_1.ChromeReleaseChannel.CANARY:
          locations.push("/opt/google/chrome-canary/chrome");
          break;
        case types_js_1.ChromeReleaseChannel.DEV:
          locations.push("/opt/google/chrome-unstable/chrome");
          break;
      }
      try {
        const wslPath = getWslLocation(channel);
        if (wslPath) {
          locations.push(...wslPath);
        }
      } catch {
      }
      return locations;
    }
    function resolveSystemExecutablePaths(platform, channel) {
      switch (platform) {
        case types_js_1.BrowserPlatform.WIN64:
        case types_js_1.BrowserPlatform.WIN32:
          const prefixLocation = new Set(WINDOWS_ENV_PARAM_NAMES.map((name) => {
            return process.env[name];
          }).filter((l) => {
            return !!l;
          }));
          prefixLocation.add("C:\\Program Files");
          prefixLocation.add("C:\\Program Files (x86)");
          prefixLocation.add("D:\\Program Files");
          prefixLocation.add("D:\\Program Files (x86)");
          return getChromeWindowsLocation(channel, prefixLocation);
        case types_js_1.BrowserPlatform.MAC_ARM:
        case types_js_1.BrowserPlatform.MAC:
          switch (channel) {
            case types_js_1.ChromeReleaseChannel.STABLE:
              return [
                "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
              ];
            case types_js_1.ChromeReleaseChannel.BETA:
              return [
                "/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta"
              ];
            case types_js_1.ChromeReleaseChannel.CANARY:
              return [
                "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary"
              ];
            case types_js_1.ChromeReleaseChannel.DEV:
              return [
                "/Applications/Google Chrome Dev.app/Contents/MacOS/Google Chrome Dev"
              ];
          }
        case types_js_1.BrowserPlatform.LINUX_ARM:
        case types_js_1.BrowserPlatform.LINUX:
          return getChromeLinuxOrWslLocation(channel);
      }
    }
    function resolveDefaultUserDataDir(platform, channel) {
      switch (platform) {
        case types_js_1.BrowserPlatform.WIN64:
        case types_js_1.BrowserPlatform.WIN32:
          switch (channel) {
            case types_js_1.ChromeReleaseChannel.STABLE:
              return node_path_1.default.join(getLocalAppDataWin(), "Google", "Chrome", "User Data");
            case types_js_1.ChromeReleaseChannel.BETA:
              return node_path_1.default.join(getLocalAppDataWin(), "Google", "Chrome Beta", "User Data");
            case types_js_1.ChromeReleaseChannel.CANARY:
              return node_path_1.default.join(getLocalAppDataWin(), "Google", "Chrome SxS", "User Data");
            case types_js_1.ChromeReleaseChannel.DEV:
              return node_path_1.default.join(getLocalAppDataWin(), "Google", "Chrome Dev", "User Data");
          }
        case types_js_1.BrowserPlatform.MAC_ARM:
        case types_js_1.BrowserPlatform.MAC:
          switch (channel) {
            case types_js_1.ChromeReleaseChannel.STABLE:
              return node_path_1.default.join(getBaseUserDataDirPathMac(), "Chrome");
            case types_js_1.ChromeReleaseChannel.BETA:
              return node_path_1.default.join(getBaseUserDataDirPathMac(), "Chrome Beta");
            case types_js_1.ChromeReleaseChannel.DEV:
              return node_path_1.default.join(getBaseUserDataDirPathMac(), "Chrome Dev");
            case types_js_1.ChromeReleaseChannel.CANARY:
              return node_path_1.default.join(getBaseUserDataDirPathMac(), "Chrome Canary");
          }
        case types_js_1.BrowserPlatform.LINUX_ARM:
        case types_js_1.BrowserPlatform.LINUX:
          switch (channel) {
            case types_js_1.ChromeReleaseChannel.STABLE:
              return node_path_1.default.join(getConfigHomeLinux(), "google-chrome");
            case types_js_1.ChromeReleaseChannel.BETA:
              return node_path_1.default.join(getConfigHomeLinux(), "google-chrome-beta");
            case types_js_1.ChromeReleaseChannel.CANARY:
              return node_path_1.default.join(getConfigHomeLinux(), "google-chrome-canary");
            case types_js_1.ChromeReleaseChannel.DEV:
              return node_path_1.default.join(getConfigHomeLinux(), "google-chrome-unstable");
          }
      }
    }
    function getLocalAppDataWin() {
      return process.env["LOCALAPPDATA"] || node_path_1.default.join(node_os_1.default.homedir(), "AppData", "Local");
    }
    function getConfigHomeLinux() {
      return process.env["CHROME_CONFIG_HOME"] || process.env["XDG_CONFIG_HOME"] || node_path_1.default.join(node_os_1.default.homedir(), ".config");
    }
    function getBaseUserDataDirPathMac() {
      return node_path_1.default.join(node_os_1.default.homedir(), "Library", "Application Support", "Google");
    }
    function compareVersions(a, b) {
      if (!semver_1.default.valid(a)) {
        throw new Error(`Version ${a} is not a valid semver version`);
      }
      if (!semver_1.default.valid(b)) {
        throw new Error(`Version ${b} is not a valid semver version`);
      }
      if (semver_1.default.gt(a, b)) {
        return 1;
      } else if (semver_1.default.lt(a, b)) {
        return -1;
      } else {
        return 0;
      }
    }
  }
});

// node_modules/@puppeteer/browsers/lib/cjs/browser-data/chrome-headless-shell.js
var require_chrome_headless_shell = __commonJS({
  "node_modules/@puppeteer/browsers/lib/cjs/browser-data/chrome-headless-shell.js"(exports2) {
    "use strict";
    init_prefix();
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.compareVersions = exports2.resolveBuildId = void 0;
    exports2.resolveDownloadUrl = resolveDownloadUrl;
    exports2.resolveDownloadPath = resolveDownloadPath;
    exports2.relativeExecutablePath = relativeExecutablePath;
    var node_path_1 = __importDefault2(require("node:path"));
    var types_js_1 = require_types();
    function folder(platform) {
      switch (platform) {
        case types_js_1.BrowserPlatform.LINUX_ARM:
        case types_js_1.BrowserPlatform.LINUX:
          return "linux64";
        case types_js_1.BrowserPlatform.MAC_ARM:
          return "mac-arm64";
        case types_js_1.BrowserPlatform.MAC:
          return "mac-x64";
        case types_js_1.BrowserPlatform.WIN32:
          return "win32";
        case types_js_1.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-headless-shell-${folder(platform)}.zip`
      ];
    }
    function relativeExecutablePath(platform, _buildId) {
      switch (platform) {
        case types_js_1.BrowserPlatform.MAC:
        case types_js_1.BrowserPlatform.MAC_ARM:
          return node_path_1.default.join("chrome-headless-shell-" + folder(platform), "chrome-headless-shell");
        case types_js_1.BrowserPlatform.LINUX_ARM:
        case types_js_1.BrowserPlatform.LINUX:
          return node_path_1.default.join("chrome-headless-shell-linux64", "chrome-headless-shell");
        case types_js_1.BrowserPlatform.WIN32:
        case types_js_1.BrowserPlatform.WIN64:
          return node_path_1.default.join("chrome-headless-shell-" + folder(platform), "chrome-headless-shell.exe");
      }
    }
    var chrome_js_1 = require_chrome();
    Object.defineProperty(exports2, "resolveBuildId", { enumerable: true, get: function() {
      return chrome_js_1.resolveBuildId;
    } });
    Object.defineProperty(exports2, "compareVersions", { enumerable: true, get: function() {
      return chrome_js_1.compareVersions;
    } });
  }
});

// node_modules/@puppeteer/browsers/lib/cjs/browser-data/chromedriver.js
var require_chromedriver = __commonJS({
  "node_modules/@puppeteer/browsers/lib/cjs/browser-data/chromedriver.js"(exports2) {
    "use strict";
    init_prefix();
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.compareVersions = exports2.resolveBuildId = void 0;
    exports2.resolveDownloadUrl = resolveDownloadUrl;
    exports2.resolveDownloadPath = resolveDownloadPath;
    exports2.relativeExecutablePath = relativeExecutablePath;
    var node_path_1 = __importDefault2(require("node:path"));
    var types_js_1 = require_types();
    function folder(platform) {
      switch (platform) {
        case types_js_1.BrowserPlatform.LINUX_ARM:
        case types_js_1.BrowserPlatform.LINUX:
          return "linux64";
        case types_js_1.BrowserPlatform.MAC_ARM:
          return "mac-arm64";
        case types_js_1.BrowserPlatform.MAC:
          return "mac-x64";
        case types_js_1.BrowserPlatform.WIN32:
          return "win32";
        case types_js_1.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), `chromedriver-${folder(platform)}.zip`];
    }
    function relativeExecutablePath(platform, _buildId) {
      switch (platform) {
        case types_js_1.BrowserPlatform.MAC:
        case types_js_1.BrowserPlatform.MAC_ARM:
          return node_path_1.default.join("chromedriver-" + folder(platform), "chromedriver");
        case types_js_1.BrowserPlatform.LINUX_ARM:
        case types_js_1.BrowserPlatform.LINUX:
          return node_path_1.default.join("chromedriver-linux64", "chromedriver");
        case types_js_1.BrowserPlatform.WIN32:
        case types_js_1.BrowserPlatform.WIN64:
          return node_path_1.default.join("chromedriver-" + folder(platform), "chromedriver.exe");
      }
    }
    var chrome_js_1 = require_chrome();
    Object.defineProperty(exports2, "resolveBuildId", { enumerable: true, get: function() {
      return chrome_js_1.resolveBuildId;
    } });
    Object.defineProperty(exports2, "compareVersions", { enumerable: true, get: function() {
      return chrome_js_1.compareVersions;
    } });
  }
});

// node_modules/@puppeteer/browsers/lib/cjs/browser-data/chromium.js
var require_chromium = __commonJS({
  "node_modules/@puppeteer/browsers/lib/cjs/browser-data/chromium.js"(exports2) {
    "use strict";
    init_prefix();
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.resolveDownloadUrl = resolveDownloadUrl;
    exports2.resolveDownloadPath = resolveDownloadPath;
    exports2.relativeExecutablePath = relativeExecutablePath;
    exports2.resolveBuildId = resolveBuildId;
    exports2.compareVersions = compareVersions;
    var node_path_1 = __importDefault2(require("node:path"));
    var httpUtil_js_1 = require_httpUtil();
    var types_js_1 = require_types();
    function archive(platform, buildId) {
      switch (platform) {
        case types_js_1.BrowserPlatform.LINUX_ARM:
        case types_js_1.BrowserPlatform.LINUX:
          return "chrome-linux";
        case types_js_1.BrowserPlatform.MAC_ARM:
        case types_js_1.BrowserPlatform.MAC:
          return "chrome-mac";
        case types_js_1.BrowserPlatform.WIN32:
        case types_js_1.BrowserPlatform.WIN64:
          return parseInt(buildId, 10) > 591479 ? "chrome-win" : "chrome-win32";
      }
    }
    function folder(platform) {
      switch (platform) {
        case types_js_1.BrowserPlatform.LINUX_ARM:
        case types_js_1.BrowserPlatform.LINUX:
          return "Linux_x64";
        case types_js_1.BrowserPlatform.MAC_ARM:
          return "Mac_Arm";
        case types_js_1.BrowserPlatform.MAC:
          return "Mac";
        case types_js_1.BrowserPlatform.WIN32:
          return "Win";
        case types_js_1.BrowserPlatform.WIN64:
          return "Win_x64";
      }
    }
    function resolveDownloadUrl(platform, buildId, baseUrl = "https://storage.googleapis.com/chromium-browser-snapshots") {
      return `${baseUrl}/${resolveDownloadPath(platform, buildId).join("/")}`;
    }
    function resolveDownloadPath(platform, buildId) {
      return [folder(platform), buildId, `${archive(platform, buildId)}.zip`];
    }
    function relativeExecutablePath(platform, _buildId) {
      switch (platform) {
        case types_js_1.BrowserPlatform.MAC:
        case types_js_1.BrowserPlatform.MAC_ARM:
          return node_path_1.default.join("chrome-mac", "Chromium.app", "Contents", "MacOS", "Chromium");
        case types_js_1.BrowserPlatform.LINUX_ARM:
        case types_js_1.BrowserPlatform.LINUX:
          return node_path_1.default.join("chrome-linux", "chrome");
        case types_js_1.BrowserPlatform.WIN32:
        case types_js_1.BrowserPlatform.WIN64:
          return node_path_1.default.join("chrome-win", "chrome.exe");
      }
    }
    async function resolveBuildId(platform) {
      return await (0, httpUtil_js_1.getText)(new URL(`https://storage.googleapis.com/chromium-browser-snapshots/${folder(platform)}/LAST_CHANGE`));
    }
    function compareVersions(a, b) {
      return Number(a) - Number(b);
    }
  }
});

// node_modules/@puppeteer/browsers/lib/cjs/browser-data/firefox.js
var require_firefox = __commonJS({
  "node_modules/@puppeteer/browsers/lib/cjs/browser-data/firefox.js"(exports2) {
    "use strict";
    init_prefix();
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.FirefoxChannel = void 0;
    exports2.resolveDownloadUrl = resolveDownloadUrl;
    exports2.resolveDownloadPath = resolveDownloadPath;
    exports2.relativeExecutablePath = relativeExecutablePath;
    exports2.changeBaseVersionUrlForTesting = changeBaseVersionUrlForTesting;
    exports2.resetBaseVersionUrlForTesting = resetBaseVersionUrlForTesting;
    exports2.resolveBuildId = resolveBuildId;
    exports2.createProfile = createProfile;
    exports2.compareVersions = compareVersions;
    var node_fs_1 = __importDefault2(require("node:fs"));
    var node_path_1 = __importDefault2(require("node:path"));
    var httpUtil_js_1 = require_httpUtil();
    var types_js_1 = require_types();
    function getFormat(buildId) {
      const majorVersion = Number(buildId.split(".").shift());
      return majorVersion >= 135 ? "xz" : "bz2";
    }
    function archiveNightly(platform, buildId) {
      switch (platform) {
        case types_js_1.BrowserPlatform.LINUX:
          return `firefox-${buildId}.en-US.linux-x86_64.tar.${getFormat(buildId)}`;
        case types_js_1.BrowserPlatform.LINUX_ARM:
          return `firefox-${buildId}.en-US.linux-aarch64.tar.${getFormat(buildId)}`;
        case types_js_1.BrowserPlatform.MAC_ARM:
        case types_js_1.BrowserPlatform.MAC:
          return `firefox-${buildId}.en-US.mac.dmg`;
        case types_js_1.BrowserPlatform.WIN32:
        case types_js_1.BrowserPlatform.WIN64:
          return `firefox-${buildId}.en-US.${platform}.zip`;
      }
    }
    function archive(platform, buildId) {
      switch (platform) {
        case types_js_1.BrowserPlatform.LINUX_ARM:
        case types_js_1.BrowserPlatform.LINUX:
          return `firefox-${buildId}.tar.${getFormat(buildId)}`;
        case types_js_1.BrowserPlatform.MAC_ARM:
        case types_js_1.BrowserPlatform.MAC:
          return `Firefox ${buildId}.dmg`;
        case types_js_1.BrowserPlatform.WIN32:
        case types_js_1.BrowserPlatform.WIN64:
          return `Firefox Setup ${buildId}.exe`;
      }
    }
    function platformName(platform) {
      switch (platform) {
        case types_js_1.BrowserPlatform.LINUX:
          return `linux-x86_64`;
        case types_js_1.BrowserPlatform.LINUX_ARM:
          return `linux-aarch64`;
        case types_js_1.BrowserPlatform.MAC_ARM:
        case types_js_1.BrowserPlatform.MAC:
          return `mac`;
        case types_js_1.BrowserPlatform.WIN32:
        case types_js_1.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 resolveDownloadUrl(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}/${resolveDownloadPath(platform, buildId).join("/")}`;
    }
    function resolveDownloadPath(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",
            archive(platform, resolvedBuildId)
          ];
      }
    }
    function relativeExecutablePath(platform, buildId) {
      const [channel] = parseBuildId(buildId);
      switch (channel) {
        case FirefoxChannel.NIGHTLY:
          switch (platform) {
            case types_js_1.BrowserPlatform.MAC_ARM:
            case types_js_1.BrowserPlatform.MAC:
              return node_path_1.default.join("Firefox Nightly.app", "Contents", "MacOS", "firefox");
            case types_js_1.BrowserPlatform.LINUX_ARM:
            case types_js_1.BrowserPlatform.LINUX:
              return node_path_1.default.join("firefox", "firefox");
            case types_js_1.BrowserPlatform.WIN32:
            case types_js_1.BrowserPlatform.WIN64:
              return node_path_1.default.join("firefox", "firefox.exe");
          }
        case FirefoxChannel.BETA:
        case FirefoxChannel.DEVEDITION:
        case FirefoxChannel.ESR:
        case FirefoxChannel.STABLE:
          switch (platform) {
            case types_js_1.BrowserPlatform.MAC_ARM:
            case types_js_1.BrowserPlatform.MAC:
              return node_path_1.default.join("Firefox.app", "Contents", "MacOS", "firefox");
            case types_js_1.BrowserPlatform.LINUX_ARM:
            case types_js_1.BrowserPlatform.LINUX:
              return node_path_1.default.join("firefox", "firefox");
            case types_js_1.BrowserPlatform.WIN32:
            case types_js_1.BrowserPlatform.WIN64:
              return node_path_1.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 || (exports2.FirefoxChannel = FirefoxChannel = {}));
    var baseVersionUrl = "https://product-details.mozilla.org/1.0";
    function changeBaseVersionUrlForTesting(url) {
      baseVersionUrl = url;
    }
    function resetBaseVersionUrlForTesting() {
      baseVersionUrl = "https://product-details.mozilla.org/1.0";
    }
    async function resolveBuildId(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 (0, httpUtil_js_1.getJSON)(new URL(`${baseVersionUrl}/firefox_versions.json`));
      const version = versions[channelToVersionKey[channel]];
      if (!version) {
        throw new Error(`Channel ${channel} is not found.`);
      }
      return channel + "_" + version;
    }
    async function createProfile(options) {
      if (!node_fs_1.default.existsSync(options.path)) {
        await node_fs_1.default.promises.mkdir(options.path, {
          recursive: true
        });
      }
      await syncPreferences({
        preferences: {
          ...defaultProfilePreferences(options.preferences),
          ...options.preferences
        },
        path: options.path
      });
    }
    function defaultProfilePreferences(extraPrefs) {
      const server = "dummy.test";
      const defaultPrefs = {
        // Make sure Shield doesn't hit the network.
        "app.normandy.api_url": "",
        // Disable Firefox old build background check
        "app.update.checkInstallTime": false,
        // Disable automatically upgrading Firefox
        "app.update.disabledForTesting": true,
        // Increase the APZ content response timeout to 1 minute
        "apz.content_response_timeout": 6e4,
        // Prevent various error message on the console
        // jest-puppeteer asserts that no error message is emitted by the console
        "browser.contentblocking.features.standard": "-tp,tpPrivate,cookieBehavior0,-cryptoTP,-fp",
        // Enable the dump function: which sends messages to the system
        // console
        // https://bugzilla.mozilla.org/show_bug.cgi?id=1543115
        "browser.dom.window.dump.enabled": true,
        // Disable topstories
        "browser.newtabpage.activity-stream.feeds.system.topstories": false,
        // Always display a blank page
        "browser.newtabpage.enabled": false,
        // Background thumbnails in particular cause grief: and disabling
        // thumbnails in general cannot hurt
        "browser.pagethumbnails.capturing_disabled": true,
        // Disable safebrowsing components.
        "browser.safebrowsing.blockedURIs.enabled": false,
        "browser.safebrowsing.downloads.enabled": false,
        "browser.safebrowsing.malware.enabled": false,
        "browser.safebrowsing.phishing.enabled": false,
        // Disable updates to search engines.
        "browser.search.update": false,
        // Do not restore the last open set of tabs if the browser has crashed
        "browser.sessionstore.resume_from_crash": false,
        // Skip check for default browser on startup
        "browser.shell.checkDefaultBrowser": false,
        // Disable newtabpage
        "browser.startup.homepage": "about:blank",
        // Do not redirect user when a milstone upgrade of Firefox is detected
        "browser.startup.homepage_override.mstone": "ignore",
        // Start with a blank page about:blank
        "browser.startup.page": 0,
        // Do not allow background tabs to be zombified on Android: otherwise for
        // tests that open additional tabs: the test harness tab itself might get
        // unloaded
        "browser.tabs.disableBackgroundZombification": false,
        // Do not warn when closing all other open tabs
        "browser.tabs.warnOnCloseOtherTabs": false,
        // Do not warn when multiple tabs will be opened
        "browser.tabs.warnOnOpen": false,
        // Do not automatically offer translations, as tests do not expect this.
        "browser.translations.automaticallyPopup": false,
        // Disable the UI tour.
        "browser.uitour.enabled": false,
        // Turn off search suggestions in the location bar so as not to trigger
        // network connections.
        "browser.urlbar.suggest.searches": false,
        // Disable first run splash page on Windows 10
        "browser.usedOnWindows10.introURL": "",
        // Do not warn on quitting Firefox
        "browser.warnOnQuit": false,
        // Defensively disable data reporting systems
        "datareporting.healthreport.documentServerURI": `http://${server}/dummy/healthreport/`,
        "datareporting.healthreport.logging.consoleEnabled": false,
        "datareporting.healthreport.service.enabled": false,
        "datareporting.healthreport.service.firstRun": false,
        "datareporting.healthreport.uploadEnabled": false,
        // Do not show datareporting policy notifications which can interfere with tests
        "datareporting.policy.dataSubmissionEnabled": false,
        "datareporting.policy.dataSubmissionPolicyBypassNotification": true,
        // DevTools JSONViewer sometimes fails to load dependencies with its require.js.
        // This doesn't affect Puppeteer but spams console (Bug 1424372)
        "devtools.jsonview.enabled": false,
        // Disable popup-blocker
        "dom.disable_open_during_load": false,
        // Enable the support for File object creation in the content process
        // Required for |Page.setFileInputFiles| protocol method.
        "dom.file.createInChild": true,
        // Disable the ProcessHangMonitor
        "dom.ipc.reportProcessHangs": false,
        // Disable slow script dialogues
        "dom.max_chrome_script_run_time": 0,
        "dom.max_script_run_time": 0,
        // Only load extensions from the application and user profile
        // AddonManager.SCOPE_PROFILE + AddonManager.SCOPE_APPLICATION
        "extensions.autoDisableScopes": 0,
        "extensions.enabledScopes": 5,
        // Disable metadata caching for installed add-ons by default
        "extensions.getAddons.cache.enabled": false,
        // Disable installing any distribution extensions or add-ons.
        "extensions.installDistroAddons": false,
        // Turn off extension updates so they do not bother tests
        "extensions.update.enabled": false,
        // Turn off extension updates so they do not bother tests
        "extensions.update.notifyUser": false,
        // Make sure opening about:addons will not hit the network
        "extensions.webservice.discoverURL": `http://${server}/dummy/discoveryURL`,
        // Allow the application to have focus even it runs in the background
        "focusmanager.testmode": true,
        // Disable useragent updates
        "general.useragent.updates.enabled": false,
        // Always use network provider for geolocation tests so we bypass the
        // macOS dialog raised by the corelocation provider
        "geo.provider.testing": true,
        // Do not scan Wifi
        "geo.wifi.scan": false,
        // No hang monitor
        "hangmonitor.timeout": 0,
        // Show chrome errors and warnings in the error console
        "javascript.options.showInConsole": true,
        // Disable download and usage of OpenH264: and Widevine plugins
        "media.gmp-manager.updateEnabled": false,
        // Disable the GFX sanity window
        "media.sanity-test.disabled": true,
        // Disable experimental feature that is only available in Nightly
        "network.cookie.sameSite.laxByDefault": false,
        // Do not prompt for temporary redirects
        "network.http.prompt-temp-redirect": false,
        // Disable speculative connections so they are not reported as leaking
        // when they are hanging around
        "network.http.speculative-parallel-limit": 0,
        // Do not automatically switch between offline and online
        "network.manage-offline-status": false,
        // Make sure SNTP requests do not hit the network
        "network.sntp.pools": server,
        // Disable Flash.
        "plugin.state.flash": 0,
        "privacy.trackingprotection.enabled": false,
        // Can be removed once Firefox 89 is no longer supported
        // https://bugzilla.mozilla.org/show_bug.cgi?id=1710839
        "remote.enabled": true,
        // Until Bug 1999693 is resolved, this preference needs to be set to allow
        // Webdriver BiDi to automatically dismiss file pickers.
        "remote.bidi.dismiss_file_pickers.enabled": true,
        // Disabled screenshots component
        "screenshots.browser.component.enabled": false,
        // Don't do network connections for mitm priming
        "security.certerrors.mitm.priming.enabled": false,
        // Local documents have access to all other local documents,
        // including directory listings
        "security.fileuri.strict_origin_policy": false,
        // Do not wait for the notification button security delay
        "security.notification_enable_delay": 0,
        // Ensure blocklist updates do not hit the network
        "services.settings.server": `http://${server}/dummy/blocklist/`,
        // Do not automatically fill sign-in forms with known usernames and
        // passwords
        "signon.autofillForms": false,
        // Disable password capture, so that tests that include forms are not
        // influenced by the presence of the persistent doorhanger notification
        "signon.rememberSignons": false,
        // Disable first-run welcome page
        "startup.homepage_welcome_url": "about:blank",
        // Disable first-run welcome page
        "startup.homepage_welcome_url.additional": "",
        // Disable browser animations (tabs, fullscreen, sliding alerts)
        "toolkit.cosmeticAnimations.enabled": false,
        // Prevent starting into safe mode after application crashes
        "toolkit.startup.max_resumed_crashes": -1
      };
      return Object.assign(defaultPrefs, extraPrefs);
    }
    async function backupFile(input) {
      if (!node_fs_1.default.existsSync(input)) {
        return;
      }
      await node_fs_1.default.promises.copyFile(input, input + ".puppeteer");
    }
    async function syncPreferences(options) {
      const prefsPath = node_path_1.default.join(options.path, "prefs.js");
      const userPath = node_path_1.default.join(options.path, "user.js");
      const lines = Object.entries(options.preferences).map(([key, value]) => {
        return `user_pref(${JSON.stringify(key)}, ${JSON.stringify(value)});`;
      });
      const result = await Promise.allSettled([
        backupFile(userPath).then(async () => {
          await node_fs_1.default.promises.writeFile(userPath, lines.join("\n"));
        }),
        backupFile(prefsPath)
      ]);
      for (const command2 of result) {
        if (command2.status === "rejected") {
          throw command2.reason;
        }
      }
    }
    function compareVersions(a, b) {
      return parseInt(a.replace(".", ""), 16) - parseInt(b.replace(".", ""), 16);
    }
  }
});

// node_modules/@puppeteer/browsers/lib/cjs/browser-data/browser-data.js
var require_browser_data = __commonJS({
  "node_modules/@puppeteer/browsers/lib/cjs/browser-data/browser-data.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
      var ownKeys2 = function(o) {
        ownKeys2 = 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 ownKeys2(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]);
        }
        __setModuleDefault2(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ChromeReleaseChannel = exports2.BrowserPlatform = exports2.Browser = exports2.versionComparators = exports2.executablePathByBrowser = exports2.downloadPaths = exports2.downloadUrls = void 0;
    exports2.resolveBuildId = resolveBuildId;
    exports2.createProfile = createProfile;
    exports2.resolveSystemExecutablePath = resolveSystemExecutablePath;
    exports2.resolveDefaultUserDataDir = resolveDefaultUserDataDir;
    exports2.resolveSystemExecutablePaths = resolveSystemExecutablePaths;
    exports2.getVersionComparator = getVersionComparator;
    var chromeHeadlessShell = __importStar2(require_chrome_headless_shell());
    var chrome2 = __importStar2(require_chrome());
    var chromedriver = __importStar2(require_chromedriver());
    var chromium = __importStar2(require_chromium());
    var firefox = __importStar2(require_firefox());
    var types_js_1 = require_types();
    Object.defineProperty(exports2, "Browser", { enumerable: true, get: function() {
      return types_js_1.Browser;
    } });
    Object.defineProperty(exports2, "BrowserPlatform", { enumerable: true, get: function() {
      return types_js_1.BrowserPlatform;
    } });
    Object.defineProperty(exports2, "ChromeReleaseChannel", { enumerable: true, get: function() {
      return types_js_1.ChromeReleaseChannel;
    } });
    exports2.downloadUrls = {
      [types_js_1.Browser.CHROMEDRIVER]: chromedriver.resolveDownloadUrl,
      [types_js_1.Browser.CHROMEHEADLESSSHELL]: chromeHeadlessShell.resolveDownloadUrl,
      [types_js_1.Browser.CHROME]: chrome2.resolveDownloadUrl,
      [types_js_1.Browser.CHROMIUM]: chromium.resolveDownloadUrl,
      [types_js_1.Browser.FIREFOX]: firefox.resolveDownloadUrl
    };
    exports2.downloadPaths = {
      [types_js_1.Browser.CHROMEDRIVER]: chromedriver.resolveDownloadPath,
      [types_js_1.Browser.CHROMEHEADLESSSHELL]: chromeHeadlessShell.resolveDownloadPath,
      [types_js_1.Browser.CHROME]: chrome2.resolveDownloadPath,
      [types_js_1.Browser.CHROMIUM]: chromium.resolveDownloadPath,
      [types_js_1.Browser.FIREFOX]: firefox.resolveDownloadPath
    };
    exports2.executablePathByBrowser = {
      [types_js_1.Browser.CHROMEDRIVER]: chromedriver.relativeExecutablePath,
      [types_js_1.Browser.CHROMEHEADLESSSHELL]: chromeHeadlessShell.relativeExecutablePath,
      [types_js_1.Browser.CHROME]: chrome2.relativeExecutablePath,
      [types_js_1.Browser.CHROMIUM]: chromium.relativeExecutablePath,
      [types_js_1.Browser.FIREFOX]: firefox.relativeExecutablePath
    };
    exports2.versionComparators = {
      [types_js_1.Browser.CHROMEDRIVER]: chromedriver.compareVersions,
      [types_js_1.Browser.CHROMEHEADLESSSHELL]: chromeHeadlessShell.compareVersions,
      [types_js_1.Browser.CHROME]: chrome2.compareVersions,
      [types_js_1.Browser.CHROMIUM]: chromium.compareVersions,
      [types_js_1.Browser.FIREFOX]: firefox.compareVersions
    };
    async function resolveBuildIdForBrowserTag(browser, platform, tag) {
      switch (browser) {
        case types_js_1.Browser.FIREFOX:
          switch (tag) {
            case types_js_1.BrowserTag.LATEST:
              return await firefox.resolveBuildId(firefox.FirefoxChannel.NIGHTLY);
            case types_js_1.BrowserTag.BETA:
              return await firefox.resolveBuildId(firefox.FirefoxChannel.BETA);
            case types_js_1.BrowserTag.NIGHTLY:
              return await firefox.resolveBuildId(firefox.FirefoxChannel.NIGHTLY);
            case types_js_1.BrowserTag.DEVEDITION:
              return await firefox.resolveBuildId(firefox.FirefoxChannel.DEVEDITION);
            case types_js_1.BrowserTag.STABLE:
              return await firefox.resolveBuildId(firefox.FirefoxChannel.STABLE);
            case types_js_1.BrowserTag.ESR:
              return await firefox.resolveBuildId(firefox.FirefoxChannel.ESR);
            case types_js_1.BrowserTag.CANARY:
            case types_js_1.BrowserTag.DEV:
              throw new Error(`${tag.toUpperCase()} is not available for Firefox`);
          }
        case types_js_1.Browser.CHROME: {
          switch (tag) {
            case types_js_1.BrowserTag.LATEST:
              return await chrome2.resolveBuildId(types_js_1.ChromeReleaseChannel.CANARY);
            case types_js_1.BrowserTag.BETA:
              return await chrome2.resolveBuildId(types_js_1.ChromeReleaseChannel.BETA);
            case types_js_1.BrowserTag.CANARY:
              return await chrome2.resolveBuildId(types_js_1.ChromeReleaseChannel.CANARY);
            case types_js_1.BrowserTag.DEV:
              return await chrome2.resolveBuildId(types_js_1.ChromeReleaseChannel.DEV);
            case types_js_1.BrowserTag.STABLE:
              return await chrome2.resolveBuildId(types_js_1.ChromeReleaseChannel.STABLE);
            case types_js_1.BrowserTag.NIGHTLY:
            case types_js_1.BrowserTag.DEVEDITION:
            case types_js_1.BrowserTag.ESR:
              throw new Error(`${tag.toUpperCase()} is not available for Chrome`);
          }
        }
        case types_js_1.Browser.CHROMEDRIVER: {
          switch (tag) {
            case types_js_1.BrowserTag.LATEST:
            case types_js_1.BrowserTag.CANARY:
              return await chromedriver.resolveBuildId(types_js_1.ChromeReleaseChannel.CANARY);
            case types_js_1.BrowserTag.BETA:
              return await chromedriver.resolveBuildId(types_js_1.ChromeReleaseChannel.BETA);
            case types_js_1.BrowserTag.DEV:
              return await chromedriver.resolveBuildId(types_js_1.ChromeReleaseChannel.DEV);
            case types_js_1.BrowserTag.STABLE:
              return await chromedriver.resolveBuildId(types_js_1.ChromeReleaseChannel.STABLE);
            case types_js_1.BrowserTag.NIGHTLY:
            case types_js_1.BrowserTag.DEVEDITION:
            case types_js_1.BrowserTag.ESR:
              throw new Error(`${tag.toUpperCase()} is not available for ChromeDriver`);
          }
        }
        case types_js_1.Browser.CHROMEHEADLESSSHELL: {
          switch (tag) {
            case types_js_1.BrowserTag.LATEST:
            case types_js_1.BrowserTag.CANARY:
              return await chromeHeadlessShell.resolveBuildId(types_js_1.ChromeReleaseChannel.CANARY);
            case types_js_1.BrowserTag.BETA:
              return await chromeHeadlessShell.resolveBuildId(types_js_1.ChromeReleaseChannel.BETA);
            case types_js_1.BrowserTag.DEV:
              return await chromeHeadlessShell.resolveBuildId(types_js_1.ChromeReleaseChannel.DEV);
            case types_js_1.BrowserTag.STABLE:
              return await chromeHeadlessShell.resolveBuildId(types_js_1.ChromeReleaseChannel.STABLE);
            case types_js_1.BrowserTag.NIGHTLY:
            case types_js_1.BrowserTag.DEVEDITION:
            case types_js_1.BrowserTag.ESR:
              throw new Error(`${tag} is not available for chrome-headless-shell`);
          }
        }
        case types_js_1.Browser.CHROMIUM:
          switch (tag) {
            case types_js_1.BrowserTag.LATEST:
              return await chromium.resolveBuildId(platform);
            case types_js_1.BrowserTag.NIGHTLY:
            case types_js_1.BrowserTag.CANARY:
            case types_js_1.BrowserTag.DEV:
            case types_js_1.BrowserTag.DEVEDITION:
            case types_js_1.BrowserTag.BETA:
            case types_js_1.BrowserTag.STABLE:
            case types_js_1.BrowserTag.ESR:
              throw new Error(`${tag} is not supported for Chromium. Use 'latest' instead.`);
          }
      }
    }
    async function resolveBuildId(browser, platform, tag) {
      const browserTag = tag;
      if (Object.values(types_js_1.BrowserTag).includes(browserTag)) {
        return await resolveBuildIdForBrowserTag(browser, platform, browserTag);
      }
      switch (browser) {
        case types_js_1.Browser.FIREFOX:
          return tag;
        case types_js_1.Browser.CHROME:
          const chromeResult = await chrome2.resolveBuildId(tag);
          if (chromeResult) {
            return chromeResult;
          }
          return tag;
        case types_js_1.Browser.CHROMEDRIVER:
          const chromeDriverResult = await chromedriver.resolveBuildId(tag);
          if (chromeDriverResult) {
            return chromeDriverResult;
          }
          return tag;
        case types_js_1.Browser.CHROMEHEADLESSSHELL:
          const chromeHeadlessShellResult = await chromeHeadlessShell.resolveBuildId(tag);
          if (chromeHeadlessShellResult) {
            return chromeHeadlessShellResult;
          }
          return tag;
        case types_js_1.Browser.CHROMIUM:
          return tag;
      }
    }
    async function createProfile(browser, opts) {
      switch (browser) {
        case types_js_1.Browser.FIREFOX:
          return await firefox.createProfile(opts);
        case types_js_1.Browser.CHROME:
        case types_js_1.Browser.CHROMIUM:
          throw new Error(`Profile creation is not support for ${browser} yet`);
      }
    }
    function resolveSystemExecutablePath(browser, platform, channel) {
      switch (browser) {
        case types_js_1.Browser.CHROMEDRIVER:
        case types_js_1.Browser.CHROMEHEADLESSSHELL:
        case types_js_1.Browser.FIREFOX:
        case types_js_1.Browser.CHROMIUM:
          throw new Error(`System browser detection is not supported for ${browser} yet.`);
        case types_js_1.Browser.CHROME:
          return chrome2.resolveSystemExecutablePaths(platform, channel)[0];
      }
    }
    function resolveDefaultUserDataDir(browser, platform, channel) {
      switch (browser) {
        case types_js_1.Browser.CHROMEDRIVER:
        case types_js_1.Browser.CHROMEHEADLESSSHELL:
        case types_js_1.Browser.FIREFOX:
        case types_js_1.Browser.CHROMIUM:
          throw new Error(`Default user dir detection is not supported for ${browser} yet.`);
        case types_js_1.Browser.CHROME:
          return chrome2.resolveDefaultUserDataDir(platform, channel);
      }
    }
    function resolveSystemExecutablePaths(browser, platform, channel) {
      switch (browser) {
        case types_js_1.Browser.CHROMEDRIVER:
        case types_js_1.Browser.CHROMEHEADLESSSHELL:
        case types_js_1.Browser.FIREFOX:
        case types_js_1.Browser.CHROMIUM:
          throw new Error(`System browser detection is not supported for ${browser} yet.`);
        case types_js_1.Browser.CHROME:
          return chrome2.resolveSystemExecutablePaths(platform, channel);
      }
    }
    function getVersionComparator(browser) {
      return exports2.versionComparators[browser];
    }
  }
});

// node_modules/@puppeteer/browsers/lib/cjs/detectPlatform.js
var require_detectPlatform = __commonJS({
  "node_modules/@puppeteer/browsers/lib/cjs/detectPlatform.js"(exports2) {
    "use strict";
    init_prefix();
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.detectBrowserPlatform = detectBrowserPlatform;
    var node_os_1 = __importDefault2(require("node:os"));
    var browser_data_js_1 = require_browser_data();
    function detectBrowserPlatform() {
      const platform = node_os_1.default.platform();
      const arch = node_os_1.default.arch();
      switch (platform) {
        case "darwin":
          return arch === "arm64" ? browser_data_js_1.BrowserPlatform.MAC_ARM : browser_data_js_1.BrowserPlatform.MAC;
        case "linux":
          return arch === "arm64" ? browser_data_js_1.BrowserPlatform.LINUX_ARM : browser_data_js_1.BrowserPlatform.LINUX;
        case "win32":
          return arch === "x64" || // Windows 11 for ARM supports x64 emulation
          arch === "arm64" && isWindows11(node_os_1.default.release()) ? browser_data_js_1.BrowserPlatform.WIN64 : browser_data_js_1.BrowserPlatform.WIN32;
        default:
          return void 0;
      }
    }
    function isWindows11(version) {
      const parts = version.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/@puppeteer/browsers/lib/cjs/Cache.js
var require_Cache = __commonJS({
  "node_modules/@puppeteer/browsers/lib/cjs/Cache.js"(exports2) {
    "use strict";
    init_prefix();
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Cache = exports2.InstalledBrowser = void 0;
    var node_fs_1 = __importDefault2(require("node:fs"));
    var node_os_1 = __importDefault2(require("node:os"));
    var node_path_1 = __importDefault2(require("node:path"));
    var debug_1 = __importDefault2(require_src());
    var browser_data_js_1 = require_browser_data();
    var detectPlatform_js_1 = require_detectPlatform();
    var debugCache = (0, debug_1.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);
      }
    };
    exports2.InstalledBrowser = InstalledBrowser;
    var Cache = class {
      #rootDir;
      constructor(rootDir) {
        this.#rootDir = rootDir;
      }
      /**
       * @internal
       */
      get rootDir() {
        return this.#rootDir;
      }
      browserRoot(browser) {
        return node_path_1.default.join(this.#rootDir, browser);
      }
      metadataFile(browser) {
        return node_path_1.default.join(this.browserRoot(browser), ".metadata");
      }
      readMetadata(browser) {
        const metatadaPath = this.metadataFile(browser);
        if (!node_fs_1.default.existsSync(metatadaPath)) {
          return { aliases: {} };
        }
        const data = JSON.parse(node_fs_1.default.readFileSync(metatadaPath, "utf8"));
        if (typeof data !== "object") {
          throw new Error(".metadata is not an object");
        }
        return data;
      }
      writeMetadata(browser, metadata) {
        const metatadaPath = this.metadataFile(browser);
        node_fs_1.default.mkdirSync(node_path_1.default.dirname(metatadaPath), { recursive: true });
        node_fs_1.default.writeFileSync(metatadaPath, JSON.stringify(metadata, null, 2));
      }
      readExecutablePath(browser, platform, buildId) {
        const metadata = this.readMetadata(browser);
        const key = `${platform}-${buildId}`;
        return metadata.executablePaths?.[key] ?? null;
      }
      writeExecutablePath(browser, platform, buildId, executablePath) {
        const metadata = this.readMetadata(browser);
        if (!metadata.executablePaths) {
          metadata.executablePaths = {};
        }
        const key = `${platform}-${buildId}`;
        metadata.executablePaths[key] = executablePath;
        this.writeMetadata(browser, metadata);
      }
      resolveAlias(browser, alias) {
        const metadata = this.readMetadata(browser);
        if (alias === "latest") {
          return Object.values(metadata.aliases || {}).sort((0, browser_data_js_1.getVersionComparator)(browser)).at(-1);
        }
        return metadata.aliases[alias];
      }
      installationDir(browser, platform, buildId) {
        return node_path_1.default.join(this.browserRoot(browser), `${platform}-${buildId}`);
      }
      clear() {
        node_fs_1.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];
          }
        }
        const key = `${platform}-${buildId}`;
        if (metadata.executablePaths?.[key]) {
          delete metadata.executablePaths[key];
          this.writeMetadata(browser, metadata);
        }
        node_fs_1.default.rmSync(this.installationDir(browser, platform, buildId), {
          force: true,
          recursive: true,
          maxRetries: 10,
          retryDelay: 500
        });
      }
      getInstalledBrowsers() {
        if (!node_fs_1.default.existsSync(this.#rootDir)) {
          return [];
        }
        const types = node_fs_1.default.readdirSync(this.#rootDir);
        const browsers = types.filter((t) => {
          return Object.values(browser_data_js_1.Browser).includes(t);
        });
        return browsers.flatMap((browser) => {
          const files = node_fs_1.default.readdirSync(this.browserRoot(browser));
          return files.map((file) => {
            const result = parseFolderPath(node_path_1.default.join(this.browserRoot(browser), file));
            if (!result) {
              return null;
            }
            return new InstalledBrowser(this, browser, result.buildId, result.platform);
          }).filter((item) => {
            return item !== null;
          });
        });
      }
      computeExecutablePath(options) {
        options.platform ??= (0, detectPlatform_js_1.detectBrowserPlatform)();
        if (!options.platform) {
          throw new Error(`Cannot download a binary for the provided platform: ${node_os_1.default.platform()} (${node_os_1.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);
        const storedExecutablePath = this.readExecutablePath(options.browser, options.platform, options.buildId);
        if (storedExecutablePath) {
          return node_path_1.default.join(installationDir, storedExecutablePath);
        }
        return node_path_1.default.join(installationDir, browser_data_js_1.executablePathByBrowser[options.browser](options.platform, options.buildId));
      }
    };
    exports2.Cache = Cache;
    function parseFolderPath(folderPath) {
      const name = node_path_1.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/@puppeteer/browsers/lib/cjs/debug.js
var require_debug3 = __commonJS({
  "node_modules/@puppeteer/browsers/lib/cjs/debug.js"(exports2) {
    "use strict";
    init_prefix();
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.debug = void 0;
    var debug_1 = __importDefault2(require_src());
    exports2.debug = debug_1.default;
  }
});

// node_modules/@puppeteer/browsers/lib/cjs/launch.js
var require_launch = __commonJS({
  "node_modules/@puppeteer/browsers/lib/cjs/launch.js"(exports2) {
    "use strict";
    init_prefix();
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.TimeoutError = exports2.Process = exports2.WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX = exports2.CDP_WEBSOCKET_ENDPOINT_REGEX = void 0;
    exports2.computeExecutablePath = computeExecutablePath;
    exports2.computeSystemExecutablePath = computeSystemExecutablePath;
    exports2.launch = launch;
    exports2.isErrorLike = isErrorLike;
    exports2.isErrnoException = isErrnoException;
    var node_child_process_1 = __importDefault2(require("node:child_process"));
    var node_events_1 = require("node:events");
    var node_fs_1 = require("node:fs");
    var node_os_1 = __importDefault2(require("node:os"));
    var node_readline_1 = __importDefault2(require("node:readline"));
    var browser_data_js_1 = require_browser_data();
    var Cache_js_1 = require_Cache();
    var debug_js_1 = require_debug3();
    var detectPlatform_js_1 = require_detectPlatform();
    var debugLaunch = (0, debug_js_1.debug)("puppeteer:browsers:launcher");
    function computeExecutablePath(options) {
      if (options.cacheDir === null) {
        options.platform ??= (0, detectPlatform_js_1.detectBrowserPlatform)();
        if (options.platform === void 0) {
          throw new Error(`No platform specified. Couldn't auto-detect browser platform.`);
        }
        return browser_data_js_1.executablePathByBrowser[options.browser](options.platform, options.buildId);
      }
      return new Cache_js_1.Cache(options.cacheDir).computeExecutablePath(options);
    }
    function computeSystemExecutablePath(options) {
      options.platform ??= (0, detectPlatform_js_1.detectBrowserPlatform)();
      if (!options.platform) {
        throw new Error(`Cannot download a binary for the provided platform: ${node_os_1.default.platform()} (${node_os_1.default.arch()})`);
      }
      const paths = (0, browser_data_js_1.resolveSystemExecutablePaths)(options.browser, options.platform, options.channel);
      for (const path2 of paths) {
        try {
          (0, node_fs_1.accessSync)(path2);
          return path2;
        } catch {
        }
      }
      throw new Error(`Could not find Google Chrome executable for channel '${options.channel}' at:${paths.map((path2) => {
        return `
 - ${path2}`;
      })}.`);
    }
    function launch(opts) {
      return new Process(opts);
    }
    exports2.CDP_WEBSOCKET_ENDPOINT_REGEX = /^DevTools listening on (ws:\/\/.*)$/;
    exports2.WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX = /^WebDriver BiDi listening on (ws:\/\/.*)$/;
    var processListeners = /* @__PURE__ */ new Map();
    var dispatchers = {
      exit: (...args2) => {
        processListeners.get("exit")?.forEach((handler) => {
          return handler(...args2);
        });
      },
      SIGINT: (...args2) => {
        processListeners.get("SIGINT")?.forEach((handler) => {
          return handler(...args2);
        });
      },
      SIGHUP: (...args2) => {
        processListeners.get("SIGHUP")?.forEach((handler) => {
          return handler(...args2);
        });
      },
      SIGTERM: (...args2) => {
        processListeners.get("SIGTERM")?.forEach((handler) => {
          return handler(...args2);
        });
      }
    };
    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;
      #logs = [];
      #maxLogLinesSize = 1e3;
      #lineEmitter = new node_events_1.EventEmitter();
      #onAbort = () => {
        this.kill();
      };
      #signal;
      constructor(opts) {
        this.#executablePath = opts.executablePath;
        this.#args = opts.args ?? [];
        this.#signal = opts.signal;
        if (this.#signal?.aborted) {
          throw new Error(this.#signal.reason ? this.#signal.reason : "Launch aborted");
        }
        this.#signal?.addEventListener("abort", this.#onAbort, { once: true });
        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
        });
        const env2 = opts.env || {};
        debugLaunch(`Launching ${this.#executablePath} ${this.#args.join(" ")}`, {
          detached: opts.detached,
          env: Object.keys(env2).reduce((res, key) => {
            if (key.toLowerCase().startsWith("puppeteer_")) {
              res[key] = env2[key];
            }
            return res;
          }, {}),
          stdio
        });
        this.#browserProcess = node_child_process_1.default.spawn(this.#executablePath, this.#args, {
          detached: opts.detached,
          env: env2,
          stdio
        });
        this.#recordStream(this.#browserProcess.stderr);
        this.#recordStream(this.#browserProcess.stdout);
        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((resolve5, 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;
            }
            resolve5();
          });
        });
      }
      async #runHooks() {
        if (this.#hooksRan) {
          return;
        }
        this.#hooksRan = true;
        await this.#onExitHook();
      }
      get nodeProcess() {
        return this.#browserProcess;
      }
      #configureStdio(opts) {
        if (opts.pipe) {
          return ["pipe", "pipe", "pipe", "pipe", "pipe"];
        } else {
          return ["pipe", "pipe", "pipe"];
        }
      }
      #clearListeners() {
        unsubscribeFromProcessEvent("exit", this.#onDriverProcessExit);
        unsubscribeFromProcessEvent("SIGINT", this.#onDriverProcessSignal);
        unsubscribeFromProcessEvent("SIGTERM", this.#onDriverProcessSignal);
        unsubscribeFromProcessEvent("SIGHUP", this.#onDriverProcessSignal);
        this.#signal?.removeEventListener("abort", this.#onAbort);
      }
      #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 {
                node_child_process_1.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();
      }
      #recordStream(stream) {
        const rl = node_readline_1.default.createInterface(stream);
        const cleanup = () => {
          rl.off("line", onLine);
          rl.off("close", onClose);
          try {
            rl.close();
          } catch {
          }
        };
        const onLine = (line) => {
          if (line.trim() === "") {
            return;
          }
          this.#logs.push(line);
          const delta = this.#logs.length - this.#maxLogLinesSize;
          if (delta) {
            this.#logs.splice(0, delta);
          }
          this.#lineEmitter.emit("line", line);
        };
        const onClose = () => {
          cleanup();
        };
        rl.on("line", onLine);
        rl.on("close", onClose);
      }
      /**
       * Get recent logs (stderr + stdout) emitted by the browser.
       *
       * @public
       */
      getRecentLogs() {
        return [...this.#logs];
      }
      waitForLineOutput(regex, timeout = 0) {
        return new Promise((resolve5, reject) => {
          const onClose = (errorOrCode) => {
            cleanup();
            reject(new Error([
              `Failed to launch the browser process: ${errorOrCode instanceof Error ? ` ${errorOrCode.message}` : ` Code: ${errorOrCode}`}`,
              "",
              `stderr:`,
              this.getRecentLogs().join("\n"),
              "",
              "TROUBLESHOOTING: https://pptr.dev/troubleshooting",
              ""
            ].join("\n")));
          };
          this.#browserProcess.on("exit", onClose);
          this.#browserProcess.on("error", onClose);
          const timeoutId = timeout > 0 ? setTimeout(onTimeout, timeout) : void 0;
          this.#lineEmitter.on("line", onLine);
          const cleanup = () => {
            clearTimeout(timeoutId);
            this.#lineEmitter.off("line", onLine);
            this.#browserProcess.off("exit", onClose);
            this.#browserProcess.off("error", onClose);
          };
          function onTimeout() {
            cleanup();
            reject(new TimeoutError(`Timed out after ${timeout} ms while waiting for the WS endpoint URL to appear in stdout!`));
          }
          for (const line of this.#logs) {
            onLine(line);
          }
          function onLine(line) {
            const match = line.match(regex);
            if (!match) {
              return;
            }
            cleanup();
            resolve5(match[1]);
          }
        });
      }
    };
    exports2.Process = Process;
    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);
      }
    };
    exports2.TimeoutError = TimeoutError;
  }
});

// node_modules/progress/lib/node-progress.js
var require_node_progress = __commonJS({
  "node_modules/progress/lib/node-progress.js"(exports2, module2) {
    init_prefix();
    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/progress/index.js
var require_progress = __commonJS({
  "node_modules/progress/index.js"(exports2, module2) {
    init_prefix();
    module2.exports = require_node_progress();
  }
});

// node_modules/@puppeteer/browsers/lib/cjs/DefaultProvider.js
var require_DefaultProvider = __commonJS({
  "node_modules/@puppeteer/browsers/lib/cjs/DefaultProvider.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.DefaultProvider = void 0;
    var browser_data_js_1 = require_browser_data();
    var DefaultProvider = class {
      #baseUrl;
      constructor(baseUrl) {
        this.#baseUrl = baseUrl;
      }
      supports(_options) {
        return true;
      }
      getDownloadUrl(options) {
        return this.#getDownloadUrl(options.browser, options.platform, options.buildId);
      }
      #getDownloadUrl(browser, platform, buildId) {
        return new URL(browser_data_js_1.downloadUrls[browser](platform, buildId, this.#baseUrl));
      }
      getExecutablePath(options) {
        return browser_data_js_1.executablePathByBrowser[options.browser](options.platform, options.buildId);
      }
      getName() {
        return "DefaultProvider";
      }
    };
    exports2.DefaultProvider = DefaultProvider;
  }
});

// node_modules/wrappy/wrappy.js
var require_wrappy = __commonJS({
  "node_modules/wrappy/wrappy.js"(exports2, module2) {
    init_prefix();
    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 args2 = new Array(arguments.length);
        for (var i = 0; i < args2.length; i++) {
          args2[i] = arguments[i];
        }
        var ret = fn.apply(this, args2);
        var cb2 = args2[args2.length - 1];
        if (typeof ret === "function" && ret !== cb2) {
          Object.keys(cb2).forEach(function(k) {
            ret[k] = cb2[k];
          });
        }
        return ret;
      }
    }
  }
});

// node_modules/once/once.js
var require_once = __commonJS({
  "node_modules/once/once.js"(exports2, module2) {
    init_prefix();
    var wrappy = require_wrappy();
    module2.exports = wrappy(once);
    module2.exports.strict = wrappy(onceStrict);
    once.proto = once(function() {
      Object.defineProperty(Function.prototype, "once", {
        value: function() {
          return once(this);
        },
        configurable: true
      });
      Object.defineProperty(Function.prototype, "onceStrict", {
        value: function() {
          return onceStrict(this);
        },
        configurable: true
      });
    });
    function once(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/end-of-stream/index.js
var require_end_of_stream = __commonJS({
  "node_modules/end-of-stream/index.js"(exports2, module2) {
    init_prefix();
    var once = require_once();
    var noop = function() {
    };
    var qnt = global.Bare ? queueMicrotask : process.nextTick.bind(process);
    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 = once(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() {
        qnt(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/pump/index.js
var require_pump = __commonJS({
  "node_modules/pump/index.js"(exports2, module2) {
    init_prefix();
    var once = require_once();
    var eos = require_end_of_stream();
    var fs2;
    try {
      fs2 = require("fs");
    } catch (e) {
    }
    var noop = function() {
    };
    var ancient = typeof process === "undefined" ? false : /^v?\.0/.test(process.version);
    var isFn = function(fn) {
      return typeof fn === "function";
    };
    var isFS = function(stream) {
      if (!ancient) return false;
      if (!fs2) return false;
      return (stream instanceof (fs2.ReadStream || noop) || stream instanceof (fs2.WriteStream || noop)) && isFn(stream.close);
    };
    var isRequest = function(stream) {
      return stream.setHeader && isFn(stream.abort);
    };
    var destroyer = function(stream, reading, writing, callback) {
      callback = once(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/get-stream/buffer-stream.js
var require_buffer_stream = __commonJS({
  "node_modules/get-stream/buffer-stream.js"(exports2, module2) {
    "use strict";
    init_prefix();
    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/get-stream/index.js
var require_get_stream = __commonJS({
  "node_modules/get-stream/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    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((resolve5, 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;
          }
          resolve5();
        });
        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/pend/index.js
var require_pend = __commonJS({
  "node_modules/pend/index.js"(exports2, module2) {
    init_prefix();
    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/fd-slicer/index.js
var require_fd_slicer = __commonJS({
  "node_modules/fd-slicer/index.js"(exports2) {
    init_prefix();
    var fs2 = require("fs");
    var util = require("util");
    var stream = require("stream");
    var Readable = stream.Readable;
    var Writable = stream.Writable;
    var PassThrough = stream.PassThrough;
    var Pend = require_pend();
    var EventEmitter = require("events").EventEmitter;
    exports2.createFromBuffer = createFromBuffer;
    exports2.createFromFd = createFromFd;
    exports2.BufferSlicer = BufferSlicer;
    exports2.FdSlicer = FdSlicer;
    util.inherits(FdSlicer, EventEmitter);
    function FdSlicer(fd, options) {
      options = options || {};
      EventEmitter.call(this);
      this.fd = fd;
      this.pend = new Pend();
      this.pend.max = 1;
      this.refCount = 0;
      this.autoClose = !!options.autoClose;
    }
    FdSlicer.prototype.read = function(buffer, offset, length, position, callback) {
      var self2 = this;
      self2.pend.go(function(cb) {
        fs2.read(self2.fd, buffer, offset, length, position, function(err, bytesRead, buffer2) {
          cb();
          callback(err, bytesRead, buffer2);
        });
      });
    };
    FdSlicer.prototype.write = function(buffer, offset, length, position, callback) {
      var self2 = this;
      self2.pend.go(function(cb) {
        fs2.write(self2.fd, buffer, offset, length, position, function(err, written, buffer2) {
          cb();
          callback(err, written, buffer2);
        });
      });
    };
    FdSlicer.prototype.createReadStream = function(options) {
      return new ReadStream(this, options);
    };
    FdSlicer.prototype.createWriteStream = function(options) {
      return new WriteStream(this, options);
    };
    FdSlicer.prototype.ref = function() {
      this.refCount += 1;
    };
    FdSlicer.prototype.unref = function() {
      var self2 = this;
      self2.refCount -= 1;
      if (self2.refCount > 0) return;
      if (self2.refCount < 0) throw new Error("invalid unref");
      if (self2.autoClose) {
        fs2.close(self2.fd, onCloseDone);
      }
      function onCloseDone(err) {
        if (err) {
          self2.emit("error", err);
        } else {
          self2.emit("close");
        }
      }
    };
    util.inherits(ReadStream, Readable);
    function ReadStream(context, options) {
      options = options || {};
      Readable.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);
        fs2.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();
    };
    util.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();
        fs2.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();
    };
    util.inherits(BufferSlicer, EventEmitter);
    function BufferSlicer(buffer, options) {
      EventEmitter.call(this);
      options = options || {};
      this.refCount = 0;
      this.buffer = buffer;
      this.maxChunkSize = options.maxChunkSize || Number.MAX_SAFE_INTEGER;
    }
    BufferSlicer.prototype.read = function(buffer, offset, length, position, callback) {
      var end = position + length;
      var delta = end - this.buffer.length;
      var written = delta > 0 ? delta : length;
      this.buffer.copy(buffer, offset, position, end);
      setImmediate(function() {
        callback(null, written);
      });
    };
    BufferSlicer.prototype.write = function(buffer, offset, length, position, callback) {
      buffer.copy(this.buffer, position, offset, offset + length);
      setImmediate(function() {
        callback(null, length, buffer);
      });
    };
    BufferSlicer.prototype.createReadStream = function(options) {
      options = options || {};
      var readStream = new PassThrough(options);
      readStream.destroyed = false;
      readStream.start = options.start || 0;
      readStream.endOffset = options.end;
      readStream.pos = readStream.endOffset || this.buffer.length;
      var entireSlice = this.buffer.slice(readStream.start, readStream.pos);
      var offset = 0;
      while (true) {
        var nextOffset = offset + this.maxChunkSize;
        if (nextOffset >= entireSlice.length) {
          if (offset < entireSlice.length) {
            readStream.write(entireSlice.slice(offset, entireSlice.length));
          }
          break;
        }
        readStream.write(entireSlice.slice(offset, nextOffset));
        offset = nextOffset;
      }
      readStream.end();
      readStream.destroy = function() {
        readStream.destroyed = true;
      };
      return readStream;
    };
    BufferSlicer.prototype.createWriteStream = function(options) {
      var bufferSlicer = this;
      options = options || {};
      var writeStream = new Writable(options);
      writeStream.start = options.start || 0;
      writeStream.endOffset = options.end == null ? this.buffer.length : +options.end;
      writeStream.bytesWritten = 0;
      writeStream.pos = writeStream.start;
      writeStream.destroyed = false;
      writeStream._write = function(buffer, encoding, callback) {
        if (writeStream.destroyed) return;
        var end = writeStream.pos + buffer.length;
        if (end > writeStream.endOffset) {
          var err = new Error("maximum file length exceeded");
          err.code = "ETOOBIG";
          writeStream.destroyed = true;
          callback(err);
          return;
        }
        buffer.copy(bufferSlicer.buffer, writeStream.pos, 0, buffer.length);
        writeStream.bytesWritten += buffer.length;
        writeStream.pos = end;
        writeStream.emit("progress");
        callback();
      };
      writeStream.destroy = function() {
        writeStream.destroyed = true;
      };
      return writeStream;
    };
    BufferSlicer.prototype.ref = function() {
      this.refCount += 1;
    };
    BufferSlicer.prototype.unref = function() {
      this.refCount -= 1;
      if (this.refCount < 0) {
        throw new Error("invalid unref");
      }
    };
    function createFromBuffer(buffer, options) {
      return new BufferSlicer(buffer, options);
    }
    function createFromFd(fd, options) {
      return new FdSlicer(fd, options);
    }
  }
});

// node_modules/buffer-crc32/index.js
var require_buffer_crc32 = __commonJS({
  "node_modules/buffer-crc32/index.js"(exports2, module2) {
    init_prefix();
    var Buffer2 = 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 (Buffer2.isBuffer(input)) {
        return input;
      }
      var hasNewBufferAPI = typeof Buffer2.alloc === "function" && typeof Buffer2.from === "function";
      if (typeof input === "number") {
        return hasNewBufferAPI ? Buffer2.alloc(input) : new Buffer2(input);
      } else if (typeof input === "string") {
        return hasNewBufferAPI ? Buffer2.from(input) : new Buffer2(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 (Buffer2.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/yauzl/index.js
var require_yauzl = __commonJS({
  "node_modules/yauzl/index.js"(exports2) {
    init_prefix();
    var fs2 = require("fs");
    var zlib = require("zlib");
    var fd_slicer = require_fd_slicer();
    var crc32 = require_buffer_crc32();
    var util = require("util");
    var EventEmitter = require("events").EventEmitter;
    var Transform = require("stream").Transform;
    var PassThrough = require("stream").PassThrough;
    var Writable = require("stream").Writable;
    exports2.open = open;
    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 open(path2, 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;
      fs2.open(path2, "r", function(err, fd) {
        if (err) return callback(err);
        fromFd(fd, options, function(err2, zipfile) {
          if (err2) fs2.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;
      fs2.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"));
      });
    }
    util.inherits(ZipFile, EventEmitter);
    function ZipFile(reader, centralDirectoryOffset, fileSize, entryCount, comment, autoClose, lazyEntries, decodeStrings, validateEntrySizes, strictFileNames) {
      var self2 = this;
      EventEmitter.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 = zlib.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, offset, length, position, callback) {
      if (length === 0) {
        return setImmediate(function() {
          callback(null, newBuffer(0));
        });
      }
      reader.read(buffer, offset, length, position, function(err, bytesRead) {
        if (err) return callback(err);
        if (bytesRead < length) {
          return callback(new Error("unexpected EOF"));
        }
        callback();
      });
    }
    util.inherits(AssertByteCountStream, Transform);
    function AssertByteCountStream(byteCount) {
      Transform.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();
    };
    util.inherits(RandomAccessReader, EventEmitter);
    function RandomAccessReader() {
      EventEmitter.call(this);
      this.refCount = 0;
    }
    RandomAccessReader.prototype.ref = function() {
      this.refCount += 1;
    };
    RandomAccessReader.prototype.unref = function() {
      var self2 = this;
      self2.refCount -= 1;
      if (self2.refCount > 0) return;
      if (self2.refCount < 0) throw new Error("invalid unref");
      self2.close(onCloseDone);
      function onCloseDone(err) {
        if (err) return self2.emit("error", err);
        self2.emit("close");
      }
    };
    RandomAccessReader.prototype.createReadStream = function(options) {
      var start = options.start;
      var end = options.end;
      if (start === end) {
        var emptyStream = new PassThrough();
        setImmediate(function() {
          emptyStream.end();
        });
        return emptyStream;
      }
      var stream = this._readStreamForRange(start, end);
      var destroyed = false;
      var refUnrefFilter = new RefUnrefFilter(this);
      stream.on("error", function(err) {
        setImmediate(function() {
          if (!destroyed) refUnrefFilter.emit("error", err);
        });
      });
      refUnrefFilter.destroy = function() {
        stream.unpipe(refUnrefFilter);
        refUnrefFilter.unref();
        stream.destroy();
      };
      var byteCounter = new AssertByteCountStream(end - start);
      refUnrefFilter.on("error", function(err) {
        setImmediate(function() {
          if (!destroyed) byteCounter.emit("error", err);
        });
      });
      byteCounter.destroy = function() {
        destroyed = true;
        refUnrefFilter.unpipe(byteCounter);
        refUnrefFilter.destroy();
      };
      return stream.pipe(refUnrefFilter).pipe(byteCounter);
    };
    RandomAccessReader.prototype._readStreamForRange = function(start, end) {
      throw new Error("not implemented");
    };
    RandomAccessReader.prototype.read = function(buffer, offset, length, position, callback) {
      var readStream = this.createReadStream({ start: position, end: position + length });
      var writeStream = new Writable();
      var written = 0;
      writeStream._write = function(chunk, encoding, cb) {
        chunk.copy(buffer, offset + written, 0, chunk.length);
        written += chunk.length;
        cb();
      };
      writeStream.on("finish", callback);
      readStream.on("error", function(error) {
        callback(error);
      });
      readStream.pipe(writeStream);
    };
    RandomAccessReader.prototype.close = function(callback) {
      setImmediate(callback);
    };
    util.inherits(RefUnrefFilter, PassThrough);
    function RefUnrefFilter(context) {
      PassThrough.call(this);
      this.context = context;
      this.context.ref();
      this.unreffedYet = false;
    }
    RefUnrefFilter.prototype._flush = function(cb) {
      this.unref();
      cb();
    };
    RefUnrefFilter.prototype.unref = function(cb) {
      if (this.unreffedYet) return;
      this.unreffedYet = true;
      this.context.unref();
    };
    var cp437 = "\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0";
    function decodeBuffer(buffer, start, end, isUtf8) {
      if (isUtf8) {
        return buffer.toString("utf8", start, end);
      } else {
        var result = "";
        for (var i = start; i < end; i++) {
          result += cp437[buffer[i]];
        }
        return result;
      }
    }
    function readUInt64LE(buffer, offset) {
      var lower32 = buffer.readUInt32LE(offset);
      var upper32 = buffer.readUInt32LE(offset + 4);
      return upper32 * 4294967296 + lower32;
    }
    var newBuffer;
    if (typeof Buffer.allocUnsafe === "function") {
      newBuffer = function(len) {
        return Buffer.allocUnsafe(len);
      };
    } else {
      newBuffer = function(len) {
        return new Buffer(len);
      };
    }
    function defaultCallback(err) {
      if (err) throw err;
    }
  }
});

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

// node_modules/events-universal/default.js
var require_default = __commonJS({
  "node_modules/events-universal/default.js"(exports2, module2) {
    init_prefix();
    module2.exports = require("events");
  }
});

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

// node_modules/fast-fifo/index.js
var require_fast_fifo = __commonJS({
  "node_modules/fast-fifo/index.js"(exports2, module2) {
    init_prefix();
    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/b4a/index.js
var require_b4a = __commonJS({
  "node_modules/b4a/index.js"(exports2, module2) {
    init_prefix();
    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 copy(source, target, targetStart, start, end) {
      return toBuffer(source).copy(target, targetStart, start, end);
    }
    function equals(a, b) {
      return toBuffer(a).equals(b);
    }
    function fill(buffer, value, offset, end, encoding) {
      return toBuffer(buffer).fill(value, offset, end, encoding);
    }
    function from(value, encodingOrOffset, length) {
      return Buffer.from(value, encodingOrOffset, length);
    }
    function includes(buffer, value, byteOffset, encoding) {
      return toBuffer(buffer).includes(value, byteOffset, encoding);
    }
    function indexOf(buffer, value, byfeOffset, encoding) {
      return toBuffer(buffer).indexOf(value, byfeOffset, encoding);
    }
    function lastIndexOf(buffer, value, byteOffset, encoding) {
      return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding);
    }
    function swap16(buffer) {
      return toBuffer(buffer).swap16();
    }
    function swap32(buffer) {
      return toBuffer(buffer).swap32();
    }
    function swap64(buffer) {
      return toBuffer(buffer).swap64();
    }
    function toBuffer(buffer) {
      if (Buffer.isBuffer(buffer)) return buffer;
      return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
    }
    function toString(buffer, encoding, start, end) {
      return toBuffer(buffer).toString(encoding, start, end);
    }
    function write(buffer, string, offset, length, encoding) {
      return toBuffer(buffer).write(string, offset, length, encoding);
    }
    function readDoubleBE(buffer, offset) {
      return toBuffer(buffer).readDoubleBE(offset);
    }
    function readDoubleLE(buffer, offset) {
      return toBuffer(buffer).readDoubleLE(offset);
    }
    function readFloatBE(buffer, offset) {
      return toBuffer(buffer).readFloatBE(offset);
    }
    function readFloatLE(buffer, offset) {
      return toBuffer(buffer).readFloatLE(offset);
    }
    function readInt32BE(buffer, offset) {
      return toBuffer(buffer).readInt32BE(offset);
    }
    function readInt32LE(buffer, offset) {
      return toBuffer(buffer).readInt32LE(offset);
    }
    function readUInt32BE(buffer, offset) {
      return toBuffer(buffer).readUInt32BE(offset);
    }
    function readUInt32LE(buffer, offset) {
      return toBuffer(buffer).readUInt32LE(offset);
    }
    function writeDoubleBE(buffer, value, offset) {
      return toBuffer(buffer).writeDoubleBE(value, offset);
    }
    function writeDoubleLE(buffer, value, offset) {
      return toBuffer(buffer).writeDoubleLE(value, offset);
    }
    function writeFloatBE(buffer, value, offset) {
      return toBuffer(buffer).writeFloatBE(value, offset);
    }
    function writeFloatLE(buffer, value, offset) {
      return toBuffer(buffer).writeFloatLE(value, offset);
    }
    function writeInt32BE(buffer, value, offset) {
      return toBuffer(buffer).writeInt32BE(value, offset);
    }
    function writeInt32LE(buffer, value, offset) {
      return toBuffer(buffer).writeInt32LE(value, offset);
    }
    function writeUInt32BE(buffer, value, offset) {
      return toBuffer(buffer).writeUInt32BE(value, offset);
    }
    function writeUInt32LE(buffer, value, offset) {
      return toBuffer(buffer).writeUInt32LE(value, offset);
    }
    module2.exports = {
      isBuffer,
      isEncoding,
      alloc,
      allocUnsafe,
      allocUnsafeSlow,
      byteLength,
      compare,
      concat,
      copy,
      equals,
      fill,
      from,
      includes,
      indexOf,
      lastIndexOf,
      swap16,
      swap32,
      swap64,
      toBuffer,
      toString,
      write,
      readDoubleBE,
      readDoubleLE,
      readFloatBE,
      readFloatLE,
      readInt32BE,
      readInt32LE,
      readUInt32BE,
      readUInt32LE,
      writeDoubleBE,
      writeDoubleLE,
      writeFloatBE,
      writeFloatLE,
      writeInt32BE,
      writeInt32LE,
      writeUInt32BE,
      writeUInt32LE
    };
  }
});

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

// node_modules/text-decoder/lib/utf8-decoder.js
var require_utf8_decoder = __commonJS({
  "node_modules/text-decoder/lib/utf8-decoder.js"(exports2, module2) {
    init_prefix();
    var b4a = require_b4a();
    module2.exports = class UTF8Decoder {
      constructor() {
        this._reset();
      }
      get remaining() {
        return this.bytesSeen;
      }
      decode(data) {
        if (data.byteLength === 0) return "";
        if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
          this.bytesSeen = trailingBytesSeen(data);
          return b4a.toString(data, "utf8");
        }
        let result = "";
        let start = 0;
        if (this.bytesNeeded > 0) {
          while (start < data.byteLength) {
            const byte = data[start];
            if (byte < this.lowerBoundary || byte > this.upperBoundary) {
              result += "\uFFFD";
              this._reset();
              break;
            }
            this.lowerBoundary = 128;
            this.upperBoundary = 191;
            this.codePoint = this.codePoint << 6 | byte & 63;
            this.bytesSeen++;
            start++;
            if (this.bytesSeen === this.bytesNeeded) {
              result += String.fromCodePoint(this.codePoint);
              this._reset();
              break;
            }
          }
          if (this.bytesNeeded > 0) return result;
        }
        const trailing = trailingIncomplete(data, start);
        const end = data.byteLength - trailing;
        if (end > start) result += b4a.toString(data, "utf8", start, end);
        for (let i = end; i < data.byteLength; i++) {
          const byte = data[i];
          if (this.bytesNeeded === 0) {
            if (byte <= 127) {
              this.bytesSeen = 0;
              result += String.fromCharCode(byte);
            } else if (byte >= 194 && byte <= 223) {
              this.bytesNeeded = 2;
              this.bytesSeen = 1;
              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.bytesSeen = 1;
              this.codePoint = byte & 15;
            } else if (byte >= 240 && byte <= 244) {
              if (byte === 240) this.lowerBoundary = 144;
              else if (byte === 244) this.upperBoundary = 143;
              this.bytesNeeded = 4;
              this.bytesSeen = 1;
              this.codePoint = byte & 7;
            } else {
              this.bytesSeen = 1;
              result += "\uFFFD";
            }
            continue;
          }
          if (byte < this.lowerBoundary || byte > this.upperBoundary) {
            result += "\uFFFD";
            i--;
            this._reset();
            continue;
          }
          this.lowerBoundary = 128;
          this.upperBoundary = 191;
          this.codePoint = this.codePoint << 6 | byte & 63;
          this.bytesSeen++;
          if (this.bytesSeen === this.bytesNeeded) {
            result += String.fromCodePoint(this.codePoint);
            this._reset();
          }
        }
        return result;
      }
      flush() {
        const result = this.bytesNeeded > 0 ? "\uFFFD" : "";
        this._reset();
        return result;
      }
      _reset() {
        this.codePoint = 0;
        this.bytesNeeded = 0;
        this.bytesSeen = 0;
        this.lowerBoundary = 128;
        this.upperBoundary = 191;
      }
    };
    function trailingIncomplete(data, start) {
      const len = data.byteLength;
      if (len <= start) return 0;
      const limit = Math.max(start, len - 4);
      let i = len - 1;
      while (i > limit && (data[i] & 192) === 128) i--;
      if (i < start) return 0;
      const byte = data[i];
      let needed;
      if (byte <= 127) return 0;
      if (byte >= 194 && byte <= 223) needed = 2;
      else if (byte >= 224 && byte <= 239) needed = 3;
      else if (byte >= 240 && byte <= 244) needed = 4;
      else return 0;
      const available = len - i;
      return available < needed ? available : 0;
    }
    function trailingBytesSeen(data) {
      const len = data.byteLength;
      if (len === 0) return 0;
      const last = data[len - 1];
      if (last <= 127) return 0;
      if ((last & 192) !== 128) return 1;
      const limit = Math.max(0, len - 4);
      let i = len - 2;
      while (i >= limit && (data[i] & 192) === 128) i--;
      if (i < 0) return 1;
      const first = data[i];
      let needed;
      if (first >= 194 && first <= 223) needed = 2;
      else if (first >= 224 && first <= 239) needed = 3;
      else if (first >= 240 && first <= 244) needed = 4;
      else return 1;
      if (len - i !== needed) return 1;
      if (needed >= 3) {
        const second = data[i + 1];
        if (first === 224 && second < 160) return 1;
        if (first === 237 && second > 159) return 1;
        if (first === 240 && second < 144) return 1;
        if (first === 244 && second > 143) return 1;
      }
      return 0;
    }
  }
});

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

// node_modules/streamx/index.js
var require_streamx = __commonJS({
  "node_modules/streamx/index.js"(exports2, module2) {
    init_prefix();
    var { EventEmitter } = require_default();
    var STREAM_DESTROYED = new Error("Stream was destroyed");
    var PREMATURE_CLOSE = new Error("Premature close");
    var FIFO = require_fast_fifo();
    var TextDecoder2 = require_text_decoder();
    var qmt = typeof queueMicrotask === "undefined" ? (fn) => global.process.nextTick(fn) : queueMicrotask;
    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 ending() {
        return (this.stream._duplexState & WRITE_FINISHING) !== 0;
      }
      get ended() {
        return (this.stream._duplexState & WRITE_DONE) !== 0;
      }
      push(data) {
        if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false;
        if (this.map !== null) data = this.map(data);
        this.buffered += this.byteLength(data);
        this.queue.push(data);
        if (this.buffered < this.highWaterMark) {
          this.stream._duplexState |= WRITE_QUEUED;
          return true;
        }
        this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED;
        return false;
      }
      shift() {
        const data = this.queue.shift();
        this.buffered -= this.byteLength(data);
        if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED;
        return data;
      }
      end(data) {
        if (typeof data === "function") this.stream.once("finish", data);
        else if (data !== void 0 && data !== null) this.push(data);
        this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY;
      }
      autoBatch(data, cb) {
        const buffer = [];
        const stream = this.stream;
        buffer.push(data);
        while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
          buffer.push(stream._writableState.shift());
        }
        if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null);
        stream._writev(buffer, cb);
      }
      update() {
        const stream = this.stream;
        stream._duplexState |= WRITE_UPDATING;
        do {
          while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
            const data = this.shift();
            stream._duplexState |= WRITE_ACTIVE_AND_WRITING;
            stream._write(data, this.afterWrite);
          }
          if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary();
        } while (this.continueUpdate() === true);
        stream._duplexState &= WRITE_NOT_UPDATING;
      }
      updateNonPrimary() {
        const stream = this.stream;
        if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
          stream._duplexState = stream._duplexState | WRITE_ACTIVE;
          stream._final(afterFinal.bind(this));
          return;
        }
        if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
          if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
            stream._duplexState |= ACTIVE;
            stream._destroy(afterDestroy.bind(this));
          }
          return;
        }
        if ((stream._duplexState & IS_OPENING) === OPENING) {
          stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
          stream._open(afterOpen.bind(this));
        }
      }
      continueUpdate() {
        if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false;
        this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
        return true;
      }
      updateCallback() {
        if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update();
        else this.updateNextTick();
      }
      updateNextTick() {
        if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return;
        this.stream._duplexState |= WRITE_NEXT_TICK;
        if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(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 ending() {
        return (this.stream._duplexState & READ_ENDING) !== 0;
      }
      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 Pipeline(this.stream, pipeTo, cb);
        if (cb) this.stream.on("error", noop);
        if (isStreamx(pipeTo)) {
          pipeTo._writableState.pipeline = this.pipeline;
          if (cb) pipeTo.on("error", noop);
          pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
        } else {
          const onerror = this.pipeline.done.bind(this.pipeline, pipeTo);
          const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null);
          pipeTo.on("error", onerror);
          pipeTo.on("close", onclose);
          pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
        }
        pipeTo.on("drain", afterDrain.bind(this));
        this.stream.emit("piping", pipeTo);
        pipeTo.emit("pipe", this.stream);
      }
      push(data) {
        const stream = this.stream;
        if (data === null) {
          this.highWaterMark = 0;
          stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED;
          return false;
        }
        if (this.map !== null) {
          data = this.map(data);
          if (data === null) {
            stream._duplexState &= READ_PUSHED;
            return this.buffered < this.highWaterMark;
          }
        }
        this.buffered += this.byteLength(data);
        this.queue.push(data);
        stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED;
        return this.buffered < this.highWaterMark;
      }
      shift() {
        const data = this.queue.shift();
        this.buffered -= this.byteLength(data);
        if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED;
        return data;
      }
      unshift(data) {
        const pending = [this.map !== null ? this.map(data) : data];
        while (this.buffered > 0) pending.push(this.shift());
        for (let i = 0; i < pending.length - 1; i++) {
          const data2 = pending[i];
          this.buffered += this.byteLength(data2);
          this.queue.push(data2);
        }
        this.push(pending[pending.length - 1]);
      }
      read() {
        const stream = this.stream;
        if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
          const data = this.shift();
          if (this.pipeTo !== null && this.pipeTo.write(data) === false)
            stream._duplexState &= READ_PIPE_NOT_DRAINED;
          if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data);
          return data;
        }
        if (this.readAhead === false) {
          stream._duplexState |= READ_READ_AHEAD;
          this.updateNextTick();
        }
        return null;
      }
      drain() {
        const stream = this.stream;
        while ((stream._duplexState & READ_STATUS) === READ_QUEUED && (stream._duplexState & READ_FLOWING) !== 0) {
          const data = this.shift();
          if (this.pipeTo !== null && this.pipeTo.write(data) === false)
            stream._duplexState &= READ_PIPE_NOT_DRAINED;
          if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data);
        }
      }
      update() {
        const stream = this.stream;
        stream._duplexState |= READ_UPDATING;
        do {
          this.drain();
          while (this.buffered < this.highWaterMark && (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD) {
            stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH;
            stream._read(this.afterRead);
            this.drain();
          }
          if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
            stream._duplexState |= READ_EMITTED_READABLE;
            stream.emit("readable");
          }
          if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary();
        } while (this.continueUpdate() === true);
        stream._duplexState &= READ_NOT_UPDATING;
      }
      updateNonPrimary() {
        const stream = this.stream;
        if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
          stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING;
          stream.emit("end");
          if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING;
          if (this.pipeTo !== null) this.pipeTo.end();
        }
        if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
          if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
            stream._duplexState |= ACTIVE;
            stream._destroy(afterDestroy.bind(this));
          }
          return;
        }
        if ((stream._duplexState & IS_OPENING) === OPENING) {
          stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
          stream._open(afterOpen.bind(this));
        }
      }
      continueUpdate() {
        if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false;
        this.stream._duplexState &= READ_NOT_NEXT_TICK;
        return true;
      }
      updateCallback() {
        if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update();
        else this.updateNextTick();
      }
      updateNextTickIfOpen() {
        if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return;
        this.stream._duplexState |= READ_NEXT_TICK;
        if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(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) qmt(this.afterUpdateNextTick);
      }
    };
    var TransformState = class {
      constructor(stream) {
        this.data = null;
        this.afterTransform = afterTransform.bind(stream);
        this.afterFinal = null;
      }
    };
    var Pipeline = class {
      constructor(src, dst, cb) {
        this.from = src;
        this.to = dst;
        this.afterPipe = cb;
        this.error = null;
        this.pipeToFinished = false;
      }
      finished() {
        this.pipeToFinished = true;
      }
      done(stream, err) {
        if (err) this.error = err;
        if (stream === this.to) {
          this.to = null;
          if (this.from !== null) {
            if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
              this.from.destroy(this.error || new Error("Writable stream closed prematurely"));
            }
            return;
          }
        }
        if (stream === this.from) {
          this.from = null;
          if (this.to !== null) {
            if ((stream._duplexState & READ_DONE) === 0) {
              this.to.destroy(this.error || new Error("Readable stream closed before ending"));
            }
            return;
          }
        }
        if (this.afterPipe !== null) this.afterPipe(this.error);
        this.to = this.from = this.afterPipe = null;
      }
    };
    function afterDrain() {
      this.stream._duplexState |= READ_PIPE_DRAINED;
      this.updateCallback();
    }
    function afterFinal(err) {
      const stream = this.stream;
      if (err) stream.destroy(err);
      if ((stream._duplexState & DESTROY_STATUS) === 0) {
        stream._duplexState |= WRITE_DONE;
        stream.emit("finish");
      }
      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
        stream._duplexState |= DESTROYING;
      }
      stream._duplexState &= WRITE_NOT_FINISHING;
      if ((stream._duplexState & WRITE_UPDATING) === 0) this.update();
      else this.updateNextTick();
    }
    function afterDestroy(err) {
      const stream = this.stream;
      if (!err && this.error !== STREAM_DESTROYED) err = this.error;
      if (err) stream.emit("error", err);
      stream._duplexState |= DESTROYED;
      stream.emit("close");
      const rs = stream._readableState;
      const ws = stream._writableState;
      if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream, err);
      if (ws !== null) {
        while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false);
        if (ws.pipeline !== null) ws.pipeline.done(stream, err);
      }
    }
    function afterWrite(err) {
      const stream = this.stream;
      if (err) stream.destroy(err);
      stream._duplexState &= WRITE_NOT_ACTIVE;
      if (this.drains !== null) tickDrains(this.drains);
      if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
        stream._duplexState &= WRITE_DRAINED;
        if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
          stream.emit("drain");
        }
      }
      this.updateCallback();
    }
    function afterRead(err) {
      if (err) this.stream.destroy(err);
      this.stream._duplexState &= READ_NOT_ACTIVE;
      if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0)
        this.stream._duplexState &= READ_NO_READ_AHEAD;
      this.updateCallback();
    }
    function updateReadNT() {
      if ((this.stream._duplexState & READ_UPDATING) === 0) {
        this.stream._duplexState &= READ_NOT_NEXT_TICK;
        this.update();
      }
    }
    function updateWriteNT() {
      if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
        this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
        this.update();
      }
    }
    function tickDrains(drains) {
      for (let i = 0; i < drains.length; i++) {
        if (--drains[i].writes === 0) {
          drains.shift().resolve(true);
          i--;
        }
      }
    }
    function afterOpen(err) {
      const stream = this.stream;
      if (err) stream.destroy(err);
      if ((stream._duplexState & DESTROYING) === 0) {
        if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) stream._duplexState |= READ_PRIMARY;
        if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) stream._duplexState |= WRITE_PRIMARY;
        stream.emit("open");
      }
      stream._duplexState &= NOT_ACTIVE;
      if (stream._writableState !== null) {
        stream._writableState.updateCallback();
      }
      if (stream._readableState !== null) {
        stream._readableState.updateCallback();
      }
    }
    function afterTransform(err, data) {
      if (data !== void 0 && data !== null) this.push(data);
      this._writableState.afterWrite(err);
    }
    function newListener(name) {
      if (this._readableState !== null) {
        if (name === "data") {
          this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD;
          this._readableState.updateNextTick();
        }
        if (name === "readable") {
          this._duplexState |= READ_EMIT_READABLE;
          this._readableState.updateNextTick();
        }
      }
      if (this._writableState !== null) {
        if (name === "drain") {
          this._duplexState |= WRITE_EMIT_DRAIN;
          this._writableState.updateNextTick();
        }
      }
    }
    var Stream = class extends EventEmitter {
      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 Readable = class _Readable extends Stream {
      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 TextDecoder2(encoding);
        const map = this._readableState.map || echo;
        this._readableState.map = mapOrSkip;
        return this;
        function mapOrSkip(data) {
          const next = dec.push(data);
          return next === "" && (data.byteLength !== 0 || dec.remaining > 0) ? null : 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(data) {
        this._readableState.updateNextTickIfOpen();
        return this._readableState.push(data);
      }
      unshift(data) {
        this._readableState.updateNextTickIfOpen();
        return this._readableState.unshift(data);
      }
      resume() {
        this._duplexState |= READ_RESUMED_READ_AHEAD;
        this._readableState.updateNextTick();
        return this;
      }
      pause() {
        this._duplexState &= this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED;
        return this;
      }
      static _fromAsyncIterator(ite, opts) {
        let destroy;
        const rs = new _Readable({
          ...opts,
          read(cb) {
            ite.next().then(push).then(cb.bind(null, null)).catch(cb);
          },
          predestroy() {
            destroy = ite.return();
          },
          destroy(cb) {
            if (!destroy) return cb(null);
            destroy.then(cb.bind(null, null)).catch(cb);
          }
        });
        return rs;
        function push(data) {
          if (data.done) rs.push(null);
          else rs.push(data.value);
        }
      }
      static from(data, opts) {
        if (isReadStreamx(data)) return data;
        if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts);
        if (!Array.isArray(data)) data = data === void 0 ? [] : [data];
        let i = 0;
        return new _Readable({
          ...opts,
          read(cb) {
            this.push(i === data.length ? null : data[i++]);
            cb(null);
          }
        });
      }
      static isBackpressured(rs) {
        return (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || rs._readableState.buffered >= rs._readableState.highWaterMark;
      }
      static isPaused(rs) {
        return (rs._duplexState & READ_RESUMED) === 0;
      }
      [asyncIterator]() {
        const stream = this;
        let 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(resolve5, reject) {
              promiseResolve = resolve5;
              promiseReject = reject;
              const data = stream.read();
              if (data !== null) ondata(data);
              else if ((stream._duplexState & DESTROYED) !== 0) ondata(null);
            });
          },
          return() {
            return destroy(null);
          },
          throw(err) {
            return destroy(err);
          }
        };
        function onreadable() {
          if (promiseResolve !== null) ondata(stream.read());
        }
        function onclose() {
          if (promiseResolve !== null) ondata(null);
        }
        function ondata(data) {
          if (promiseReject === null) return;
          if (error) promiseReject(error);
          else if (data === null && (stream._duplexState & READ_DONE) === 0)
            promiseReject(STREAM_DESTROYED);
          else promiseResolve({ value: data, done: data === null });
          promiseReject = promiseResolve = null;
        }
        function destroy(err) {
          stream.destroy(err);
          return new Promise((resolve5, reject) => {
            if (stream._duplexState & DESTROYED) return resolve5({ value: void 0, done: true });
            stream.once("close", function() {
              if (err) reject(err);
              else resolve5({ value: void 0, done: true });
            });
          });
        }
      }
    };
    var Writable = class extends Stream {
      constructor(opts) {
        super(opts);
        this._duplexState |= OPENING | READ_DONE;
        this._writableState = new WritableState(this, opts);
        if (opts) {
          if (opts.writev) this._writev = opts.writev;
          if (opts.write) this._write = opts.write;
          if (opts.final) this._final = opts.final;
          if (opts.eagerOpen) this._writableState.updateNextTick();
        }
      }
      cork() {
        this._duplexState |= WRITE_CORKED;
      }
      uncork() {
        this._duplexState &= WRITE_NOT_CORKED;
        this._writableState.updateNextTick();
      }
      _writev(batch, cb) {
        cb(null);
      }
      _write(data, cb) {
        this._writableState.autoBatch(data, cb);
      }
      _final(cb) {
        cb(null);
      }
      static isBackpressured(ws) {
        return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0;
      }
      static drained(ws) {
        if (ws.destroyed) return Promise.resolve(false);
        const state = ws._writableState;
        const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length;
        const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0);
        if (writes === 0) return Promise.resolve(true);
        if (state.drains === null) state.drains = [];
        return new Promise((resolve5) => {
          state.drains.push({ writes, resolve: resolve5 });
        });
      }
      write(data) {
        this._writableState.updateNextTick();
        return this._writableState.push(data);
      }
      end(data) {
        this._writableState.updateNextTick();
        this._writableState.end(data);
        return this;
      }
    };
    var Duplex = class extends Readable {
      // and Writable
      constructor(opts) {
        super(opts);
        this._duplexState = OPENING | this._duplexState & READ_READ_AHEAD;
        this._writableState = new WritableState(this, opts);
        if (opts) {
          if (opts.writev) this._writev = opts.writev;
          if (opts.write) this._write = opts.write;
          if (opts.final) this._final = opts.final;
        }
      }
      cork() {
        this._duplexState |= WRITE_CORKED;
      }
      uncork() {
        this._duplexState &= WRITE_NOT_CORKED;
        this._writableState.updateNextTick();
      }
      _writev(batch, cb) {
        cb(null);
      }
      _write(data, cb) {
        this._writableState.autoBatch(data, cb);
      }
      _final(cb) {
        cb(null);
      }
      write(data) {
        this._writableState.updateNextTick();
        return this._writableState.push(data);
      }
      end(data) {
        this._writableState.updateNextTick();
        this._writableState.end(data);
        return this;
      }
    };
    var Transform = class extends Duplex {
      constructor(opts) {
        super(opts);
        this._transformState = new TransformState(this);
        if (opts) {
          if (opts.transform) this._transform = opts.transform;
          if (opts.flush) this._flush = opts.flush;
        }
      }
      _write(data, cb) {
        if (this._readableState.buffered >= this._readableState.highWaterMark) {
          this._transformState.data = data;
        } else {
          this._transform(data, this._transformState.afterTransform);
        }
      }
      _read(cb) {
        if (this._transformState.data !== null) {
          const data = this._transformState.data;
          this._transformState.data = null;
          cb(null);
          this._transform(data, this._transformState.afterTransform);
        } else {
          cb(null);
        }
      }
      destroy(err) {
        super.destroy(err);
        if (this._transformState.data !== null) {
          this._transformState.data = null;
          this._transformState.afterTransform();
        }
      }
      _transform(data, cb) {
        cb(null, data);
      }
      _flush(cb) {
        cb(null);
      }
      _final(cb) {
        this._transformState.afterFinal = cb;
        this._flush(transformAfterFlush.bind(this));
      }
    };
    var PassThrough = class extends Transform {
    };
    function transformAfterFlush(err, data) {
      const cb = this._transformState.afterFinal;
      if (err) return cb(err);
      if (data !== null && data !== void 0) this.push(data);
      this.push(null);
      cb(null);
    }
    function pipelinePromise(...streams) {
      return new Promise((resolve5, reject) => {
        return pipeline(...streams, (err) => {
          if (err) return reject(err);
          resolve5();
        });
      });
    }
    function pipeline(stream, ...streams) {
      const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams];
      const done = all.length && typeof all[all.length - 1] === "function" ? all.pop() : null;
      if (all.length < 2) throw new Error("Pipeline requires at least 2 streams");
      let src = all[0];
      let dest = null;
      let error = null;
      for (let i = 1; i < all.length; i++) {
        dest = all[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 all) {
          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 isEnding(stream) {
      return !!stream._readableState && stream._readableState.ending;
    }
    function isEnded(stream) {
      return !!stream._readableState && stream._readableState.ended;
    }
    function isFinishing(stream) {
      return !!stream._writableState && stream._writableState.ending;
    }
    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 & DESTROYING) === DESTROYING || (stream._duplexState & ACTIVE_OR_TICKING) !== 0;
    }
    function isTypedArray(data) {
      return typeof data === "object" && data !== null && typeof data.byteLength === "number";
    }
    function defaultByteLength(data) {
      return isTypedArray(data) ? data.byteLength : 1024;
    }
    function noop() {
    }
    function abort() {
      this.destroy(new Error("Stream aborted."));
    }
    function isWritev(s) {
      return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev;
    }
    module2.exports = {
      pipeline,
      pipelinePromise,
      isStream,
      isStreamx,
      isEnding,
      isEnded,
      isFinishing,
      isFinished,
      isDisturbed,
      getStreamError,
      Stream,
      Writable,
      Readable,
      Duplex,
      Transform,
      // Export PassThrough for compatibility with Node.js core's stream module
      PassThrough
    };
  }
});

// node_modules/tar-stream/headers.js
var require_headers = __commonJS({
  "node_modules/tar-stream/headers.js"(exports2) {
    init_prefix();
    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 mode2 = 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: mode2,
        uid,
        gid,
        size,
        mtime: new Date(1e3 * mtime),
        type,
        linkname,
        uname,
        gname,
        devmajor,
        devminor,
        pax: null
      };
    };
    function isUSTAR(buf) {
      return b4a.equals(USTAR_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6));
    }
    function isGNU(buf) {
      return b4a.equals(GNU_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) && b4a.equals(GNU_VER, buf.subarray(VERSION_OFFSET, VERSION_OFFSET + 2));
    }
    function clamp(index, len, defaultValue) {
      if (typeof index !== "number") return defaultValue;
      index = ~~index;
      if (index >= len) return len;
      if (index >= 0) return index;
      index += len;
      if (index >= 0) return index;
      return 0;
    }
    function toType(flag) {
      switch (flag) {
        case 0:
          return "file";
        case 1:
          return "link";
        case 2:
          return "symlink";
        case 3:
          return "character-device";
        case 4:
          return "block-device";
        case 5:
          return "directory";
        case 6:
          return "fifo";
        case 7:
          return "contiguous-file";
        case 72:
          return "pax-header";
        case 55:
          return "pax-global-header";
        case 27:
          return "gnu-long-link-path";
        case 28:
        case 30:
          return "gnu-long-path";
      }
      return null;
    }
    function toTypeflag(flag) {
      switch (flag) {
        case "file":
          return 0;
        case "link":
          return 1;
        case "symlink":
          return 2;
        case "character-device":
          return 3;
        case "block-device":
          return 4;
        case "directory":
          return 5;
        case "fifo":
          return 6;
        case "contiguous-file":
          return 7;
        case "pax-header":
          return 72;
      }
      return 0;
    }
    function indexOf(block, num, offset, end) {
      for (; offset < end; offset++) {
        if (block[offset] === num) return offset;
      }
      return end;
    }
    function cksum(block) {
      let sum = 8 * 32;
      for (let i = 0; i < 148; i++) sum += block[i];
      for (let j = 156; j < 512; j++) sum += block[j];
      return sum;
    }
    function encodeOct(val, n) {
      val = val.toString(8);
      if (val.length > n) return SEVENS.slice(0, n) + " ";
      return ZEROS.slice(0, n - val.length) + val + " ";
    }
    function encodeSizeBin(num, buf, off) {
      buf[off] = 128;
      for (let i = 11; i > 0; i--) {
        buf[off + i] = num & 255;
        num = Math.floor(num / 256);
      }
    }
    function encodeSize(num, buf, off) {
      if (num.toString(8).length > 11) {
        encodeSizeBin(num, buf, off);
      } else {
        b4a.write(buf, encodeOct(num, 11), off);
      }
    }
    function parse256(buf) {
      let positive;
      if (buf[0] === 128) positive = true;
      else if (buf[0] === 255) positive = false;
      else return null;
      const 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, offset, length) {
      val = val.subarray(offset, offset + length);
      offset = 0;
      if (val[offset] & 128) {
        return parse256(val);
      } else {
        while (offset < val.length && val[offset] === 32) offset++;
        const end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length);
        while (offset < end && val[offset] === 0) offset++;
        if (end === offset) return 0;
        return parseInt(b4a.toString(val.subarray(offset, end)), 8);
      }
    }
    function decodeStr(val, offset, length, encoding) {
      return b4a.toString(val.subarray(offset, indexOf(val, 0, offset, offset + length)), encoding);
    }
    function addLength(str) {
      const len = b4a.byteLength(str);
      let digits = Math.floor(Math.log(len) / Math.log(10)) + 1;
      if (len + digits >= Math.pow(10, digits)) digits++;
      return len + digits + str;
    }
  }
});

// node_modules/tar-stream/extract.js
var require_extract = __commonJS({
  "node_modules/tar-stream/extract.js"(exports2, module2) {
    init_prefix();
    var { Writable, Readable, 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 Readable {
      constructor(self2, header, offset) {
        super();
        this.header = header;
        this.offset = offset;
        this._parent = self2;
      }
      _read(cb) {
        if (this.header.size === 0) {
          this.push(null);
        }
        if (this._parent._stream === this) {
          this._parent._update();
        }
        cb(null);
      }
      _predestroy() {
        this._parent.destroy(getStreamError(this));
      }
      _detach() {
        if (this._parent._stream === this) {
          this._parent._stream = null;
          this._parent._missing = overflow(this.header.size);
          this._parent._update();
        }
      }
      _destroy(cb) {
        this._detach();
        cb(null);
      }
    };
    var Extract = class extends Writable {
      constructor(opts) {
        super(opts);
        if (!opts) opts = {};
        this._buffer = new BufferList();
        this._offset = 0;
        this._header = null;
        this._stream = null;
        this._missing = 0;
        this._longHeader = false;
        this._callback = noop;
        this._locked = false;
        this._finished = false;
        this._pax = null;
        this._paxGlobal = null;
        this._gnuLongPath = null;
        this._gnuLongLinkPath = null;
        this._filenameEncoding = opts.filenameEncoding || "utf-8";
        this._allowUnknownFormat = !!opts.allowUnknownFormat;
        this._unlockBound = this._unlock.bind(this);
      }
      _unlock(err) {
        this._locked = false;
        if (err) {
          this.destroy(err);
          this._continueWrite(err);
          return;
        }
        this._update();
      }
      _consumeHeader() {
        if (this._locked) return false;
        this._offset = this._buffer.shifted;
        try {
          this._header = headers.decode(this._buffer.shift(512), this._filenameEncoding, this._allowUnknownFormat);
        } catch (err) {
          this._continueWrite(err);
          return false;
        }
        if (!this._header) return true;
        switch (this._header.type) {
          case "gnu-long-path":
          case "gnu-long-link-path":
          case "pax-global-header":
          case "pax-header":
            this._longHeader = true;
            this._missing = this._header.size;
            return true;
        }
        this._locked = true;
        this._applyLongHeaders();
        if (this._header.size === 0 || this._header.type === "directory") {
          this.emit("entry", this._header, this._createStream(), this._unlockBound);
          return true;
        }
        this._stream = this._createStream();
        this._missing = this._header.size;
        this.emit("entry", this._header, this._stream, this._unlockBound);
        return true;
      }
      _applyLongHeaders() {
        if (this._gnuLongPath) {
          this._header.name = this._gnuLongPath;
          this._gnuLongPath = null;
        }
        if (this._gnuLongLinkPath) {
          this._header.linkname = this._gnuLongLinkPath;
          this._gnuLongLinkPath = null;
        }
        if (this._pax) {
          if (this._pax.path) this._header.name = this._pax.path;
          if (this._pax.linkpath) this._header.linkname = this._pax.linkpath;
          if (this._pax.size) this._header.size = parseInt(this._pax.size, 10);
          this._header.pax = this._pax;
          this._pax = null;
        }
      }
      _decodeLongHeader(buf) {
        switch (this._header.type) {
          case "gnu-long-path":
            this._gnuLongPath = headers.decodeLongPath(buf, this._filenameEncoding);
            break;
          case "gnu-long-link-path":
            this._gnuLongLinkPath = headers.decodeLongPath(buf, this._filenameEncoding);
            break;
          case "pax-global-header":
            this._paxGlobal = headers.decodePax(buf);
            break;
          case "pax-header":
            this._pax = this._paxGlobal === null ? headers.decodePax(buf) : Object.assign({}, this._paxGlobal, headers.decodePax(buf));
            break;
        }
      }
      _consumeLongHeader() {
        this._longHeader = false;
        this._missing = overflow(this._header.size);
        const buf = this._buffer.shift(this._header.size);
        try {
          this._decodeLongHeader(buf);
        } catch (err) {
          this._continueWrite(err);
          return false;
        }
        return true;
      }
      _consumeStream() {
        const buf = this._buffer.shiftFirst(this._missing);
        if (buf === null) return false;
        this._missing -= buf.byteLength;
        const drained = this._stream.push(buf);
        if (this._missing === 0) {
          this._stream.push(null);
          if (drained) this._stream._detach();
          return drained && this._locked === false;
        }
        return drained;
      }
      _createStream() {
        return new Source(this, this._header, this._offset);
      }
      _update() {
        while (this._buffer.buffered > 0 && !this.destroying) {
          if (this._missing > 0) {
            if (this._stream !== null) {
              if (this._consumeStream() === false) return;
              continue;
            }
            if (this._longHeader === true) {
              if (this._missing > this._buffer.buffered) break;
              if (this._consumeLongHeader() === false) return false;
              continue;
            }
            const ignore = this._buffer.shiftFirst(this._missing);
            if (ignore !== null) this._missing -= ignore.byteLength;
            continue;
          }
          if (this._buffer.buffered < 512) break;
          if (this._stream !== null || this._consumeHeader() === false) return;
        }
        this._continueWrite(null);
      }
      _continueWrite(err) {
        const cb = this._callback;
        this._callback = noop;
        cb(err);
      }
      _write(data, cb) {
        this._callback = cb;
        this._buffer.push(data);
        this._update();
      }
      _final(cb) {
        this._finished = this._missing === 0 && this._buffer.buffered === 0;
        cb(this._finished ? null : new Error("Unexpected end of data"));
      }
      _predestroy() {
        this._continueWrite(null);
      }
      _destroy(cb) {
        if (this._stream) this._stream.destroy(getStreamError(this));
        cb(null);
      }
      [Symbol.asyncIterator]() {
        let 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(resolve5, reject) {
          if (error) {
            return reject(error);
          }
          if (entryStream) {
            resolve5({ value: entryStream, done: false });
            entryStream = null;
            return;
          }
          promiseResolve = resolve5;
          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((resolve5, reject) => {
            if (extract.destroyed) return resolve5({ value: void 0, done: true });
            extract.once("close", function() {
              if (err) reject(err);
              else resolve5({ 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/tar-stream/constants.js
var require_constants6 = __commonJS({
  "node_modules/tar-stream/constants.js"(exports2, module2) {
    init_prefix();
    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/tar-stream/pack.js
var require_pack = __commonJS({
  "node_modules/tar-stream/pack.js"(exports2, module2) {
    init_prefix();
    var { Readable, Writable, getStreamError } = require_streamx();
    var b4a = require_b4a();
    var constants = require_constants6();
    var headers = require_headers();
    var DMODE = 493;
    var FMODE = 420;
    var END_OF_TAR = b4a.alloc(1024);
    var Sink = class extends Writable {
      constructor(pack, 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 = pack;
        this._openCallback = null;
        if (this._pack._stream === null) this._pack._stream = this;
        else this._pack._pending.push(this);
      }
      _open(cb) {
        this._openCallback = cb;
        if (this._pack._stream === this) this._continueOpen();
      }
      _continuePack(err) {
        if (this._callback === null) return;
        const callback = this._callback;
        this._callback = null;
        callback(err);
      }
      _continueOpen() {
        if (this._pack._stream === null) this._pack._stream = this;
        const cb = this._openCallback;
        this._openCallback = null;
        if (cb === null) return;
        if (this._pack.destroying) return cb(new Error("pack stream destroyed"));
        if (this._pack._finalized) return cb(new Error("pack stream is already finalized"));
        this._pack._stream = this;
        if (!this._isLinkname) {
          this._pack._encode(this.header);
        }
        if (this._isVoid) {
          this._finish();
          this._continuePack(null);
        }
        cb(null);
      }
      _write(data, cb) {
        if (this._isLinkname) {
          this._linkname = this._linkname ? b4a.concat([this._linkname, data]) : data;
          return cb(null);
        }
        if (this._isVoid) {
          if (data.byteLength > 0) {
            return cb(new Error("No body allowed for this entry"));
          }
          return cb();
        }
        this.written += data.byteLength;
        if (this._pack.push(data)) return cb();
        this._pack._drain = cb;
      }
      _finish() {
        if (this._finished) return;
        this._finished = true;
        if (this._isLinkname) {
          this.header.linkname = this._linkname ? b4a.toString(this._linkname, "utf-8") : "";
          this._pack._encode(this.header);
        }
        overflow(this._pack, this.header.size);
        this._pack._done(this);
      }
      _final(cb) {
        if (this.written !== this.header.size) {
          return cb(new Error("Size mismatch"));
        }
        this._finish();
        cb(null);
      }
      _getError() {
        return getStreamError(this) || new Error("tar entry destroyed");
      }
      _predestroy() {
        this._pack.destroy(this._getError());
      }
      _destroy(cb) {
        this._pack._done(this);
        this._continuePack(this._finished ? null : this._getError());
        cb();
      }
    };
    var Pack = class extends Readable {
      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 pack(opts) {
      return new Pack(opts);
    };
    function modeToType(mode2) {
      switch (mode2 & 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/tar-stream/index.js
var require_tar_stream = __commonJS({
  "node_modules/tar-stream/index.js"(exports2) {
    init_prefix();
    exports2.extract = require_extract();
    exports2.pack = require_pack();
  }
});

// node_modules/tar-fs/index.js
var require_tar_fs = __commonJS({
  "node_modules/tar-fs/index.js"(exports2) {
    init_prefix();
    var tar = require_tar_stream();
    var pump = require_pump();
    var fs2 = require("fs");
    var path2 = require("path");
    var win32 = (global.Bare ? global.Bare.platform : process.platform) === "win32";
    exports2.pack = function pack(cwd, opts) {
      if (!cwd) cwd = ".";
      if (!opts) opts = {};
      const xfs = opts.fs || fs2;
      const ignore = opts.ignore || opts.filter || noop;
      const mapStream = opts.mapStream || echo;
      const statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort);
      const strict = opts.strict !== false;
      const umask = typeof opts.umask === "number" ? ~opts.umask : ~processUmask();
      const pack2 = 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(path2.join(cwd, filename), function(err, linkname) {
          if (err) return pack2.destroy(err);
          header.linkname = normalize2(linkname);
          pack2.entry(header, onnextentry);
        });
      }
      function onstat(err, filename, stat) {
        if (pack2.destroyed) return;
        if (err) return pack2.destroy(err);
        if (!filename) {
          if (opts.finalize !== false) pack2.finalize();
          return finish(pack2);
        }
        if (stat.isSocket()) return onnextentry();
        let header = {
          name: normalize2(filename),
          mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask,
          mtime: stat.mtime,
          size: stat.size,
          type: "file",
          uid: stat.uid,
          gid: stat.gid
        };
        if (stat.isDirectory()) {
          header.size = 0;
          header.type = "directory";
          header = map(header) || header;
          return pack2.entry(header, onnextentry);
        }
        if (stat.isSymbolicLink()) {
          header.size = 0;
          header.type = "symlink";
          header = map(header) || header;
          return onsymlink(filename, header);
        }
        header = map(header) || header;
        if (!stat.isFile()) {
          if (strict) return pack2.destroy(new Error("unsupported type for " + filename));
          return onnextentry();
        }
        const entry = pack2.entry(header, onnextentry);
        const rs = mapStream(xfs.createReadStream(path2.join(cwd, 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 pack2.destroy(err);
        statNext(onstat);
      }
      return pack2;
    };
    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(cwd, opts) {
      if (!cwd) cwd = ".";
      if (!opts) opts = {};
      cwd = path2.resolve(cwd);
      const xfs = opts.fs || fs2;
      const ignore = 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 = path2.join(cwd, path2.join("/", header.name));
        if (ignore(name, header)) {
          stream.resume();
          return next();
        }
        const dir = path2.join(name, ".") === path2.join(cwd, ".") ? cwd : path2.dirname(name);
        validate(xfs, dir, path2.join(cwd, "."), 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
            }, stat);
          }
          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 stat(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 = path2.resolve(path2.dirname(name), header.linkname);
            if (!inCwd(dst) && validateSymLinks) return next(new Error(name + " is not a valid symlink"));
            validateNotSymlink(xfs, dst, path2.join(cwd, "."), function(err, valid) {
              if (err) return next(err);
              if (!valid && validateSymLinks) return next(new Error(name + " is not a valid symlink"));
              xfs.symlink(header.linkname, name, stat);
            });
          });
        }
        function onlink() {
          if (win32) return next();
          xfs.unlink(name, function() {
            const link = path2.join(cwd, path2.join("/", header.linkname));
            xfs.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();
                }
                stat(err2);
              });
            });
          });
        }
        function inCwd(dst) {
          return dst === cwd || dst.startsWith(cwd + path2.sep);
        }
        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", stat);
          });
        }
      }
      function utimesParent(name, cb) {
        let top2;
        while ((top2 = head(stack)) && name.slice(0, top2[0].length) !== top2[0]) stack.pop();
        if (!top2) return cb();
        xfs.utimes(top2[0], now, top2[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 mode2 = (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, mode2, 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 validateNotSymlink(fs3, name, root, cb) {
      if (name === root) return cb(null, true);
      if (!name.startsWith(root + path2.sep)) return cb(null, false);
      fs3.lstat(name, function(err, st) {
        if (err && err.code !== "ENOENT" && err.code !== "EPERM") return cb(err);
        if (err || !st.isSymbolicLink()) return validateNotSymlink(fs3, path2.join(name, ".."), root, cb);
        cb(null, false);
      });
    }
    function validate(fs3, name, root, cb) {
      if (name === root) return cb(null, true);
      fs3.lstat(name, function(err, st) {
        if (err && err.code !== "ENOENT" && err.code !== "EPERM") return cb(err);
        if (err || st.isDirectory()) return validate(fs3, path2.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(fs3, stat, cwd, ignore, 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 = path2.join(cwd, next);
        stat.call(fs3, nextAbs, function(err, stat2) {
          if (err) return callback(entries.indexOf(next) === -1 && err.code === "ENOENT" ? null : err);
          if (!stat2.isDirectory()) return callback(null, next, stat2);
          fs3.readdir(nextAbs, function(err2, files) {
            if (err2) return callback(err2);
            if (sort) files.sort();
            for (let i = 0; i < files.length; i++) {
              if (!ignore(path2.join(cwd, next, files[i]))) queue.push(path2.join(next, files[i]));
            }
            callback(null, next, stat2);
          });
        });
      };
    }
    function strip(map, level) {
      return function(header) {
        header.name = header.name.split("/").slice(level).join("/");
        const linkname = header.linkname;
        if (linkname && (header.type === "link" || path2.isAbsolute(linkname))) {
          header.linkname = linkname.split("/").slice(level).join("/");
        }
        return map(header);
      };
    }
  }
});

// node_modules/@puppeteer/browsers/lib/cjs/fileUtil.js
var require_fileUtil = __commonJS({
  "node_modules/@puppeteer/browsers/lib/cjs/fileUtil.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
      var ownKeys2 = function(o) {
        ownKeys2 = 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 ownKeys2(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]);
        }
        __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.internalConstantsForTesting = void 0;
    exports2.unpackArchive = unpackArchive;
    var node_child_process_1 = require("node:child_process");
    var node_fs_1 = require("node:fs");
    var promises_1 = require("node:fs/promises");
    var path2 = __importStar2(require("node:path"));
    var node_stream_1 = require("node:stream");
    var debug_1 = __importDefault2(require_src());
    var debugFileUtil = (0, debug_1.default)("puppeteer:browsers:fileUtil");
    async function unpackArchive(archivePath, folderPath) {
      if (!path2.isAbsolute(folderPath)) {
        folderPath = path2.resolve(process.cwd(), folderPath);
      }
      if (archivePath.endsWith(".zip")) {
        const extractZip = await Promise.resolve().then(() => __toESM(require_extract_zip()));
        await extractZip.default(archivePath, { dir: folderPath });
      } else if (archivePath.endsWith(".tar.bz2")) {
        await extractTar(archivePath, folderPath, "bzip2");
      } else if (archivePath.endsWith(".dmg")) {
        await (0, promises_1.mkdir)(folderPath);
        await installDMG(archivePath, folderPath);
      } else if (archivePath.endsWith(".exe")) {
        const result = (0, node_child_process_1.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 node_stream_1.Stream.Transform({
        transform(chunk, encoding, callback) {
          if (!child.stdin.write(chunk, encoding)) {
            child.stdin.once("drain", callback);
          } else {
            callback();
          }
        },
        flush(callback) {
          if (child.stdout.destroyed) {
            callback();
          } else {
            child.stdin.end();
            child.stdout.on("close", callback);
          }
        }
      });
      child.stdin.on("error", (e) => {
        if ("code" in e && e.code === "EPIPE") {
          stream.emit("end");
        } else {
          stream.destroy(e);
        }
      });
      child.stdout.on("data", (data) => {
        return stream.push(data);
      }).on("error", (e) => {
        return stream.destroy(e);
      });
      child.once("close", () => {
        return stream.end();
      });
      return stream;
    }
    exports2.internalConstantsForTesting = {
      xz: "xz",
      bzip2: "bzip2"
    };
    async function extractTar(tarPath, folderPath, decompressUtilityName) {
      const tarFs = await Promise.resolve().then(() => __toESM(require_tar_fs()));
      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 unpack = (0, node_child_process_1.spawn)(exports2.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, node_fs_1.createReadStream)(tarPath).pipe(createTransformStream(unpack)).pipe(tar);
      });
    }
    async function installDMG(dmgPath, folderPath) {
      const { stdout } = (0, node_child_process_1.spawnSync)(`hdiutil`, [
        "attach",
        "-nobrowse",
        "-noautoopen",
        dmgPath
      ]);
      const volumes = stdout.toString("utf8").match(/\/Volumes\/(.*)/m);
      if (!volumes) {
        throw new Error(`Could not find volume path in ${stdout}`);
      }
      const mountPath = volumes[0];
      try {
        const fileNames = await (0, promises_1.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 = path2.join(mountPath, appName);
        (0, node_child_process_1.spawnSync)("cp", ["-R", mountedPath, folderPath]);
      } finally {
        (0, node_child_process_1.spawnSync)("hdiutil", ["detach", mountPath, "-quiet"]);
      }
    }
  }
});

// node_modules/@puppeteer/browsers/lib/cjs/install.js
var require_install = __commonJS({
  "node_modules/@puppeteer/browsers/lib/cjs/install.js"(exports2) {
    "use strict";
    init_prefix();
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.install = install;
    exports2.uninstall = uninstall;
    exports2.getInstalledBrowsers = getInstalledBrowsers;
    exports2.canDownload = canDownload;
    exports2.getDownloadUrl = getDownloadUrl;
    exports2.makeProgressCallback = makeProgressCallback;
    var node_assert_1 = __importDefault2(require("node:assert"));
    var node_child_process_1 = require("node:child_process");
    var node_fs_1 = require("node:fs");
    var promises_1 = require("node:fs/promises");
    var node_os_1 = __importDefault2(require("node:os"));
    var node_path_1 = __importDefault2(require("node:path"));
    var progress_1 = __importDefault2(require_progress());
    var browser_data_js_1 = require_browser_data();
    var Cache_js_1 = require_Cache();
    var debug_js_1 = require_debug3();
    var DefaultProvider_js_1 = require_DefaultProvider();
    var detectPlatform_js_1 = require_detectPlatform();
    var fileUtil_js_1 = require_fileUtil();
    var httpUtil_js_1 = require_httpUtil();
    var debugInstall = (0, debug_js_1.debug)("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 installWithProviders(options) {
      if (!options.platform) {
        throw new Error("Platform must be defined");
      }
      const cache = new Cache_js_1.Cache(options.cacheDir);
      const browserRoot = cache.browserRoot(options.browser);
      const providers = [...options.providers || []];
      if (options.baseUrl) {
        providers.push(new DefaultProvider_js_1.DefaultProvider(options.baseUrl));
      }
      if (!options.baseUrl || options.forceFallbackForTesting) {
        providers.push(new DefaultProvider_js_1.DefaultProvider());
      }
      const downloadOptions = {
        browser: options.browser,
        platform: options.platform,
        buildId: options.buildId,
        progressCallback: options.downloadProgressCallback === "default" ? await makeProgressCallback(options.browser, options.buildIdAlias ?? options.buildId) : options.downloadProgressCallback
      };
      const errors = [];
      for (const provider of providers) {
        try {
          if (!await provider.supports(downloadOptions)) {
            debugInstall(`Provider ${provider.getName()} does not support ${options.browser} on ${options.platform}`);
            continue;
          }
          if (!(provider instanceof DefaultProvider_js_1.DefaultProvider)) {
            debugInstall(`\u26A0\uFE0F  Using custom downloader: ${provider.getName()}`);
            debugInstall(`\u26A0\uFE0F  Puppeteer does not guarantee compatibility with non-default providers`);
          }
          debugInstall(`Trying provider: ${provider.getName()} for ${options.browser} ${options.buildId}`);
          const url = await provider.getDownloadUrl(downloadOptions);
          if (!url) {
            debugInstall(`Provider ${provider.getName()} returned no URL for ${options.browser} ${options.buildId}`);
            continue;
          }
          debugInstall(`Successfully got URL from ${provider.getName()}: ${url}`);
          if (!(0, node_fs_1.existsSync)(browserRoot)) {
            await (0, promises_1.mkdir)(browserRoot, { recursive: true });
          }
          return await installUrl(url, options, provider);
        } catch (err) {
          debugInstall(`Provider ${provider.getName()} failed: ${err.message}`);
          errors.push({
            providerName: provider.getName(),
            error: err
          });
        }
      }
      const errorDetails = errors.map((e) => {
        return `  - ${e.providerName}: ${e.error.message}`;
      }).join("\n");
      throw new Error(`All providers failed for ${options.browser} ${options.buildId}:
${errorDetails}`);
    }
    async function install(options) {
      options.platform ??= (0, detectPlatform_js_1.detectBrowserPlatform)();
      options.unpack ??= true;
      if (!options.platform) {
        throw new Error(`Cannot download a binary for the provided platform: ${node_os_1.default.platform()} (${node_os_1.default.arch()})`);
      }
      options.providers ??= [];
      return await installWithProviders(options);
    }
    async function installDeps(installedBrowser) {
      if (process.platform !== "linux" || installedBrowser.platform !== browser_data_js_1.BrowserPlatform.LINUX) {
        return;
      }
      const depsPath = node_path_1.default.join(node_path_1.default.dirname(installedBrowser.executablePath), "deb.deps");
      if (!(0, node_fs_1.existsSync)(depsPath)) {
        debugInstall(`deb.deps file was not found at ${depsPath}`);
        return;
      }
      const data = (0, node_fs_1.readFileSync)(depsPath, "utf-8").split("\n").join(",");
      if (process.getuid?.() !== 0) {
        throw new Error("Installing system dependencies requires root privileges");
      }
      let result = (0, node_child_process_1.spawnSync)("apt-get", ["-v"]);
      if (result.status !== 0) {
        throw new Error("Failed to install system dependencies: apt-get does not seem to be available");
      }
      debugInstall(`Trying to install dependencies: ${data}`);
      result = (0, node_child_process_1.spawnSync)("apt-get", [
        "satisfy",
        "-y",
        data,
        "--no-install-recommends"
      ]);
      if (result.status !== 0) {
        throw new Error(`Failed to install system dependencies: status=${result.status},error=${result.error},stdout=${result.stdout.toString("utf8")},stderr=${result.stderr.toString("utf8")}`);
      }
      debugInstall(`Installed system dependencies ${data}`);
    }
    async function installUrl(url, options, provider) {
      if (!provider) {
        throw new Error("Provider is required for installation");
      }
      options.platform ??= (0, detectPlatform_js_1.detectBrowserPlatform)();
      if (!options.platform) {
        throw new Error(`Cannot download a binary for the provided platform: ${node_os_1.default.platform()} (${node_os_1.default.arch()})`);
      }
      let downloadProgressCallback = options.downloadProgressCallback;
      if (downloadProgressCallback === "default") {
        downloadProgressCallback = await makeProgressCallback(options.browser, options.buildIdAlias ?? options.buildId);
      }
      const fileName = decodeURIComponent(url.toString()).split("/").pop();
      (0, node_assert_1.default)(fileName, `A malformed download URL was found: ${url}.`);
      const cache = new Cache_js_1.Cache(options.cacheDir);
      const browserRoot = cache.browserRoot(options.browser);
      const archivePath = node_path_1.default.join(browserRoot, `${options.buildId}-${fileName}`);
      if (!(0, node_fs_1.existsSync)(browserRoot)) {
        await (0, promises_1.mkdir)(browserRoot, { recursive: true });
      }
      if (!options.unpack) {
        if ((0, node_fs_1.existsSync)(archivePath)) {
          return archivePath;
        }
        debugInstall(`Downloading binary from ${url}`);
        debugTime("download");
        await (0, httpUtil_js_1.downloadFile)(url, archivePath, downloadProgressCallback);
        debugTimeEnd("download");
        return archivePath;
      }
      const outputPath = cache.installationDir(options.browser, options.platform, options.buildId);
      const relativeExecutablePath = await provider.getExecutablePath({
        browser: options.browser,
        buildId: options.buildId,
        platform: options.platform
      });
      debugInstall(`Using executable path from provider: ${relativeExecutablePath}`);
      const installedBrowser = new Cache_js_1.InstalledBrowser(cache, options.browser, options.buildId, options.platform);
      if (!(provider instanceof DefaultProvider_js_1.DefaultProvider)) {
        cache.writeExecutablePath(options.browser, options.platform, options.buildId, relativeExecutablePath);
      }
      try {
        if ((0, node_fs_1.existsSync)(outputPath)) {
          if (!(0, node_fs_1.existsSync)(installedBrowser.executablePath)) {
            throw new Error(`The browser folder (${outputPath}) exists but the executable (${installedBrowser.executablePath}) is missing`);
          }
          await runSetup(installedBrowser);
          if (options.installDeps) {
            await installDeps(installedBrowser);
          }
          return installedBrowser;
        }
        if (!(0, node_fs_1.existsSync)(archivePath)) {
          debugInstall(`Downloading binary from ${url}`);
          try {
            debugTime("download");
            await (0, httpUtil_js_1.downloadFile)(url, archivePath, downloadProgressCallback);
          } finally {
            debugTimeEnd("download");
          }
        } else {
          debugInstall(`Using existing archive at ${archivePath}`);
        }
        debugInstall(`Installing ${archivePath} to ${outputPath}`);
        try {
          debugTime("extract");
          await (0, fileUtil_js_1.unpackArchive)(archivePath, outputPath);
        } finally {
          debugTimeEnd("extract");
        }
        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, node_fs_1.existsSync)(archivePath)) {
          await (0, promises_1.unlink)(archivePath);
        }
      }
    }
    async function runSetup(installedBrowser) {
      if ((installedBrowser.platform === browser_data_js_1.BrowserPlatform.WIN32 || installedBrowser.platform === browser_data_js_1.BrowserPlatform.WIN64) && installedBrowser.browser === browser_data_js_1.Browser.CHROME && installedBrowser.platform === (0, detectPlatform_js_1.detectBrowserPlatform)()) {
        try {
          debugTime("permissions");
          const browserDir = node_path_1.default.dirname(installedBrowser.executablePath);
          const setupExePath = node_path_1.default.join(browserDir, "setup.exe");
          if (!(0, node_fs_1.existsSync)(setupExePath)) {
            return;
          }
          (0, node_child_process_1.spawnSync)(node_path_1.default.join(browserDir, "setup.exe"), [`--configure-browser-in-directory=` + browserDir], {
            shell: true
          });
        } finally {
          debugTimeEnd("permissions");
        }
      }
    }
    async function uninstall(options) {
      options.platform ??= (0, detectPlatform_js_1.detectBrowserPlatform)();
      if (!options.platform) {
        throw new Error(`Cannot detect the browser platform for: ${node_os_1.default.platform()} (${node_os_1.default.arch()})`);
      }
      new Cache_js_1.Cache(options.cacheDir).uninstall(options.browser, options.platform, options.buildId);
    }
    async function getInstalledBrowsers(options) {
      return new Cache_js_1.Cache(options.cacheDir).getInstalledBrowsers();
    }
    async function canDownload(options) {
      options.platform ??= (0, detectPlatform_js_1.detectBrowserPlatform)();
      if (!options.platform) {
        throw new Error(`Cannot download a binary for the provided platform: ${node_os_1.default.platform()} (${node_os_1.default.arch()})`);
      }
      const providers = [
        ...options.providers || [],
        new DefaultProvider_js_1.DefaultProvider(options.baseUrl)
      ];
      const downloadOptions = {
        browser: options.browser,
        platform: options.platform,
        buildId: options.buildId
      };
      for (const provider of providers) {
        if (!await provider.supports(downloadOptions)) {
          continue;
        }
        const url = await provider.getDownloadUrl(downloadOptions);
        if (url && await (0, httpUtil_js_1.headHttpRequest)(url)) {
          return true;
        }
      }
      return false;
    }
    function getDownloadUrl(browser, platform, buildId, baseUrl) {
      return new URL(browser_data_js_1.downloadUrls[browser](platform, buildId, baseUrl));
    }
    function makeProgressCallback(browser, buildId) {
      let progressBar;
      let lastDownloadedBytes = 0;
      return (downloadedBytes, totalBytes) => {
        if (!progressBar) {
          progressBar = new progress_1.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`;
    }
  }
});

// node_modules/cliui/build/lib/index.js
function addBorder(col, ts, style) {
  if (col.border) {
    if (/[.']-+[.']/.test(ts)) {
      return "";
    }
    if (ts.trim().length !== 0) {
      return style;
    }
    return "  ";
  }
  return "";
}
function _minWidth(col) {
  const padding = col.padding || [];
  const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
  if (col.border) {
    return minWidth + 4;
  }
  return minWidth;
}
function getWindowWidth() {
  if (typeof process === "object" && process.stdout && process.stdout.columns) {
    return process.stdout.columns;
  }
  return 80;
}
function alignRight(str, width) {
  str = str.trim();
  const strWidth = mixin.stringWidth(str);
  if (strWidth < width) {
    return " ".repeat(width - strWidth) + str;
  }
  return str;
}
function alignCenter(str, width) {
  str = str.trim();
  const strWidth = mixin.stringWidth(str);
  if (strWidth >= width) {
    return str;
  }
  return " ".repeat(width - strWidth >> 1) + str;
}
function cliui(opts, _mixin) {
  mixin = _mixin;
  return new UI({
    width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
    wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
  });
}
var align, top, right, bottom, left, UI, mixin;
var init_lib = __esm({
  "node_modules/cliui/build/lib/index.js"() {
    "use strict";
    init_prefix();
    align = {
      right: alignRight,
      center: alignCenter
    };
    top = 0;
    right = 1;
    bottom = 2;
    left = 3;
    UI = class {
      constructor(opts) {
        var _a2;
        this.width = opts.width;
        this.wrap = (_a2 = opts.wrap) !== null && _a2 !== void 0 ? _a2 : true;
        this.rows = [];
      }
      span(...args2) {
        const cols = this.div(...args2);
        cols.span = true;
      }
      resetOutput() {
        this.rows = [];
      }
      div(...args2) {
        if (args2.length === 0) {
          this.div("");
        }
        if (this.wrap && this.shouldApplyLayoutDSL(...args2) && typeof args2[0] === "string") {
          return this.applyLayoutDSL(args2[0]);
        }
        const cols = args2.map((arg) => {
          if (typeof arg === "string") {
            return this.colFromString(arg);
          }
          return arg;
        });
        this.rows.push(cols);
        return cols;
      }
      shouldApplyLayoutDSL(...args2) {
        return args2.length === 1 && typeof args2[0] === "string" && /[\t\n]/.test(args2[0]);
      }
      applyLayoutDSL(str) {
        const rows = str.split("\n").map((row) => row.split("	"));
        let leftColumnWidth = 0;
        rows.forEach((columns) => {
          if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) {
            leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0]));
          }
        });
        rows.forEach((columns) => {
          this.div(...columns.map((r, i) => {
            return {
              text: r.trim(),
              padding: this.measurePadding(r),
              width: i === 0 && columns.length > 1 ? leftColumnWidth : void 0
            };
          }));
        });
        return this.rows[this.rows.length - 1];
      }
      colFromString(text) {
        return {
          text,
          padding: this.measurePadding(text)
        };
      }
      measurePadding(str) {
        const noAnsi = mixin.stripAnsi(str);
        return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
      }
      toString() {
        const lines = [];
        this.rows.forEach((row) => {
          this.rowToString(row, lines);
        });
        return lines.filter((line) => !line.hidden).map((line) => line.text).join("\n");
      }
      rowToString(row, lines) {
        this.rasterize(row).forEach((rrow, r) => {
          let str = "";
          rrow.forEach((col, c) => {
            const { width } = row[c];
            const wrapWidth = this.negatePadding(row[c]);
            let ts = col;
            if (wrapWidth > mixin.stringWidth(col)) {
              ts += " ".repeat(wrapWidth - mixin.stringWidth(col));
            }
            if (row[c].align && row[c].align !== "left" && this.wrap) {
              const fn = align[row[c].align];
              ts = fn(ts, wrapWidth);
              if (mixin.stringWidth(ts) < wrapWidth) {
                ts += " ".repeat((width || 0) - mixin.stringWidth(ts) - 1);
              }
            }
            const padding = row[c].padding || [0, 0, 0, 0];
            if (padding[left]) {
              str += " ".repeat(padding[left]);
            }
            str += addBorder(row[c], ts, "| ");
            str += ts;
            str += addBorder(row[c], ts, " |");
            if (padding[right]) {
              str += " ".repeat(padding[right]);
            }
            if (r === 0 && lines.length > 0) {
              str = this.renderInline(str, lines[lines.length - 1]);
            }
          });
          lines.push({
            text: str.replace(/ +$/, ""),
            span: row.span
          });
        });
        return lines;
      }
      // if the full 'source' can render in
      // the target line, do so.
      renderInline(source, previousLine) {
        const match = source.match(/^ */);
        const leadingWhitespace = match ? match[0].length : 0;
        const target = previousLine.text;
        const targetTextWidth = mixin.stringWidth(target.trimRight());
        if (!previousLine.span) {
          return source;
        }
        if (!this.wrap) {
          previousLine.hidden = true;
          return target + source;
        }
        if (leadingWhitespace < targetTextWidth) {
          return source;
        }
        previousLine.hidden = true;
        return target.trimRight() + " ".repeat(leadingWhitespace - targetTextWidth) + source.trimLeft();
      }
      rasterize(row) {
        const rrows = [];
        const widths = this.columnWidths(row);
        let wrapped;
        row.forEach((col, c) => {
          col.width = widths[c];
          if (this.wrap) {
            wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split("\n");
          } else {
            wrapped = col.text.split("\n");
          }
          if (col.border) {
            wrapped.unshift("." + "-".repeat(this.negatePadding(col) + 2) + ".");
            wrapped.push("'" + "-".repeat(this.negatePadding(col) + 2) + "'");
          }
          if (col.padding) {
            wrapped.unshift(...new Array(col.padding[top] || 0).fill(""));
            wrapped.push(...new Array(col.padding[bottom] || 0).fill(""));
          }
          wrapped.forEach((str, r) => {
            if (!rrows[r]) {
              rrows.push([]);
            }
            const rrow = rrows[r];
            for (let i = 0; i < c; i++) {
              if (rrow[i] === void 0) {
                rrow.push("");
              }
            }
            rrow.push(str);
          });
        });
        return rrows;
      }
      negatePadding(col) {
        let wrapWidth = col.width || 0;
        if (col.padding) {
          wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
        }
        if (col.border) {
          wrapWidth -= 4;
        }
        return wrapWidth;
      }
      columnWidths(row) {
        if (!this.wrap) {
          return row.map((col) => {
            return col.width || mixin.stringWidth(col.text);
          });
        }
        let unset = row.length;
        let remainingWidth = this.width;
        const widths = row.map((col) => {
          if (col.width) {
            unset--;
            remainingWidth -= col.width;
            return col.width;
          }
          return void 0;
        });
        const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
        return widths.map((w, i) => {
          if (w === void 0) {
            return Math.max(unsetWidth, _minWidth(row[i]));
          }
          return w;
        });
      }
    };
  }
});

// node_modules/cliui/build/lib/string-utils.js
function stripAnsi(str) {
  return str.replace(ansi, "");
}
function wrap(str, width) {
  const [start, end] = str.match(ansi) || ["", ""];
  str = stripAnsi(str);
  let wrapped = "";
  for (let i = 0; i < str.length; i++) {
    if (i !== 0 && i % width === 0) {
      wrapped += "\n";
    }
    wrapped += str.charAt(i);
  }
  if (start && end) {
    wrapped = `${start}${wrapped}${end}`;
  }
  return wrapped;
}
var ansi;
var init_string_utils = __esm({
  "node_modules/cliui/build/lib/string-utils.js"() {
    init_prefix();
    ansi = new RegExp("\x1B(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)", "g");
  }
});

// node_modules/cliui/index.mjs
function ui(opts) {
  return cliui(opts, {
    stringWidth: (str) => {
      return [...str].length;
    },
    stripAnsi,
    wrap
  });
}
var init_cliui = __esm({
  "node_modules/cliui/index.mjs"() {
    init_prefix();
    init_lib();
    init_string_utils();
  }
});

// node_modules/escalade/sync/index.mjs
function sync_default(start, callback) {
  let dir = (0, import_path.resolve)(".", start);
  let tmp, stats = (0, import_fs.statSync)(dir);
  if (!stats.isDirectory()) {
    dir = (0, import_path.dirname)(dir);
  }
  while (true) {
    tmp = callback(dir, (0, import_fs.readdirSync)(dir));
    if (tmp) return (0, import_path.resolve)(dir, tmp);
    dir = (0, import_path.dirname)(tmp = dir);
    if (tmp === dir) break;
  }
}
var import_path, import_fs;
var init_sync = __esm({
  "node_modules/escalade/sync/index.mjs"() {
    init_prefix();
    import_path = require("path");
    import_fs = require("fs");
  }
});

// node_modules/yargs-parser/build/lib/string-utils.js
function camelCase(str) {
  const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase();
  if (!isCamelCase) {
    str = str.toLowerCase();
  }
  if (str.indexOf("-") === -1 && str.indexOf("_") === -1) {
    return str;
  } else {
    let camelcase = "";
    let nextChrUpper = false;
    const leadingHyphens = str.match(/^-+/);
    for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) {
      let chr = str.charAt(i);
      if (nextChrUpper) {
        nextChrUpper = false;
        chr = chr.toUpperCase();
      }
      if (i !== 0 && (chr === "-" || chr === "_")) {
        nextChrUpper = true;
      } else if (chr !== "-" && chr !== "_") {
        camelcase += chr;
      }
    }
    return camelcase;
  }
}
function decamelize(str, joinString) {
  const lowercase = str.toLowerCase();
  joinString = joinString || "-";
  let notCamelcase = "";
  for (let i = 0; i < str.length; i++) {
    const chrLower = lowercase.charAt(i);
    const chrString = str.charAt(i);
    if (chrLower !== chrString && i > 0) {
      notCamelcase += `${joinString}${lowercase.charAt(i)}`;
    } else {
      notCamelcase += chrString;
    }
  }
  return notCamelcase;
}
function looksLikeNumber(x) {
  if (x === null || x === void 0)
    return false;
  if (typeof x === "number")
    return true;
  if (/^0x[0-9a-f]+$/i.test(x))
    return true;
  if (/^0[^.]/.test(x))
    return false;
  return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}
var init_string_utils2 = __esm({
  "node_modules/yargs-parser/build/lib/string-utils.js"() {
    init_prefix();
  }
});

// node_modules/yargs-parser/build/lib/tokenize-arg-string.js
function tokenizeArgString(argString) {
  if (Array.isArray(argString)) {
    return argString.map((e) => typeof e !== "string" ? e + "" : e);
  }
  argString = argString.trim();
  let i = 0;
  let prevC = null;
  let c = null;
  let opening = null;
  const args2 = [];
  for (let ii = 0; ii < argString.length; ii++) {
    prevC = c;
    c = argString.charAt(ii);
    if (c === " " && !opening) {
      if (!(prevC === " ")) {
        i++;
      }
      continue;
    }
    if (c === opening) {
      opening = null;
    } else if ((c === "'" || c === '"') && !opening) {
      opening = c;
    }
    if (!args2[i])
      args2[i] = "";
    args2[i] += c;
  }
  return args2;
}
var init_tokenize_arg_string = __esm({
  "node_modules/yargs-parser/build/lib/tokenize-arg-string.js"() {
    init_prefix();
  }
});

// node_modules/yargs-parser/build/lib/yargs-parser-types.js
var DefaultValuesForTypeKey;
var init_yargs_parser_types = __esm({
  "node_modules/yargs-parser/build/lib/yargs-parser-types.js"() {
    init_prefix();
    (function(DefaultValuesForTypeKey2) {
      DefaultValuesForTypeKey2["BOOLEAN"] = "boolean";
      DefaultValuesForTypeKey2["STRING"] = "string";
      DefaultValuesForTypeKey2["NUMBER"] = "number";
      DefaultValuesForTypeKey2["ARRAY"] = "array";
    })(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {}));
  }
});

// node_modules/yargs-parser/build/lib/yargs-parser.js
function combineAliases(aliases) {
  const aliasArrays = [];
  const combined = /* @__PURE__ */ Object.create(null);
  let change = true;
  Object.keys(aliases).forEach(function(key) {
    aliasArrays.push([].concat(aliases[key], key));
  });
  while (change) {
    change = false;
    for (let i = 0; i < aliasArrays.length; i++) {
      for (let ii = i + 1; ii < aliasArrays.length; ii++) {
        const intersect = aliasArrays[i].filter(function(v) {
          return aliasArrays[ii].indexOf(v) !== -1;
        });
        if (intersect.length) {
          aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]);
          aliasArrays.splice(ii, 1);
          change = true;
          break;
        }
      }
    }
  }
  aliasArrays.forEach(function(aliasArray) {
    aliasArray = aliasArray.filter(function(v, i, self2) {
      return self2.indexOf(v) === i;
    });
    const lastAlias = aliasArray.pop();
    if (lastAlias !== void 0 && typeof lastAlias === "string") {
      combined[lastAlias] = aliasArray;
    }
  });
  return combined;
}
function increment(orig) {
  return orig !== void 0 ? orig + 1 : 1;
}
function sanitizeKey(key) {
  if (key === "__proto__")
    return "___proto___";
  return key;
}
function stripQuotes(val) {
  return typeof val === "string" && (val[0] === "'" || val[0] === '"') && val[val.length - 1] === val[0] ? val.substring(1, val.length - 1) : val;
}
var mixin2, YargsParser;
var init_yargs_parser = __esm({
  "node_modules/yargs-parser/build/lib/yargs-parser.js"() {
    init_prefix();
    init_tokenize_arg_string();
    init_yargs_parser_types();
    init_string_utils2();
    YargsParser = class {
      constructor(_mixin) {
        mixin2 = _mixin;
      }
      parse(argsInput, options) {
        const opts = Object.assign({
          alias: void 0,
          array: void 0,
          boolean: void 0,
          config: void 0,
          configObjects: void 0,
          configuration: void 0,
          coerce: void 0,
          count: void 0,
          default: void 0,
          envPrefix: void 0,
          narg: void 0,
          normalize: void 0,
          string: void 0,
          number: void 0,
          __: void 0,
          key: void 0
        }, options);
        const args2 = tokenizeArgString(argsInput);
        const inputIsString = typeof argsInput === "string";
        const aliases = combineAliases(Object.assign(/* @__PURE__ */ Object.create(null), opts.alias));
        const configuration = Object.assign({
          "boolean-negation": true,
          "camel-case-expansion": true,
          "combine-arrays": false,
          "dot-notation": true,
          "duplicate-arguments-array": true,
          "flatten-duplicate-arrays": true,
          "greedy-arrays": true,
          "halt-at-non-option": false,
          "nargs-eats-options": false,
          "negation-prefix": "no-",
          "parse-numbers": true,
          "parse-positional-numbers": true,
          "populate--": false,
          "set-placeholder-key": false,
          "short-option-groups": true,
          "strip-aliased": false,
          "strip-dashed": false,
          "unknown-options-as-args": false
        }, opts.configuration);
        const defaults = Object.assign(/* @__PURE__ */ Object.create(null), opts.default);
        const configObjects = opts.configObjects || [];
        const envPrefix = opts.envPrefix;
        const notFlagsOption = configuration["populate--"];
        const notFlagsArgv = notFlagsOption ? "--" : "_";
        const newAliases = /* @__PURE__ */ Object.create(null);
        const defaulted = /* @__PURE__ */ Object.create(null);
        const __ = opts.__ || mixin2.format;
        const flags = {
          aliases: /* @__PURE__ */ Object.create(null),
          arrays: /* @__PURE__ */ Object.create(null),
          bools: /* @__PURE__ */ Object.create(null),
          strings: /* @__PURE__ */ Object.create(null),
          numbers: /* @__PURE__ */ Object.create(null),
          counts: /* @__PURE__ */ Object.create(null),
          normalize: /* @__PURE__ */ Object.create(null),
          configs: /* @__PURE__ */ Object.create(null),
          nargs: /* @__PURE__ */ Object.create(null),
          coercions: /* @__PURE__ */ Object.create(null),
          keys: []
        };
        const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/;
        const negatedBoolean = new RegExp("^--" + configuration["negation-prefix"] + "(.+)");
        [].concat(opts.array || []).filter(Boolean).forEach(function(opt) {
          const key = typeof opt === "object" ? opt.key : opt;
          const assignment = Object.keys(opt).map(function(key2) {
            const arrayFlagKeys = {
              boolean: "bools",
              string: "strings",
              number: "numbers"
            };
            return arrayFlagKeys[key2];
          }).filter(Boolean).pop();
          if (assignment) {
            flags[assignment][key] = true;
          }
          flags.arrays[key] = true;
          flags.keys.push(key);
        });
        [].concat(opts.boolean || []).filter(Boolean).forEach(function(key) {
          flags.bools[key] = true;
          flags.keys.push(key);
        });
        [].concat(opts.string || []).filter(Boolean).forEach(function(key) {
          flags.strings[key] = true;
          flags.keys.push(key);
        });
        [].concat(opts.number || []).filter(Boolean).forEach(function(key) {
          flags.numbers[key] = true;
          flags.keys.push(key);
        });
        [].concat(opts.count || []).filter(Boolean).forEach(function(key) {
          flags.counts[key] = true;
          flags.keys.push(key);
        });
        [].concat(opts.normalize || []).filter(Boolean).forEach(function(key) {
          flags.normalize[key] = true;
          flags.keys.push(key);
        });
        if (typeof opts.narg === "object") {
          Object.entries(opts.narg).forEach(([key, value]) => {
            if (typeof value === "number") {
              flags.nargs[key] = value;
              flags.keys.push(key);
            }
          });
        }
        if (typeof opts.coerce === "object") {
          Object.entries(opts.coerce).forEach(([key, value]) => {
            if (typeof value === "function") {
              flags.coercions[key] = value;
              flags.keys.push(key);
            }
          });
        }
        if (typeof opts.config !== "undefined") {
          if (Array.isArray(opts.config) || typeof opts.config === "string") {
            ;
            [].concat(opts.config).filter(Boolean).forEach(function(key) {
              flags.configs[key] = true;
            });
          } else if (typeof opts.config === "object") {
            Object.entries(opts.config).forEach(([key, value]) => {
              if (typeof value === "boolean" || typeof value === "function") {
                flags.configs[key] = value;
              }
            });
          }
        }
        extendAliases(opts.key, aliases, opts.default, flags.arrays);
        Object.keys(defaults).forEach(function(key) {
          (flags.aliases[key] || []).forEach(function(alias) {
            defaults[alias] = defaults[key];
          });
        });
        let error = null;
        checkConfiguration();
        let notFlags = [];
        const argv = Object.assign(/* @__PURE__ */ Object.create(null), { _: [] });
        const argvReturn = {};
        for (let i = 0; i < args2.length; i++) {
          const arg = args2[i];
          const truncatedArg = arg.replace(/^-{3,}/, "---");
          let broken;
          let key;
          let letters;
          let m;
          let next;
          let value;
          if (arg !== "--" && /^-/.test(arg) && isUnknownOptionAsArg(arg)) {
            pushPositional(arg);
          } else if (truncatedArg.match(/^---+(=|$)/)) {
            pushPositional(arg);
            continue;
          } else if (arg.match(/^--.+=/) || !configuration["short-option-groups"] && arg.match(/^-.+=/)) {
            m = arg.match(/^--?([^=]+)=([\s\S]*)$/);
            if (m !== null && Array.isArray(m) && m.length >= 3) {
              if (checkAllAliases(m[1], flags.arrays)) {
                i = eatArray(i, m[1], args2, m[2]);
              } else if (checkAllAliases(m[1], flags.nargs) !== false) {
                i = eatNargs(i, m[1], args2, m[2]);
              } else {
                setArg(m[1], m[2], true);
              }
            }
          } else if (arg.match(negatedBoolean) && configuration["boolean-negation"]) {
            m = arg.match(negatedBoolean);
            if (m !== null && Array.isArray(m) && m.length >= 2) {
              key = m[1];
              setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false);
            }
          } else if (arg.match(/^--.+/) || !configuration["short-option-groups"] && arg.match(/^-[^-]+/)) {
            m = arg.match(/^--?(.+)/);
            if (m !== null && Array.isArray(m) && m.length >= 2) {
              key = m[1];
              if (checkAllAliases(key, flags.arrays)) {
                i = eatArray(i, key, args2);
              } else if (checkAllAliases(key, flags.nargs) !== false) {
                i = eatNargs(i, key, args2);
              } else {
                next = args2[i + 1];
                if (next !== void 0 && (!next.match(/^-/) || next.match(negative)) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) {
                  setArg(key, next);
                  i++;
                } else if (/^(true|false)$/.test(next)) {
                  setArg(key, next);
                  i++;
                } else {
                  setArg(key, defaultValue(key));
                }
              }
            }
          } else if (arg.match(/^-.\..+=/)) {
            m = arg.match(/^-([^=]+)=([\s\S]*)$/);
            if (m !== null && Array.isArray(m) && m.length >= 3) {
              setArg(m[1], m[2]);
            }
          } else if (arg.match(/^-.\..+/) && !arg.match(negative)) {
            next = args2[i + 1];
            m = arg.match(/^-(.\..+)/);
            if (m !== null && Array.isArray(m) && m.length >= 2) {
              key = m[1];
              if (next !== void 0 && !next.match(/^-/) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) {
                setArg(key, next);
                i++;
              } else {
                setArg(key, defaultValue(key));
              }
            }
          } else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
            letters = arg.slice(1, -1).split("");
            broken = false;
            for (let j = 0; j < letters.length; j++) {
              next = arg.slice(j + 2);
              if (letters[j + 1] && letters[j + 1] === "=") {
                value = arg.slice(j + 3);
                key = letters[j];
                if (checkAllAliases(key, flags.arrays)) {
                  i = eatArray(i, key, args2, value);
                } else if (checkAllAliases(key, flags.nargs) !== false) {
                  i = eatNargs(i, key, args2, value);
                } else {
                  setArg(key, value);
                }
                broken = true;
                break;
              }
              if (next === "-") {
                setArg(letters[j], next);
                continue;
              }
              if (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && checkAllAliases(next, flags.bools) === false) {
                setArg(letters[j], next);
                broken = true;
                break;
              }
              if (letters[j + 1] && letters[j + 1].match(/\W/)) {
                setArg(letters[j], next);
                broken = true;
                break;
              } else {
                setArg(letters[j], defaultValue(letters[j]));
              }
            }
            key = arg.slice(-1)[0];
            if (!broken && key !== "-") {
              if (checkAllAliases(key, flags.arrays)) {
                i = eatArray(i, key, args2);
              } else if (checkAllAliases(key, flags.nargs) !== false) {
                i = eatNargs(i, key, args2);
              } else {
                next = args2[i + 1];
                if (next !== void 0 && (!/^(-|--)[^-]/.test(next) || next.match(negative)) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) {
                  setArg(key, next);
                  i++;
                } else if (/^(true|false)$/.test(next)) {
                  setArg(key, next);
                  i++;
                } else {
                  setArg(key, defaultValue(key));
                }
              }
            }
          } else if (arg.match(/^-[0-9]$/) && arg.match(negative) && checkAllAliases(arg.slice(1), flags.bools)) {
            key = arg.slice(1);
            setArg(key, defaultValue(key));
          } else if (arg === "--") {
            notFlags = args2.slice(i + 1);
            break;
          } else if (configuration["halt-at-non-option"]) {
            notFlags = args2.slice(i);
            break;
          } else {
            pushPositional(arg);
          }
        }
        applyEnvVars(argv, true);
        applyEnvVars(argv, false);
        setConfig(argv);
        setConfigObjects();
        applyDefaultsAndAliases(argv, flags.aliases, defaults, true);
        applyCoercions(argv);
        if (configuration["set-placeholder-key"])
          setPlaceholderKeys(argv);
        Object.keys(flags.counts).forEach(function(key) {
          if (!hasKey(argv, key.split(".")))
            setArg(key, 0);
        });
        if (notFlagsOption && notFlags.length)
          argv[notFlagsArgv] = [];
        notFlags.forEach(function(key) {
          argv[notFlagsArgv].push(key);
        });
        if (configuration["camel-case-expansion"] && configuration["strip-dashed"]) {
          Object.keys(argv).filter((key) => key !== "--" && key.includes("-")).forEach((key) => {
            delete argv[key];
          });
        }
        if (configuration["strip-aliased"]) {
          ;
          [].concat(...Object.keys(aliases).map((k) => aliases[k])).forEach((alias) => {
            if (configuration["camel-case-expansion"] && alias.includes("-")) {
              delete argv[alias.split(".").map((prop) => camelCase(prop)).join(".")];
            }
            delete argv[alias];
          });
        }
        function pushPositional(arg) {
          const maybeCoercedNumber = maybeCoerceNumber("_", arg);
          if (typeof maybeCoercedNumber === "string" || typeof maybeCoercedNumber === "number") {
            argv._.push(maybeCoercedNumber);
          }
        }
        function eatNargs(i, key, args3, argAfterEqualSign) {
          let ii;
          let toEat = checkAllAliases(key, flags.nargs);
          toEat = typeof toEat !== "number" || isNaN(toEat) ? 1 : toEat;
          if (toEat === 0) {
            if (!isUndefined(argAfterEqualSign)) {
              error = Error(__("Argument unexpected for: %s", key));
            }
            setArg(key, defaultValue(key));
            return i;
          }
          let available = isUndefined(argAfterEqualSign) ? 0 : 1;
          if (configuration["nargs-eats-options"]) {
            if (args3.length - (i + 1) + available < toEat) {
              error = Error(__("Not enough arguments following: %s", key));
            }
            available = toEat;
          } else {
            for (ii = i + 1; ii < args3.length; ii++) {
              if (!args3[ii].match(/^-[^0-9]/) || args3[ii].match(negative) || isUnknownOptionAsArg(args3[ii]))
                available++;
              else
                break;
            }
            if (available < toEat)
              error = Error(__("Not enough arguments following: %s", key));
          }
          let consumed = Math.min(available, toEat);
          if (!isUndefined(argAfterEqualSign) && consumed > 0) {
            setArg(key, argAfterEqualSign);
            consumed--;
          }
          for (ii = i + 1; ii < consumed + i + 1; ii++) {
            setArg(key, args3[ii]);
          }
          return i + consumed;
        }
        function eatArray(i, key, args3, argAfterEqualSign) {
          let argsToSet = [];
          let next = argAfterEqualSign || args3[i + 1];
          const nargsCount = checkAllAliases(key, flags.nargs);
          if (checkAllAliases(key, flags.bools) && !/^(true|false)$/.test(next)) {
            argsToSet.push(true);
          } else if (isUndefined(next) || isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) {
            if (defaults[key] !== void 0) {
              const defVal = defaults[key];
              argsToSet = Array.isArray(defVal) ? defVal : [defVal];
            }
          } else {
            if (!isUndefined(argAfterEqualSign)) {
              argsToSet.push(processValue(key, argAfterEqualSign, true));
            }
            for (let ii = i + 1; ii < args3.length; ii++) {
              if (!configuration["greedy-arrays"] && argsToSet.length > 0 || nargsCount && typeof nargsCount === "number" && argsToSet.length >= nargsCount)
                break;
              next = args3[ii];
              if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))
                break;
              i = ii;
              argsToSet.push(processValue(key, next, inputIsString));
            }
          }
          if (typeof nargsCount === "number" && (nargsCount && argsToSet.length < nargsCount || isNaN(nargsCount) && argsToSet.length === 0)) {
            error = Error(__("Not enough arguments following: %s", key));
          }
          setArg(key, argsToSet);
          return i;
        }
        function setArg(key, val, shouldStripQuotes = inputIsString) {
          if (/-/.test(key) && configuration["camel-case-expansion"]) {
            const alias = key.split(".").map(function(prop) {
              return camelCase(prop);
            }).join(".");
            addNewAlias(key, alias);
          }
          const value = processValue(key, val, shouldStripQuotes);
          const splitKey = key.split(".");
          setKey(argv, splitKey, value);
          if (flags.aliases[key]) {
            flags.aliases[key].forEach(function(x) {
              const keyProperties = x.split(".");
              setKey(argv, keyProperties, value);
            });
          }
          if (splitKey.length > 1 && configuration["dot-notation"]) {
            ;
            (flags.aliases[splitKey[0]] || []).forEach(function(x) {
              let keyProperties = x.split(".");
              const a = [].concat(splitKey);
              a.shift();
              keyProperties = keyProperties.concat(a);
              if (!(flags.aliases[key] || []).includes(keyProperties.join("."))) {
                setKey(argv, keyProperties, value);
              }
            });
          }
          if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
            const keys = [key].concat(flags.aliases[key] || []);
            keys.forEach(function(key2) {
              Object.defineProperty(argvReturn, key2, {
                enumerable: true,
                get() {
                  return val;
                },
                set(value2) {
                  val = typeof value2 === "string" ? mixin2.normalize(value2) : value2;
                }
              });
            });
          }
        }
        function addNewAlias(key, alias) {
          if (!(flags.aliases[key] && flags.aliases[key].length)) {
            flags.aliases[key] = [alias];
            newAliases[alias] = true;
          }
          if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
            addNewAlias(alias, key);
          }
        }
        function processValue(key, val, shouldStripQuotes) {
          if (shouldStripQuotes) {
            val = stripQuotes(val);
          }
          if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
            if (typeof val === "string")
              val = val === "true";
          }
          let value = Array.isArray(val) ? val.map(function(v) {
            return maybeCoerceNumber(key, v);
          }) : maybeCoerceNumber(key, val);
          if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === "boolean")) {
            value = increment();
          }
          if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
            if (Array.isArray(val))
              value = val.map((val2) => {
                return mixin2.normalize(val2);
              });
            else
              value = mixin2.normalize(val);
          }
          return value;
        }
        function maybeCoerceNumber(key, value) {
          if (!configuration["parse-positional-numbers"] && key === "_")
            return value;
          if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) {
            const shouldCoerceNumber = looksLikeNumber(value) && configuration["parse-numbers"] && Number.isSafeInteger(Math.floor(parseFloat(`${value}`)));
            if (shouldCoerceNumber || !isUndefined(value) && checkAllAliases(key, flags.numbers)) {
              value = Number(value);
            }
          }
          return value;
        }
        function setConfig(argv2) {
          const configLookup = /* @__PURE__ */ Object.create(null);
          applyDefaultsAndAliases(configLookup, flags.aliases, defaults);
          Object.keys(flags.configs).forEach(function(configKey) {
            const configPath2 = argv2[configKey] || configLookup[configKey];
            if (configPath2) {
              try {
                let config2 = null;
                const resolvedConfigPath = mixin2.resolve(mixin2.cwd(), configPath2);
                const resolveConfig = flags.configs[configKey];
                if (typeof resolveConfig === "function") {
                  try {
                    config2 = resolveConfig(resolvedConfigPath);
                  } catch (e) {
                    config2 = e;
                  }
                  if (config2 instanceof Error) {
                    error = config2;
                    return;
                  }
                } else {
                  config2 = mixin2.require(resolvedConfigPath);
                }
                setConfigObject(config2);
              } catch (ex) {
                if (ex.name === "PermissionDenied")
                  error = ex;
                else if (argv2[configKey])
                  error = Error(__("Invalid JSON config file: %s", configPath2));
              }
            }
          });
        }
        function setConfigObject(config2, prev) {
          Object.keys(config2).forEach(function(key) {
            const value = config2[key];
            const fullKey = prev ? prev + "." + key : key;
            if (typeof value === "object" && value !== null && !Array.isArray(value) && configuration["dot-notation"]) {
              setConfigObject(value, fullKey);
            } else {
              if (!hasKey(argv, fullKey.split(".")) || checkAllAliases(fullKey, flags.arrays) && configuration["combine-arrays"]) {
                setArg(fullKey, value);
              }
            }
          });
        }
        function setConfigObjects() {
          if (typeof configObjects !== "undefined") {
            configObjects.forEach(function(configObject) {
              setConfigObject(configObject);
            });
          }
        }
        function applyEnvVars(argv2, configOnly) {
          if (typeof envPrefix === "undefined")
            return;
          const prefix = typeof envPrefix === "string" ? envPrefix : "";
          const env2 = mixin2.env();
          Object.keys(env2).forEach(function(envVar) {
            if (prefix === "" || envVar.lastIndexOf(prefix, 0) === 0) {
              const keys = envVar.split("__").map(function(key, i) {
                if (i === 0) {
                  key = key.substring(prefix.length);
                }
                return camelCase(key);
              });
              if ((configOnly && flags.configs[keys.join(".")] || !configOnly) && !hasKey(argv2, keys)) {
                setArg(keys.join("."), env2[envVar]);
              }
            }
          });
        }
        function applyCoercions(argv2) {
          let coerce;
          const applied = /* @__PURE__ */ new Set();
          Object.keys(argv2).forEach(function(key) {
            if (!applied.has(key)) {
              coerce = checkAllAliases(key, flags.coercions);
              if (typeof coerce === "function") {
                try {
                  const value = maybeCoerceNumber(key, coerce(argv2[key]));
                  [].concat(flags.aliases[key] || [], key).forEach((ali) => {
                    applied.add(ali);
                    argv2[ali] = value;
                  });
                } catch (err) {
                  error = err;
                }
              }
            }
          });
        }
        function setPlaceholderKeys(argv2) {
          flags.keys.forEach((key) => {
            if (~key.indexOf("."))
              return;
            if (typeof argv2[key] === "undefined")
              argv2[key] = void 0;
          });
          return argv2;
        }
        function applyDefaultsAndAliases(obj, aliases2, defaults2, canLog = false) {
          Object.keys(defaults2).forEach(function(key) {
            if (!hasKey(obj, key.split("."))) {
              setKey(obj, key.split("."), defaults2[key]);
              if (canLog)
                defaulted[key] = true;
              (aliases2[key] || []).forEach(function(x) {
                if (hasKey(obj, x.split(".")))
                  return;
                setKey(obj, x.split("."), defaults2[key]);
              });
            }
          });
        }
        function hasKey(obj, keys) {
          let o = obj;
          if (!configuration["dot-notation"])
            keys = [keys.join(".")];
          keys.slice(0, -1).forEach(function(key2) {
            o = o[key2] || {};
          });
          const key = keys[keys.length - 1];
          if (typeof o !== "object")
            return false;
          else
            return key in o;
        }
        function setKey(obj, keys, value) {
          let o = obj;
          if (!configuration["dot-notation"])
            keys = [keys.join(".")];
          keys.slice(0, -1).forEach(function(key2) {
            key2 = sanitizeKey(key2);
            if (typeof o === "object" && o[key2] === void 0) {
              o[key2] = {};
            }
            if (typeof o[key2] !== "object" || Array.isArray(o[key2])) {
              if (Array.isArray(o[key2])) {
                o[key2].push({});
              } else {
                o[key2] = [o[key2], {}];
              }
              o = o[key2][o[key2].length - 1];
            } else {
              o = o[key2];
            }
          });
          const key = sanitizeKey(keys[keys.length - 1]);
          const isTypeArray = checkAllAliases(keys.join("."), flags.arrays);
          const isValueArray = Array.isArray(value);
          let duplicate = configuration["duplicate-arguments-array"];
          if (!duplicate && checkAllAliases(key, flags.nargs)) {
            duplicate = true;
            if (!isUndefined(o[key]) && flags.nargs[key] === 1 || Array.isArray(o[key]) && o[key].length === flags.nargs[key]) {
              o[key] = void 0;
            }
          }
          if (value === increment()) {
            o[key] = increment(o[key]);
          } else if (Array.isArray(o[key])) {
            if (duplicate && isTypeArray && isValueArray) {
              o[key] = configuration["flatten-duplicate-arrays"] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]);
            } else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
              o[key] = value;
            } else {
              o[key] = o[key].concat([value]);
            }
          } else if (o[key] === void 0 && isTypeArray) {
            o[key] = isValueArray ? value : [value];
          } else if (duplicate && !(o[key] === void 0 || checkAllAliases(key, flags.counts) || checkAllAliases(key, flags.bools))) {
            o[key] = [o[key], value];
          } else {
            o[key] = value;
          }
        }
        function extendAliases(...args3) {
          args3.forEach(function(obj) {
            Object.keys(obj || {}).forEach(function(key) {
              if (flags.aliases[key])
                return;
              flags.aliases[key] = [].concat(aliases[key] || []);
              flags.aliases[key].concat(key).forEach(function(x) {
                if (/-/.test(x) && configuration["camel-case-expansion"]) {
                  const c = camelCase(x);
                  if (c !== key && flags.aliases[key].indexOf(c) === -1) {
                    flags.aliases[key].push(c);
                    newAliases[c] = true;
                  }
                }
              });
              flags.aliases[key].concat(key).forEach(function(x) {
                if (x.length > 1 && /[A-Z]/.test(x) && configuration["camel-case-expansion"]) {
                  const c = decamelize(x, "-");
                  if (c !== key && flags.aliases[key].indexOf(c) === -1) {
                    flags.aliases[key].push(c);
                    newAliases[c] = true;
                  }
                }
              });
              flags.aliases[key].forEach(function(x) {
                flags.aliases[x] = [key].concat(flags.aliases[key].filter(function(y) {
                  return x !== y;
                }));
              });
            });
          });
        }
        function checkAllAliases(key, flag) {
          const toCheck = [].concat(flags.aliases[key] || [], key);
          const keys = Object.keys(flag);
          const setAlias = toCheck.find((key2) => keys.includes(key2));
          return setAlias ? flag[setAlias] : false;
        }
        function hasAnyFlag(key) {
          const flagsKeys = Object.keys(flags);
          const toCheck = [].concat(flagsKeys.map((k) => flags[k]));
          return toCheck.some(function(flag) {
            return Array.isArray(flag) ? flag.includes(key) : flag[key];
          });
        }
        function hasFlagsMatching(arg, ...patterns) {
          const toCheck = [].concat(...patterns);
          return toCheck.some(function(pattern) {
            const match = arg.match(pattern);
            return match && hasAnyFlag(match[1]);
          });
        }
        function hasAllShortFlags(arg) {
          if (arg.match(negative) || !arg.match(/^-[^-]+/)) {
            return false;
          }
          let hasAllFlags = true;
          let next;
          const letters = arg.slice(1).split("");
          for (let j = 0; j < letters.length; j++) {
            next = arg.slice(j + 2);
            if (!hasAnyFlag(letters[j])) {
              hasAllFlags = false;
              break;
            }
            if (letters[j + 1] && letters[j + 1] === "=" || next === "-" || /[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) || letters[j + 1] && letters[j + 1].match(/\W/)) {
              break;
            }
          }
          return hasAllFlags;
        }
        function isUnknownOptionAsArg(arg) {
          return configuration["unknown-options-as-args"] && isUnknownOption(arg);
        }
        function isUnknownOption(arg) {
          arg = arg.replace(/^-{3,}/, "--");
          if (arg.match(negative)) {
            return false;
          }
          if (hasAllShortFlags(arg)) {
            return false;
          }
          const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/;
          const normalFlag = /^-+([^=]+?)$/;
          const flagEndingInHyphen = /^-+([^=]+?)-$/;
          const flagEndingInDigits = /^-+([^=]+?\d+)$/;
          const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/;
          return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters);
        }
        function defaultValue(key) {
          if (!checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts) && `${key}` in defaults) {
            return defaults[key];
          } else {
            return defaultForType(guessType2(key));
          }
        }
        function defaultForType(type) {
          const def = {
            [DefaultValuesForTypeKey.BOOLEAN]: true,
            [DefaultValuesForTypeKey.STRING]: "",
            [DefaultValuesForTypeKey.NUMBER]: void 0,
            [DefaultValuesForTypeKey.ARRAY]: []
          };
          return def[type];
        }
        function guessType2(key) {
          let type = DefaultValuesForTypeKey.BOOLEAN;
          if (checkAllAliases(key, flags.strings))
            type = DefaultValuesForTypeKey.STRING;
          else if (checkAllAliases(key, flags.numbers))
            type = DefaultValuesForTypeKey.NUMBER;
          else if (checkAllAliases(key, flags.bools))
            type = DefaultValuesForTypeKey.BOOLEAN;
          else if (checkAllAliases(key, flags.arrays))
            type = DefaultValuesForTypeKey.ARRAY;
          return type;
        }
        function isUndefined(num) {
          return num === void 0;
        }
        function checkConfiguration() {
          Object.keys(flags.counts).find((key) => {
            if (checkAllAliases(key, flags.arrays)) {
              error = Error(__("Invalid configuration: %s, opts.count excludes opts.array.", key));
              return true;
            } else if (checkAllAliases(key, flags.nargs)) {
              error = Error(__("Invalid configuration: %s, opts.count excludes opts.narg.", key));
              return true;
            }
            return false;
          });
        }
        return {
          aliases: Object.assign({}, flags.aliases),
          argv: Object.assign(argvReturn, argv),
          configuration,
          defaulted: Object.assign({}, defaulted),
          error,
          newAliases: Object.assign({}, newAliases)
        };
      }
    };
  }
});

// node_modules/yargs-parser/build/lib/index.js
var import_util, import_path2, import_fs2, _a, _b, _c, minNodeVersion, nodeVersion, env, parser, yargsParser, lib_default;
var init_lib2 = __esm({
  "node_modules/yargs-parser/build/lib/index.js"() {
    init_prefix();
    import_util = require("util");
    import_path2 = require("path");
    init_string_utils2();
    init_yargs_parser();
    import_fs2 = require("fs");
    minNodeVersion = process && process.env && process.env.YARGS_MIN_NODE_VERSION ? Number(process.env.YARGS_MIN_NODE_VERSION) : 12;
    nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1);
    if (nodeVersion) {
      const major = Number(nodeVersion.match(/^([^.]+)/)[1]);
      if (major < minNodeVersion) {
        throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);
      }
    }
    env = process ? process.env : {};
    parser = new YargsParser({
      cwd: process.cwd,
      env: () => {
        return env;
      },
      format: import_util.format,
      normalize: import_path2.normalize,
      resolve: import_path2.resolve,
      // TODO: figure  out a  way to combine ESM and CJS coverage, such  that
      // we can exercise all the lines below:
      require: (path2) => {
        if (typeof require !== "undefined") {
          return require(path2);
        } else if (path2.match(/\.json$/)) {
          return JSON.parse((0, import_fs2.readFileSync)(path2, "utf8"));
        } else {
          throw Error("only .json config files are supported in ESM");
        }
      }
    });
    yargsParser = function Parser(args2, opts) {
      const result = parser.parse(args2.slice(), opts);
      return result.argv;
    };
    yargsParser.detailed = function(args2, opts) {
      return parser.parse(args2.slice(), opts);
    };
    yargsParser.camelCase = camelCase;
    yargsParser.decamelize = decamelize;
    yargsParser.looksLikeNumber = looksLikeNumber;
    lib_default = yargsParser;
  }
});

// node_modules/yargs/build/lib/utils/process-argv.js
function getProcessArgvBinIndex() {
  if (isBundledElectronApp())
    return 0;
  return 1;
}
function isBundledElectronApp() {
  return isElectronApp() && !process.defaultApp;
}
function isElectronApp() {
  return !!process.versions.electron;
}
function hideBin(argv) {
  return argv.slice(getProcessArgvBinIndex() + 1);
}
function getProcessArgvBin() {
  return process.argv[getProcessArgvBinIndex()];
}
var init_process_argv = __esm({
  "node_modules/yargs/build/lib/utils/process-argv.js"() {
    init_prefix();
  }
});

// node_modules/yargs/build/lib/yerror.js
var YError;
var init_yerror = __esm({
  "node_modules/yargs/build/lib/yerror.js"() {
    init_prefix();
    YError = class _YError extends Error {
      constructor(msg) {
        super(msg || "yargs error");
        this.name = "YError";
        if (Error.captureStackTrace) {
          Error.captureStackTrace(this, _YError);
        }
      }
    };
  }
});

// node_modules/y18n/build/lib/platform-shims/node.js
var import_fs3, import_util2, import_path3, node_default;
var init_node = __esm({
  "node_modules/y18n/build/lib/platform-shims/node.js"() {
    init_prefix();
    import_fs3 = require("fs");
    import_util2 = require("util");
    import_path3 = require("path");
    node_default = {
      fs: {
        readFileSync: import_fs3.readFileSync,
        writeFile: import_fs3.writeFile
      },
      format: import_util2.format,
      resolve: import_path3.resolve,
      exists: (file) => {
        try {
          return (0, import_fs3.statSync)(file).isFile();
        } catch (err) {
          return false;
        }
      }
    };
  }
});

// node_modules/y18n/build/lib/index.js
function y18n(opts, _shim) {
  shim = _shim;
  const y18n3 = new Y18N(opts);
  return {
    __: y18n3.__.bind(y18n3),
    __n: y18n3.__n.bind(y18n3),
    setLocale: y18n3.setLocale.bind(y18n3),
    getLocale: y18n3.getLocale.bind(y18n3),
    updateLocale: y18n3.updateLocale.bind(y18n3),
    locale: y18n3.locale
  };
}
var shim, Y18N;
var init_lib3 = __esm({
  "node_modules/y18n/build/lib/index.js"() {
    init_prefix();
    Y18N = class {
      constructor(opts) {
        opts = opts || {};
        this.directory = opts.directory || "./locales";
        this.updateFiles = typeof opts.updateFiles === "boolean" ? opts.updateFiles : true;
        this.locale = opts.locale || "en";
        this.fallbackToLanguage = typeof opts.fallbackToLanguage === "boolean" ? opts.fallbackToLanguage : true;
        this.cache = /* @__PURE__ */ Object.create(null);
        this.writeQueue = [];
      }
      __(...args2) {
        if (typeof arguments[0] !== "string") {
          return this._taggedLiteral(arguments[0], ...arguments);
        }
        const str = args2.shift();
        let cb = function() {
        };
        if (typeof args2[args2.length - 1] === "function")
          cb = args2.pop();
        cb = cb || function() {
        };
        if (!this.cache[this.locale])
          this._readLocaleFile();
        if (!this.cache[this.locale][str] && this.updateFiles) {
          this.cache[this.locale][str] = str;
          this._enqueueWrite({
            directory: this.directory,
            locale: this.locale,
            cb
          });
        } else {
          cb();
        }
        return shim.format.apply(shim.format, [this.cache[this.locale][str] || str].concat(args2));
      }
      __n() {
        const args2 = Array.prototype.slice.call(arguments);
        const singular = args2.shift();
        const plural = args2.shift();
        const quantity = args2.shift();
        let cb = function() {
        };
        if (typeof args2[args2.length - 1] === "function")
          cb = args2.pop();
        if (!this.cache[this.locale])
          this._readLocaleFile();
        let str = quantity === 1 ? singular : plural;
        if (this.cache[this.locale][singular]) {
          const entry = this.cache[this.locale][singular];
          str = entry[quantity === 1 ? "one" : "other"];
        }
        if (!this.cache[this.locale][singular] && this.updateFiles) {
          this.cache[this.locale][singular] = {
            one: singular,
            other: plural
          };
          this._enqueueWrite({
            directory: this.directory,
            locale: this.locale,
            cb
          });
        } else {
          cb();
        }
        const values = [str];
        if (~str.indexOf("%d"))
          values.push(quantity);
        return shim.format.apply(shim.format, values.concat(args2));
      }
      setLocale(locale) {
        this.locale = locale;
      }
      getLocale() {
        return this.locale;
      }
      updateLocale(obj) {
        if (!this.cache[this.locale])
          this._readLocaleFile();
        for (const key in obj) {
          if (Object.prototype.hasOwnProperty.call(obj, key)) {
            this.cache[this.locale][key] = obj[key];
          }
        }
      }
      _taggedLiteral(parts, ...args2) {
        let str = "";
        parts.forEach(function(part, i) {
          const arg = args2[i + 1];
          str += part;
          if (typeof arg !== "undefined") {
            str += "%s";
          }
        });
        return this.__.apply(this, [str].concat([].slice.call(args2, 1)));
      }
      _enqueueWrite(work) {
        this.writeQueue.push(work);
        if (this.writeQueue.length === 1)
          this._processWriteQueue();
      }
      _processWriteQueue() {
        const _this = this;
        const work = this.writeQueue[0];
        const directory = work.directory;
        const locale = work.locale;
        const cb = work.cb;
        const languageFile = this._resolveLocaleFile(directory, locale);
        const serializedLocale = JSON.stringify(this.cache[locale], null, 2);
        shim.fs.writeFile(languageFile, serializedLocale, "utf-8", function(err) {
          _this.writeQueue.shift();
          if (_this.writeQueue.length > 0)
            _this._processWriteQueue();
          cb(err);
        });
      }
      _readLocaleFile() {
        let localeLookup = {};
        const languageFile = this._resolveLocaleFile(this.directory, this.locale);
        try {
          if (shim.fs.readFileSync) {
            localeLookup = JSON.parse(shim.fs.readFileSync(languageFile, "utf-8"));
          }
        } catch (err) {
          if (err instanceof SyntaxError) {
            err.message = "syntax error in " + languageFile;
          }
          if (err.code === "ENOENT")
            localeLookup = {};
          else
            throw err;
        }
        this.cache[this.locale] = localeLookup;
      }
      _resolveLocaleFile(directory, locale) {
        let file = shim.resolve(directory, "./", locale + ".json");
        if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf("_")) {
          const languageFile = shim.resolve(directory, "./", locale.split("_")[0] + ".json");
          if (this._fileExistsSync(languageFile))
            file = languageFile;
        }
        return file;
      }
      _fileExistsSync(file) {
        return shim.exists(file);
      }
    };
  }
});

// node_modules/y18n/index.mjs
var y18n2, y18n_default;
var init_y18n = __esm({
  "node_modules/y18n/index.mjs"() {
    init_prefix();
    init_node();
    init_lib3();
    y18n2 = (opts) => {
      return y18n(opts, node_default);
    };
    y18n_default = y18n2;
  }
});

// node_modules/yargs/lib/platform-shims/esm.mjs
var import_assert, import_util3, import_fs4, import_url, import_path4, import_meta, REQUIRE_ERROR, REQUIRE_DIRECTORY_ERROR, __dirname2, mainFilename, esm_default;
var init_esm = __esm({
  "node_modules/yargs/lib/platform-shims/esm.mjs"() {
    "use strict";
    init_prefix();
    import_assert = require("assert");
    init_cliui();
    init_sync();
    import_util3 = require("util");
    import_fs4 = require("fs");
    import_url = require("url");
    init_lib2();
    import_path4 = require("path");
    init_process_argv();
    init_yerror();
    init_y18n();
    import_meta = {};
    REQUIRE_ERROR = "require is not supported by ESM";
    REQUIRE_DIRECTORY_ERROR = "loading a directory of commands is not supported yet for ESM";
    try {
      __dirname2 = (0, import_url.fileURLToPath)(import_meta.url);
    } catch (e) {
      __dirname2 = process.cwd();
    }
    mainFilename = __dirname2.substring(0, __dirname2.lastIndexOf("node_modules"));
    esm_default = {
      assert: {
        notStrictEqual: import_assert.notStrictEqual,
        strictEqual: import_assert.strictEqual
      },
      cliui: ui,
      findUp: sync_default,
      getEnv: (key) => {
        return process.env[key];
      },
      inspect: import_util3.inspect,
      getCallerFile: () => {
        throw new YError(REQUIRE_DIRECTORY_ERROR);
      },
      getProcessArgvBin,
      mainFilename: mainFilename || process.cwd(),
      Parser: lib_default,
      path: {
        basename: import_path4.basename,
        dirname: import_path4.dirname,
        extname: import_path4.extname,
        relative: import_path4.relative,
        resolve: import_path4.resolve
      },
      process: {
        argv: () => process.argv,
        cwd: process.cwd,
        emitWarning: (warning, type) => process.emitWarning(warning, type),
        execPath: () => process.execPath,
        exit: process.exit,
        nextTick: process.nextTick,
        stdColumns: typeof process.stdout.columns !== "undefined" ? process.stdout.columns : null
      },
      readFileSync: import_fs4.readFileSync,
      require: () => {
        throw new YError(REQUIRE_ERROR);
      },
      requireDirectory: () => {
        throw new YError(REQUIRE_DIRECTORY_ERROR);
      },
      stringWidth: (str) => {
        return [...str].length;
      },
      y18n: y18n_default({
        directory: (0, import_path4.resolve)(__dirname2, "../../../locales"),
        updateFiles: false
      })
    };
  }
});

// node_modules/yargs/build/lib/typings/common-types.js
function assertNotStrictEqual(actual, expected, shim3, message) {
  shim3.assert.notStrictEqual(actual, expected, message);
}
function assertSingleKey(actual, shim3) {
  shim3.assert.strictEqual(typeof actual, "string");
}
function objectKeys(object) {
  return Object.keys(object);
}
var init_common_types = __esm({
  "node_modules/yargs/build/lib/typings/common-types.js"() {
    init_prefix();
  }
});

// node_modules/yargs/build/lib/utils/is-promise.js
function isPromise(maybePromise) {
  return !!maybePromise && !!maybePromise.then && typeof maybePromise.then === "function";
}
var init_is_promise = __esm({
  "node_modules/yargs/build/lib/utils/is-promise.js"() {
    init_prefix();
  }
});

// node_modules/yargs/build/lib/parse-command.js
function parseCommand(cmd) {
  const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, " ");
  const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/);
  const bregex = /\.*[\][<>]/g;
  const firstCommand = splitCommand.shift();
  if (!firstCommand)
    throw new Error(`No command found in: ${cmd}`);
  const parsedCommand = {
    cmd: firstCommand.replace(bregex, ""),
    demanded: [],
    optional: []
  };
  splitCommand.forEach((cmd2, i) => {
    let variadic = false;
    cmd2 = cmd2.replace(/\s/g, "");
    if (/\.+[\]>]/.test(cmd2) && i === splitCommand.length - 1)
      variadic = true;
    if (/^\[/.test(cmd2)) {
      parsedCommand.optional.push({
        cmd: cmd2.replace(bregex, "").split("|"),
        variadic
      });
    } else {
      parsedCommand.demanded.push({
        cmd: cmd2.replace(bregex, "").split("|"),
        variadic
      });
    }
  });
  return parsedCommand;
}
var init_parse_command = __esm({
  "node_modules/yargs/build/lib/parse-command.js"() {
    init_prefix();
  }
});

// node_modules/yargs/build/lib/argsert.js
function argsert(arg1, arg2, arg3) {
  function parseArgs() {
    return typeof arg1 === "object" ? [{ demanded: [], optional: [] }, arg1, arg2] : [
      parseCommand(`cmd ${arg1}`),
      arg2,
      arg3
    ];
  }
  try {
    let position = 0;
    const [parsed, callerArguments, _length] = parseArgs();
    const args2 = [].slice.call(callerArguments);
    while (args2.length && args2[args2.length - 1] === void 0)
      args2.pop();
    const length = _length || args2.length;
    if (length < parsed.demanded.length) {
      throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args2.length}.`);
    }
    const totalCommands = parsed.demanded.length + parsed.optional.length;
    if (length > totalCommands) {
      throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`);
    }
    parsed.demanded.forEach((demanded) => {
      const arg = args2.shift();
      const observedType = guessType(arg);
      const matchingTypes = demanded.cmd.filter((type) => type === observedType || type === "*");
      if (matchingTypes.length === 0)
        argumentTypeError(observedType, demanded.cmd, position);
      position += 1;
    });
    parsed.optional.forEach((optional) => {
      if (args2.length === 0)
        return;
      const arg = args2.shift();
      const observedType = guessType(arg);
      const matchingTypes = optional.cmd.filter((type) => type === observedType || type === "*");
      if (matchingTypes.length === 0)
        argumentTypeError(observedType, optional.cmd, position);
      position += 1;
    });
  } catch (err) {
    console.warn(err.stack);
  }
}
function guessType(arg) {
  if (Array.isArray(arg)) {
    return "array";
  } else if (arg === null) {
    return "null";
  }
  return typeof arg;
}
function argumentTypeError(observedType, allowedTypes, position) {
  throw new YError(`Invalid ${positionName[position] || "manyith"} argument. Expected ${allowedTypes.join(" or ")} but received ${observedType}.`);
}
var positionName;
var init_argsert = __esm({
  "node_modules/yargs/build/lib/argsert.js"() {
    init_prefix();
    init_yerror();
    init_parse_command();
    positionName = ["first", "second", "third", "fourth", "fifth", "sixth"];
  }
});

// node_modules/yargs/build/lib/middleware.js
function commandMiddlewareFactory(commandMiddleware) {
  if (!commandMiddleware)
    return [];
  return commandMiddleware.map((middleware) => {
    middleware.applyBeforeValidation = false;
    return middleware;
  });
}
function applyMiddleware(argv, yargs, middlewares, beforeValidation) {
  return middlewares.reduce((acc, middleware) => {
    if (middleware.applyBeforeValidation !== beforeValidation) {
      return acc;
    }
    if (middleware.mutates) {
      if (middleware.applied)
        return acc;
      middleware.applied = true;
    }
    if (isPromise(acc)) {
      return acc.then((initialObj) => Promise.all([initialObj, middleware(initialObj, yargs)])).then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj));
    } else {
      const result = middleware(acc, yargs);
      return isPromise(result) ? result.then((middlewareObj) => Object.assign(acc, middlewareObj)) : Object.assign(acc, result);
    }
  }, argv);
}
var GlobalMiddleware;
var init_middleware = __esm({
  "node_modules/yargs/build/lib/middleware.js"() {
    init_prefix();
    init_argsert();
    init_is_promise();
    GlobalMiddleware = class {
      constructor(yargs) {
        this.globalMiddleware = [];
        this.frozens = [];
        this.yargs = yargs;
      }
      addMiddleware(callback, applyBeforeValidation, global2 = true, mutates = false) {
        argsert("<array|function> [boolean] [boolean] [boolean]", [callback, applyBeforeValidation, global2], arguments.length);
        if (Array.isArray(callback)) {
          for (let i = 0; i < callback.length; i++) {
            if (typeof callback[i] !== "function") {
              throw Error("middleware must be a function");
            }
            const m = callback[i];
            m.applyBeforeValidation = applyBeforeValidation;
            m.global = global2;
          }
          Array.prototype.push.apply(this.globalMiddleware, callback);
        } else if (typeof callback === "function") {
          const m = callback;
          m.applyBeforeValidation = applyBeforeValidation;
          m.global = global2;
          m.mutates = mutates;
          this.globalMiddleware.push(callback);
        }
        return this.yargs;
      }
      addCoerceMiddleware(callback, option) {
        const aliases = this.yargs.getAliases();
        this.globalMiddleware = this.globalMiddleware.filter((m) => {
          const toCheck = [...aliases[option] || [], option];
          if (!m.option)
            return true;
          else
            return !toCheck.includes(m.option);
        });
        callback.option = option;
        return this.addMiddleware(callback, true, true, true);
      }
      getMiddleware() {
        return this.globalMiddleware;
      }
      freeze() {
        this.frozens.push([...this.globalMiddleware]);
      }
      unfreeze() {
        const frozen = this.frozens.pop();
        if (frozen !== void 0)
          this.globalMiddleware = frozen;
      }
      reset() {
        this.globalMiddleware = this.globalMiddleware.filter((m) => m.global);
      }
    };
  }
});

// node_modules/yargs/build/lib/utils/maybe-async-result.js
function maybeAsyncResult(getResult, resultHandler, errorHandler = (err) => {
  throw err;
}) {
  try {
    const result = isFunction(getResult) ? getResult() : getResult;
    return isPromise(result) ? result.then((result2) => resultHandler(result2)) : resultHandler(result);
  } catch (err) {
    return errorHandler(err);
  }
}
function isFunction(arg) {
  return typeof arg === "function";
}
var init_maybe_async_result = __esm({
  "node_modules/yargs/build/lib/utils/maybe-async-result.js"() {
    init_prefix();
    init_is_promise();
  }
});

// node_modules/yargs/build/lib/utils/which-module.js
function whichModule(exported) {
  if (typeof require === "undefined")
    return null;
  for (let i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) {
    mod = require.cache[files[i]];
    if (mod.exports === exported)
      return mod;
  }
  return null;
}
var init_which_module = __esm({
  "node_modules/yargs/build/lib/utils/which-module.js"() {
    init_prefix();
  }
});

// node_modules/yargs/build/lib/command.js
function command(usage2, validation2, globalMiddleware, shim3) {
  return new CommandInstance(usage2, validation2, globalMiddleware, shim3);
}
function isCommandBuilderDefinition(builder) {
  return typeof builder === "object" && !!builder.builder && typeof builder.handler === "function";
}
function isCommandAndAliases(cmd) {
  return cmd.every((c) => typeof c === "string");
}
function isCommandBuilderCallback(builder) {
  return typeof builder === "function";
}
function isCommandBuilderOptionDefinitions(builder) {
  return typeof builder === "object";
}
function isCommandHandlerDefinition(cmd) {
  return typeof cmd === "object" && !Array.isArray(cmd);
}
var DEFAULT_MARKER, CommandInstance;
var init_command = __esm({
  "node_modules/yargs/build/lib/command.js"() {
    init_prefix();
    init_common_types();
    init_is_promise();
    init_middleware();
    init_parse_command();
    init_yargs_factory();
    init_maybe_async_result();
    init_which_module();
    DEFAULT_MARKER = /(^\*)|(^\$0)/;
    CommandInstance = class {
      constructor(usage2, validation2, globalMiddleware, shim3) {
        this.requireCache = /* @__PURE__ */ new Set();
        this.handlers = {};
        this.aliasMap = {};
        this.frozens = [];
        this.shim = shim3;
        this.usage = usage2;
        this.globalMiddleware = globalMiddleware;
        this.validation = validation2;
      }
      addDirectory(dir, req, callerFile, opts) {
        opts = opts || {};
        if (typeof opts.recurse !== "boolean")
          opts.recurse = false;
        if (!Array.isArray(opts.extensions))
          opts.extensions = ["js"];
        const parentVisit = typeof opts.visit === "function" ? opts.visit : (o) => o;
        opts.visit = (obj, joined, filename) => {
          const visited = parentVisit(obj, joined, filename);
          if (visited) {
            if (this.requireCache.has(joined))
              return visited;
            else
              this.requireCache.add(joined);
            this.addHandler(visited);
          }
          return visited;
        };
        this.shim.requireDirectory({ require: req, filename: callerFile }, dir, opts);
      }
      addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) {
        let aliases = [];
        const middlewares = commandMiddlewareFactory(commandMiddleware);
        handler = handler || (() => {
        });
        if (Array.isArray(cmd)) {
          if (isCommandAndAliases(cmd)) {
            [cmd, ...aliases] = cmd;
          } else {
            for (const command2 of cmd) {
              this.addHandler(command2);
            }
          }
        } else if (isCommandHandlerDefinition(cmd)) {
          let command2 = Array.isArray(cmd.command) || typeof cmd.command === "string" ? cmd.command : this.moduleName(cmd);
          if (cmd.aliases)
            command2 = [].concat(command2).concat(cmd.aliases);
          this.addHandler(command2, this.extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated);
          return;
        } else if (isCommandBuilderDefinition(builder)) {
          this.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated);
          return;
        }
        if (typeof cmd === "string") {
          const parsedCommand = parseCommand(cmd);
          aliases = aliases.map((alias) => parseCommand(alias).cmd);
          let isDefault = false;
          const parsedAliases = [parsedCommand.cmd].concat(aliases).filter((c) => {
            if (DEFAULT_MARKER.test(c)) {
              isDefault = true;
              return false;
            }
            return true;
          });
          if (parsedAliases.length === 0 && isDefault)
            parsedAliases.push("$0");
          if (isDefault) {
            parsedCommand.cmd = parsedAliases[0];
            aliases = parsedAliases.slice(1);
            cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd);
          }
          aliases.forEach((alias) => {
            this.aliasMap[alias] = parsedCommand.cmd;
          });
          if (description !== false) {
            this.usage.command(cmd, description, isDefault, aliases, deprecated);
          }
          this.handlers[parsedCommand.cmd] = {
            original: cmd,
            description,
            handler,
            builder: builder || {},
            middlewares,
            deprecated,
            demanded: parsedCommand.demanded,
            optional: parsedCommand.optional
          };
          if (isDefault)
            this.defaultCommand = this.handlers[parsedCommand.cmd];
        }
      }
      getCommandHandlers() {
        return this.handlers;
      }
      getCommands() {
        return Object.keys(this.handlers).concat(Object.keys(this.aliasMap));
      }
      hasDefaultCommand() {
        return !!this.defaultCommand;
      }
      runCommand(command2, yargs, parsed, commandIndex, helpOnly, helpOrVersionSet) {
        const commandHandler = this.handlers[command2] || this.handlers[this.aliasMap[command2]] || this.defaultCommand;
        const currentContext = yargs.getInternalMethods().getContext();
        const parentCommands = currentContext.commands.slice();
        const isDefaultCommand = !command2;
        if (command2) {
          currentContext.commands.push(command2);
          currentContext.fullCommands.push(commandHandler.original);
        }
        const builderResult = this.applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, parsed.aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet);
        return isPromise(builderResult) ? builderResult.then((result) => this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, result.innerArgv, currentContext, helpOnly, result.aliases, yargs)) : this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, builderResult.innerArgv, currentContext, helpOnly, builderResult.aliases, yargs);
      }
      applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet) {
        const builder = commandHandler.builder;
        let innerYargs = yargs;
        if (isCommandBuilderCallback(builder)) {
          yargs.getInternalMethods().getUsageInstance().freeze();
          const builderOutput = builder(yargs.getInternalMethods().reset(aliases), helpOrVersionSet);
          if (isPromise(builderOutput)) {
            return builderOutput.then((output) => {
              innerYargs = isYargsInstance(output) ? output : yargs;
              return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
            });
          }
        } else if (isCommandBuilderOptionDefinitions(builder)) {
          yargs.getInternalMethods().getUsageInstance().freeze();
          innerYargs = yargs.getInternalMethods().reset(aliases);
          Object.keys(commandHandler.builder).forEach((key) => {
            innerYargs.option(key, builder[key]);
          });
        }
        return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
      }
      parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly) {
        if (isDefaultCommand)
          innerYargs.getInternalMethods().getUsageInstance().unfreeze(true);
        if (this.shouldUpdateUsage(innerYargs)) {
          innerYargs.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description);
        }
        const innerArgv = innerYargs.getInternalMethods().runYargsParserAndExecuteCommands(null, void 0, true, commandIndex, helpOnly);
        return isPromise(innerArgv) ? innerArgv.then((argv) => ({
          aliases: innerYargs.parsed.aliases,
          innerArgv: argv
        })) : {
          aliases: innerYargs.parsed.aliases,
          innerArgv
        };
      }
      shouldUpdateUsage(yargs) {
        return !yargs.getInternalMethods().getUsageInstance().getUsageDisabled() && yargs.getInternalMethods().getUsageInstance().getUsage().length === 0;
      }
      usageFromParentCommandsCommandHandler(parentCommands, commandHandler) {
        const c = DEFAULT_MARKER.test(commandHandler.original) ? commandHandler.original.replace(DEFAULT_MARKER, "").trim() : commandHandler.original;
        const pc = parentCommands.filter((c2) => {
          return !DEFAULT_MARKER.test(c2);
        });
        pc.push(c);
        return `$0 ${pc.join(" ")}`;
      }
      handleValidationAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, aliases, yargs, middlewares, positionalMap) {
        if (!yargs.getInternalMethods().getHasOutput()) {
          const validation2 = yargs.getInternalMethods().runValidation(aliases, positionalMap, yargs.parsed.error, isDefaultCommand);
          innerArgv = maybeAsyncResult(innerArgv, (result) => {
            validation2(result);
            return result;
          });
        }
        if (commandHandler.handler && !yargs.getInternalMethods().getHasOutput()) {
          yargs.getInternalMethods().setHasOutput();
          const populateDoubleDash = !!yargs.getOptions().configuration["populate--"];
          yargs.getInternalMethods().postProcess(innerArgv, populateDoubleDash, false, false);
          innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false);
          innerArgv = maybeAsyncResult(innerArgv, (result) => {
            const handlerResult = commandHandler.handler(result);
            return isPromise(handlerResult) ? handlerResult.then(() => result) : result;
          });
          if (!isDefaultCommand) {
            yargs.getInternalMethods().getUsageInstance().cacheHelpMessage();
          }
          if (isPromise(innerArgv) && !yargs.getInternalMethods().hasParseCallback()) {
            innerArgv.catch((error) => {
              try {
                yargs.getInternalMethods().getUsageInstance().fail(null, error);
              } catch (_err) {
              }
            });
          }
        }
        if (!isDefaultCommand) {
          currentContext.commands.pop();
          currentContext.fullCommands.pop();
        }
        return innerArgv;
      }
      applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, helpOnly, aliases, yargs) {
        let positionalMap = {};
        if (helpOnly)
          return innerArgv;
        if (!yargs.getInternalMethods().getHasOutput()) {
          positionalMap = this.populatePositionals(commandHandler, innerArgv, currentContext, yargs);
        }
        const middlewares = this.globalMiddleware.getMiddleware().slice(0).concat(commandHandler.middlewares);
        const maybePromiseArgv = applyMiddleware(innerArgv, yargs, middlewares, true);
        return isPromise(maybePromiseArgv) ? maybePromiseArgv.then((resolvedInnerArgv) => this.handleValidationAndGetResult(isDefaultCommand, commandHandler, resolvedInnerArgv, currentContext, aliases, yargs, middlewares, positionalMap)) : this.handleValidationAndGetResult(isDefaultCommand, commandHandler, maybePromiseArgv, currentContext, aliases, yargs, middlewares, positionalMap);
      }
      populatePositionals(commandHandler, argv, context, yargs) {
        argv._ = argv._.slice(context.commands.length);
        const demanded = commandHandler.demanded.slice(0);
        const optional = commandHandler.optional.slice(0);
        const positionalMap = {};
        this.validation.positionalCount(demanded.length, argv._.length);
        while (demanded.length) {
          const demand = demanded.shift();
          this.populatePositional(demand, argv, positionalMap);
        }
        while (optional.length) {
          const maybe = optional.shift();
          this.populatePositional(maybe, argv, positionalMap);
        }
        argv._ = context.commands.concat(argv._.map((a) => "" + a));
        this.postProcessPositionals(argv, positionalMap, this.cmdToParseOptions(commandHandler.original), yargs);
        return positionalMap;
      }
      populatePositional(positional, argv, positionalMap) {
        const cmd = positional.cmd[0];
        if (positional.variadic) {
          positionalMap[cmd] = argv._.splice(0).map(String);
        } else {
          if (argv._.length)
            positionalMap[cmd] = [String(argv._.shift())];
        }
      }
      cmdToParseOptions(cmdString) {
        const parseOptions = {
          array: [],
          default: {},
          alias: {},
          demand: {}
        };
        const parsed = parseCommand(cmdString);
        parsed.demanded.forEach((d) => {
          const [cmd, ...aliases] = d.cmd;
          if (d.variadic) {
            parseOptions.array.push(cmd);
            parseOptions.default[cmd] = [];
          }
          parseOptions.alias[cmd] = aliases;
          parseOptions.demand[cmd] = true;
        });
        parsed.optional.forEach((o) => {
          const [cmd, ...aliases] = o.cmd;
          if (o.variadic) {
            parseOptions.array.push(cmd);
            parseOptions.default[cmd] = [];
          }
          parseOptions.alias[cmd] = aliases;
        });
        return parseOptions;
      }
      postProcessPositionals(argv, positionalMap, parseOptions, yargs) {
        const options = Object.assign({}, yargs.getOptions());
        options.default = Object.assign(parseOptions.default, options.default);
        for (const key of Object.keys(parseOptions.alias)) {
          options.alias[key] = (options.alias[key] || []).concat(parseOptions.alias[key]);
        }
        options.array = options.array.concat(parseOptions.array);
        options.config = {};
        const unparsed = [];
        Object.keys(positionalMap).forEach((key) => {
          positionalMap[key].map((value) => {
            if (options.configuration["unknown-options-as-args"])
              options.key[key] = true;
            unparsed.push(`--${key}`);
            unparsed.push(value);
          });
        });
        if (!unparsed.length)
          return;
        const config2 = Object.assign({}, options.configuration, {
          "populate--": false
        });
        const parsed = this.shim.Parser.detailed(unparsed, Object.assign({}, options, {
          configuration: config2
        }));
        if (parsed.error) {
          yargs.getInternalMethods().getUsageInstance().fail(parsed.error.message, parsed.error);
        } else {
          const positionalKeys = Object.keys(positionalMap);
          Object.keys(positionalMap).forEach((key) => {
            positionalKeys.push(...parsed.aliases[key]);
          });
          Object.keys(parsed.argv).forEach((key) => {
            if (positionalKeys.includes(key)) {
              if (!positionalMap[key])
                positionalMap[key] = parsed.argv[key];
              if (!this.isInConfigs(yargs, key) && !this.isDefaulted(yargs, key) && Object.prototype.hasOwnProperty.call(argv, key) && Object.prototype.hasOwnProperty.call(parsed.argv, key) && (Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))) {
                argv[key] = [].concat(argv[key], parsed.argv[key]);
              } else {
                argv[key] = parsed.argv[key];
              }
            }
          });
        }
      }
      isDefaulted(yargs, key) {
        const { default: defaults } = yargs.getOptions();
        return Object.prototype.hasOwnProperty.call(defaults, key) || Object.prototype.hasOwnProperty.call(defaults, this.shim.Parser.camelCase(key));
      }
      isInConfigs(yargs, key) {
        const { configObjects } = yargs.getOptions();
        return configObjects.some((c) => Object.prototype.hasOwnProperty.call(c, key)) || configObjects.some((c) => Object.prototype.hasOwnProperty.call(c, this.shim.Parser.camelCase(key)));
      }
      runDefaultBuilderOn(yargs) {
        if (!this.defaultCommand)
          return;
        if (this.shouldUpdateUsage(yargs)) {
          const commandString = DEFAULT_MARKER.test(this.defaultCommand.original) ? this.defaultCommand.original : this.defaultCommand.original.replace(/^[^[\]<>]*/, "$0 ");
          yargs.getInternalMethods().getUsageInstance().usage(commandString, this.defaultCommand.description);
        }
        const builder = this.defaultCommand.builder;
        if (isCommandBuilderCallback(builder)) {
          return builder(yargs, true);
        } else if (!isCommandBuilderDefinition(builder)) {
          Object.keys(builder).forEach((key) => {
            yargs.option(key, builder[key]);
          });
        }
        return void 0;
      }
      moduleName(obj) {
        const mod = whichModule(obj);
        if (!mod)
          throw new Error(`No command name given for module: ${this.shim.inspect(obj)}`);
        return this.commandFromFilename(mod.filename);
      }
      commandFromFilename(filename) {
        return this.shim.path.basename(filename, this.shim.path.extname(filename));
      }
      extractDesc({ describe, description, desc }) {
        for (const test of [describe, description, desc]) {
          if (typeof test === "string" || test === false)
            return test;
          assertNotStrictEqual(test, true, this.shim);
        }
        return false;
      }
      freeze() {
        this.frozens.push({
          handlers: this.handlers,
          aliasMap: this.aliasMap,
          defaultCommand: this.defaultCommand
        });
      }
      unfreeze() {
        const frozen = this.frozens.pop();
        assertNotStrictEqual(frozen, void 0, this.shim);
        ({
          handlers: this.handlers,
          aliasMap: this.aliasMap,
          defaultCommand: this.defaultCommand
        } = frozen);
      }
      reset() {
        this.handlers = {};
        this.aliasMap = {};
        this.defaultCommand = void 0;
        this.requireCache = /* @__PURE__ */ new Set();
        return this;
      }
    };
  }
});

// node_modules/yargs/build/lib/utils/obj-filter.js
function objFilter(original = {}, filter = () => true) {
  const obj = {};
  objectKeys(original).forEach((key) => {
    if (filter(key, original[key])) {
      obj[key] = original[key];
    }
  });
  return obj;
}
var init_obj_filter = __esm({
  "node_modules/yargs/build/lib/utils/obj-filter.js"() {
    init_prefix();
    init_common_types();
  }
});

// node_modules/yargs/build/lib/utils/set-blocking.js
function setBlocking(blocking) {
  if (typeof process === "undefined")
    return;
  [process.stdout, process.stderr].forEach((_stream) => {
    const stream = _stream;
    if (stream._handle && stream.isTTY && typeof stream._handle.setBlocking === "function") {
      stream._handle.setBlocking(blocking);
    }
  });
}
var init_set_blocking = __esm({
  "node_modules/yargs/build/lib/utils/set-blocking.js"() {
    init_prefix();
  }
});

// node_modules/yargs/build/lib/usage.js
function isBoolean(fail) {
  return typeof fail === "boolean";
}
function usage(yargs, shim3) {
  const __ = shim3.y18n.__;
  const self2 = {};
  const fails = [];
  self2.failFn = function failFn(f) {
    fails.push(f);
  };
  let failMessage = null;
  let globalFailMessage = null;
  let showHelpOnFail = true;
  self2.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) {
    const [enabled, message] = typeof arg1 === "string" ? [true, arg1] : [arg1, arg2];
    if (yargs.getInternalMethods().isGlobalContext()) {
      globalFailMessage = message;
    }
    failMessage = message;
    showHelpOnFail = enabled;
    return self2;
  };
  let failureOutput = false;
  self2.fail = function fail(msg, err) {
    const logger = yargs.getInternalMethods().getLoggerInstance();
    if (fails.length) {
      for (let i = fails.length - 1; i >= 0; --i) {
        const fail2 = fails[i];
        if (isBoolean(fail2)) {
          if (err)
            throw err;
          else if (msg)
            throw Error(msg);
        } else {
          fail2(msg, err, self2);
        }
      }
    } else {
      if (yargs.getExitProcess())
        setBlocking(true);
      if (!failureOutput) {
        failureOutput = true;
        if (showHelpOnFail) {
          yargs.showHelp("error");
          logger.error();
        }
        if (msg || err)
          logger.error(msg || err);
        const globalOrCommandFailMessage = failMessage || globalFailMessage;
        if (globalOrCommandFailMessage) {
          if (msg || err)
            logger.error("");
          logger.error(globalOrCommandFailMessage);
        }
      }
      err = err || new YError(msg);
      if (yargs.getExitProcess()) {
        return yargs.exit(1);
      } else if (yargs.getInternalMethods().hasParseCallback()) {
        return yargs.exit(1, err);
      } else {
        throw err;
      }
    }
  };
  let usages = [];
  let usageDisabled = false;
  self2.usage = (msg, description) => {
    if (msg === null) {
      usageDisabled = true;
      usages = [];
      return self2;
    }
    usageDisabled = false;
    usages.push([msg, description || ""]);
    return self2;
  };
  self2.getUsage = () => {
    return usages;
  };
  self2.getUsageDisabled = () => {
    return usageDisabled;
  };
  self2.getPositionalGroupName = () => {
    return __("Positionals:");
  };
  let examples = [];
  self2.example = (cmd, description) => {
    examples.push([cmd, description || ""]);
  };
  let commands = [];
  self2.command = function command2(cmd, description, isDefault, aliases, deprecated = false) {
    if (isDefault) {
      commands = commands.map((cmdArray) => {
        cmdArray[2] = false;
        return cmdArray;
      });
    }
    commands.push([cmd, description || "", isDefault, aliases, deprecated]);
  };
  self2.getCommands = () => commands;
  let descriptions = {};
  self2.describe = function describe(keyOrKeys, desc) {
    if (Array.isArray(keyOrKeys)) {
      keyOrKeys.forEach((k) => {
        self2.describe(k, desc);
      });
    } else if (typeof keyOrKeys === "object") {
      Object.keys(keyOrKeys).forEach((k) => {
        self2.describe(k, keyOrKeys[k]);
      });
    } else {
      descriptions[keyOrKeys] = desc;
    }
  };
  self2.getDescriptions = () => descriptions;
  let epilogs = [];
  self2.epilog = (msg) => {
    epilogs.push(msg);
  };
  let wrapSet = false;
  let wrap2;
  self2.wrap = (cols) => {
    wrapSet = true;
    wrap2 = cols;
  };
  self2.getWrap = () => {
    if (shim3.getEnv("YARGS_DISABLE_WRAP")) {
      return null;
    }
    if (!wrapSet) {
      wrap2 = windowWidth();
      wrapSet = true;
    }
    return wrap2;
  };
  const deferY18nLookupPrefix = "__yargsString__:";
  self2.deferY18nLookup = (str) => deferY18nLookupPrefix + str;
  self2.help = function help() {
    if (cachedHelpMessage)
      return cachedHelpMessage;
    normalizeAliases();
    const base$0 = yargs.customScriptName ? yargs.$0 : shim3.path.basename(yargs.$0);
    const demandedOptions = yargs.getDemandedOptions();
    const demandedCommands = yargs.getDemandedCommands();
    const deprecatedOptions = yargs.getDeprecatedOptions();
    const groups = yargs.getGroups();
    const options = yargs.getOptions();
    let keys = [];
    keys = keys.concat(Object.keys(descriptions));
    keys = keys.concat(Object.keys(demandedOptions));
    keys = keys.concat(Object.keys(demandedCommands));
    keys = keys.concat(Object.keys(options.default));
    keys = keys.filter(filterHiddenOptions);
    keys = Object.keys(keys.reduce((acc, key) => {
      if (key !== "_")
        acc[key] = true;
      return acc;
    }, {}));
    const theWrap = self2.getWrap();
    const ui2 = shim3.cliui({
      width: theWrap,
      wrap: !!theWrap
    });
    if (!usageDisabled) {
      if (usages.length) {
        usages.forEach((usage2) => {
          ui2.div({ text: `${usage2[0].replace(/\$0/g, base$0)}` });
          if (usage2[1]) {
            ui2.div({ text: `${usage2[1]}`, padding: [1, 0, 0, 0] });
          }
        });
        ui2.div();
      } else if (commands.length) {
        let u = null;
        if (demandedCommands._) {
          u = `${base$0} <${__("command")}>
`;
        } else {
          u = `${base$0} [${__("command")}]
`;
        }
        ui2.div(`${u}`);
      }
    }
    if (commands.length > 1 || commands.length === 1 && !commands[0][2]) {
      ui2.div(__("Commands:"));
      const context = yargs.getInternalMethods().getContext();
      const parentCommands = context.commands.length ? `${context.commands.join(" ")} ` : "";
      if (yargs.getInternalMethods().getParserConfiguration()["sort-commands"] === true) {
        commands = commands.sort((a, b) => a[0].localeCompare(b[0]));
      }
      const prefix = base$0 ? `${base$0} ` : "";
      commands.forEach((command2) => {
        const commandString = `${prefix}${parentCommands}${command2[0].replace(/^\$0 ?/, "")}`;
        ui2.span({
          text: commandString,
          padding: [0, 2, 0, 2],
          width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4
        }, { text: command2[1] });
        const hints = [];
        if (command2[2])
          hints.push(`[${__("default")}]`);
        if (command2[3] && command2[3].length) {
          hints.push(`[${__("aliases:")} ${command2[3].join(", ")}]`);
        }
        if (command2[4]) {
          if (typeof command2[4] === "string") {
            hints.push(`[${__("deprecated: %s", command2[4])}]`);
          } else {
            hints.push(`[${__("deprecated")}]`);
          }
        }
        if (hints.length) {
          ui2.div({
            text: hints.join(" "),
            padding: [0, 0, 0, 2],
            align: "right"
          });
        } else {
          ui2.div();
        }
      });
      ui2.div();
    }
    const aliasKeys = (Object.keys(options.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []);
    keys = keys.filter((key) => !yargs.parsed.newAliases[key] && aliasKeys.every((alias) => (options.alias[alias] || []).indexOf(key) === -1));
    const defaultGroup = __("Options:");
    if (!groups[defaultGroup])
      groups[defaultGroup] = [];
    addUngroupedKeys(keys, options.alias, groups, defaultGroup);
    const isLongSwitch = (sw) => /^--/.test(getText(sw));
    const displayedGroups = Object.keys(groups).filter((groupName) => groups[groupName].length > 0).map((groupName) => {
      const normalizedKeys = groups[groupName].filter(filterHiddenOptions).map((key) => {
        if (aliasKeys.includes(key))
          return key;
        for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== void 0; i++) {
          if ((options.alias[aliasKey] || []).includes(key))
            return aliasKey;
        }
        return key;
      });
      return { groupName, normalizedKeys };
    }).filter(({ normalizedKeys }) => normalizedKeys.length > 0).map(({ groupName, normalizedKeys }) => {
      const switches = normalizedKeys.reduce((acc, key) => {
        acc[key] = [key].concat(options.alias[key] || []).map((sw) => {
          if (groupName === self2.getPositionalGroupName())
            return sw;
          else {
            return (/^[0-9]$/.test(sw) ? options.boolean.includes(key) ? "-" : "--" : sw.length > 1 ? "--" : "-") + sw;
          }
        }).sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2) ? 0 : isLongSwitch(sw1) ? 1 : -1).join(", ");
        return acc;
      }, {});
      return { groupName, normalizedKeys, switches };
    });
    const shortSwitchesUsed = displayedGroups.filter(({ groupName }) => groupName !== self2.getPositionalGroupName()).some(({ normalizedKeys, switches }) => !normalizedKeys.every((key) => isLongSwitch(switches[key])));
    if (shortSwitchesUsed) {
      displayedGroups.filter(({ groupName }) => groupName !== self2.getPositionalGroupName()).forEach(({ normalizedKeys, switches }) => {
        normalizedKeys.forEach((key) => {
          if (isLongSwitch(switches[key])) {
            switches[key] = addIndentation(switches[key], "-x, ".length);
          }
        });
      });
    }
    displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => {
      ui2.div(groupName);
      normalizedKeys.forEach((key) => {
        const kswitch = switches[key];
        let desc = descriptions[key] || "";
        let type = null;
        if (desc.includes(deferY18nLookupPrefix))
          desc = __(desc.substring(deferY18nLookupPrefix.length));
        if (options.boolean.includes(key))
          type = `[${__("boolean")}]`;
        if (options.count.includes(key))
          type = `[${__("count")}]`;
        if (options.string.includes(key))
          type = `[${__("string")}]`;
        if (options.normalize.includes(key))
          type = `[${__("string")}]`;
        if (options.array.includes(key))
          type = `[${__("array")}]`;
        if (options.number.includes(key))
          type = `[${__("number")}]`;
        const deprecatedExtra = (deprecated) => typeof deprecated === "string" ? `[${__("deprecated: %s", deprecated)}]` : `[${__("deprecated")}]`;
        const extra = [
          key in deprecatedOptions ? deprecatedExtra(deprecatedOptions[key]) : null,
          type,
          key in demandedOptions ? `[${__("required")}]` : null,
          options.choices && options.choices[key] ? `[${__("choices:")} ${self2.stringifiedValues(options.choices[key])}]` : null,
          defaultString(options.default[key], options.defaultDescription[key])
        ].filter(Boolean).join(" ");
        ui2.span({
          text: getText(kswitch),
          padding: [0, 2, 0, 2 + getIndentation(kswitch)],
          width: maxWidth(switches, theWrap) + 4
        }, desc);
        const shouldHideOptionExtras = yargs.getInternalMethods().getUsageConfiguration()["hide-types"] === true;
        if (extra && !shouldHideOptionExtras)
          ui2.div({ text: extra, padding: [0, 0, 0, 2], align: "right" });
        else
          ui2.div();
      });
      ui2.div();
    });
    if (examples.length) {
      ui2.div(__("Examples:"));
      examples.forEach((example) => {
        example[0] = example[0].replace(/\$0/g, base$0);
      });
      examples.forEach((example) => {
        if (example[1] === "") {
          ui2.div({
            text: example[0],
            padding: [0, 2, 0, 2]
          });
        } else {
          ui2.div({
            text: example[0],
            padding: [0, 2, 0, 2],
            width: maxWidth(examples, theWrap) + 4
          }, {
            text: example[1]
          });
        }
      });
      ui2.div();
    }
    if (epilogs.length > 0) {
      const e = epilogs.map((epilog) => epilog.replace(/\$0/g, base$0)).join("\n");
      ui2.div(`${e}
`);
    }
    return ui2.toString().replace(/\s*$/, "");
  };
  function maxWidth(table, theWrap, modifier) {
    let width = 0;
    if (!Array.isArray(table)) {
      table = Object.values(table).map((v) => [v]);
    }
    table.forEach((v) => {
      width = Math.max(shim3.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width);
    });
    if (theWrap)
      width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10));
    return width;
  }
  function normalizeAliases() {
    const demandedOptions = yargs.getDemandedOptions();
    const options = yargs.getOptions();
    (Object.keys(options.alias) || []).forEach((key) => {
      options.alias[key].forEach((alias) => {
        if (descriptions[alias])
          self2.describe(key, descriptions[alias]);
        if (alias in demandedOptions)
          yargs.demandOption(key, demandedOptions[alias]);
        if (options.boolean.includes(alias))
          yargs.boolean(key);
        if (options.count.includes(alias))
          yargs.count(key);
        if (options.string.includes(alias))
          yargs.string(key);
        if (options.normalize.includes(alias))
          yargs.normalize(key);
        if (options.array.includes(alias))
          yargs.array(key);
        if (options.number.includes(alias))
          yargs.number(key);
      });
    });
  }
  let cachedHelpMessage;
  self2.cacheHelpMessage = function() {
    cachedHelpMessage = this.help();
  };
  self2.clearCachedHelpMessage = function() {
    cachedHelpMessage = void 0;
  };
  self2.hasCachedHelpMessage = function() {
    return !!cachedHelpMessage;
  };
  function addUngroupedKeys(keys, aliases, groups, defaultGroup) {
    let groupedKeys = [];
    let toCheck = null;
    Object.keys(groups).forEach((group) => {
      groupedKeys = groupedKeys.concat(groups[group]);
    });
    keys.forEach((key) => {
      toCheck = [key].concat(aliases[key]);
      if (!toCheck.some((k) => groupedKeys.indexOf(k) !== -1)) {
        groups[defaultGroup].push(key);
      }
    });
    return groupedKeys;
  }
  function filterHiddenOptions(key) {
    return yargs.getOptions().hiddenOptions.indexOf(key) < 0 || yargs.parsed.argv[yargs.getOptions().showHiddenOpt];
  }
  self2.showHelp = (level) => {
    const logger = yargs.getInternalMethods().getLoggerInstance();
    if (!level)
      level = "error";
    const emit = typeof level === "function" ? level : logger[level];
    emit(self2.help());
  };
  self2.functionDescription = (fn) => {
    const description = fn.name ? shim3.Parser.decamelize(fn.name, "-") : __("generated-value");
    return ["(", description, ")"].join("");
  };
  self2.stringifiedValues = function stringifiedValues(values, separator) {
    let string = "";
    const sep = separator || ", ";
    const array = [].concat(values);
    if (!values || !array.length)
      return string;
    array.forEach((value) => {
      if (string.length)
        string += sep;
      string += JSON.stringify(value);
    });
    return string;
  };
  function defaultString(value, defaultDescription) {
    let string = `[${__("default:")} `;
    if (value === void 0 && !defaultDescription)
      return null;
    if (defaultDescription) {
      string += defaultDescription;
    } else {
      switch (typeof value) {
        case "string":
          string += `"${value}"`;
          break;
        case "object":
          string += JSON.stringify(value);
          break;
        default:
          string += value;
      }
    }
    return `${string}]`;
  }
  function windowWidth() {
    const maxWidth2 = 80;
    if (shim3.process.stdColumns) {
      return Math.min(maxWidth2, shim3.process.stdColumns);
    } else {
      return maxWidth2;
    }
  }
  let version = null;
  self2.version = (ver) => {
    version = ver;
  };
  self2.showVersion = (level) => {
    const logger = yargs.getInternalMethods().getLoggerInstance();
    if (!level)
      level = "error";
    const emit = typeof level === "function" ? level : logger[level];
    emit(version);
  };
  self2.reset = function reset(localLookup) {
    failMessage = null;
    failureOutput = false;
    usages = [];
    usageDisabled = false;
    epilogs = [];
    examples = [];
    commands = [];
    descriptions = objFilter(descriptions, (k) => !localLookup[k]);
    return self2;
  };
  const frozens = [];
  self2.freeze = function freeze() {
    frozens.push({
      failMessage,
      failureOutput,
      usages,
      usageDisabled,
      epilogs,
      examples,
      commands,
      descriptions
    });
  };
  self2.unfreeze = function unfreeze(defaultCommand = false) {
    const frozen = frozens.pop();
    if (!frozen)
      return;
    if (defaultCommand) {
      descriptions = { ...frozen.descriptions, ...descriptions };
      commands = [...frozen.commands, ...commands];
      usages = [...frozen.usages, ...usages];
      examples = [...frozen.examples, ...examples];
      epilogs = [...frozen.epilogs, ...epilogs];
    } else {
      ({
        failMessage,
        failureOutput,
        usages,
        usageDisabled,
        epilogs,
        examples,
        commands,
        descriptions
      } = frozen);
    }
  };
  return self2;
}
function isIndentedText(text) {
  return typeof text === "object";
}
function addIndentation(text, indent) {
  return isIndentedText(text) ? { text: text.text, indentation: text.indentation + indent } : { text, indentation: indent };
}
function getIndentation(text) {
  return isIndentedText(text) ? text.indentation : 0;
}
function getText(text) {
  return isIndentedText(text) ? text.text : text;
}
var init_usage = __esm({
  "node_modules/yargs/build/lib/usage.js"() {
    init_prefix();
    init_obj_filter();
    init_yerror();
    init_set_blocking();
  }
});

// node_modules/yargs/build/lib/completion-templates.js
var completionShTemplate, completionZshTemplate;
var init_completion_templates = __esm({
  "node_modules/yargs/build/lib/completion-templates.js"() {
    init_prefix();
    completionShTemplate = `###-begin-{{app_name}}-completions-###
#
# yargs command completion script
#
# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc
#    or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.
#
_{{app_name}}_yargs_completions()
{
    local cur_word args type_list

    cur_word="\${COMP_WORDS[COMP_CWORD]}"
    args=("\${COMP_WORDS[@]}")

    # ask yargs to generate completions.
    type_list=$({{app_path}} --get-yargs-completions "\${args[@]}")

    COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) )

    # if no match was found, fall back to filename completion
    if [ \${#COMPREPLY[@]} -eq 0 ]; then
      COMPREPLY=()
    fi

    return 0
}
complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
###-end-{{app_name}}-completions-###
`;
    completionZshTemplate = `#compdef {{app_name}}
###-begin-{{app_name}}-completions-###
#
# yargs command completion script
#
# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc
#    or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX.
#
_{{app_name}}_yargs_completions()
{
  local reply
  local si=$IFS
  IFS=$'
' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}"))
  IFS=$si
  _describe 'values' reply
}
compdef _{{app_name}}_yargs_completions {{app_name}}
###-end-{{app_name}}-completions-###
`;
  }
});

// node_modules/yargs/build/lib/completion.js
function completion(yargs, usage2, command2, shim3) {
  return new Completion(yargs, usage2, command2, shim3);
}
function isSyncCompletionFunction(completionFunction) {
  return completionFunction.length < 3;
}
function isFallbackCompletionFunction(completionFunction) {
  return completionFunction.length > 3;
}
var Completion;
var init_completion = __esm({
  "node_modules/yargs/build/lib/completion.js"() {
    init_prefix();
    init_command();
    init_common_types();
    init_completion_templates();
    init_is_promise();
    init_parse_command();
    Completion = class {
      constructor(yargs, usage2, command2, shim3) {
        var _a2, _b2, _c2;
        this.yargs = yargs;
        this.usage = usage2;
        this.command = command2;
        this.shim = shim3;
        this.completionKey = "get-yargs-completions";
        this.aliases = null;
        this.customCompletionFunction = null;
        this.indexAfterLastReset = 0;
        this.zshShell = (_c2 = ((_a2 = this.shim.getEnv("SHELL")) === null || _a2 === void 0 ? void 0 : _a2.includes("zsh")) || ((_b2 = this.shim.getEnv("ZSH_NAME")) === null || _b2 === void 0 ? void 0 : _b2.includes("zsh"))) !== null && _c2 !== void 0 ? _c2 : false;
      }
      defaultCompletion(args2, argv, current, done) {
        const handlers = this.command.getCommandHandlers();
        for (let i = 0, ii = args2.length; i < ii; ++i) {
          if (handlers[args2[i]] && handlers[args2[i]].builder) {
            const builder = handlers[args2[i]].builder;
            if (isCommandBuilderCallback(builder)) {
              this.indexAfterLastReset = i + 1;
              const y = this.yargs.getInternalMethods().reset();
              builder(y, true);
              return y.argv;
            }
          }
        }
        const completions = [];
        this.commandCompletions(completions, args2, current);
        this.optionCompletions(completions, args2, argv, current);
        this.choicesFromOptionsCompletions(completions, args2, argv, current);
        this.choicesFromPositionalsCompletions(completions, args2, argv, current);
        done(null, completions);
      }
      commandCompletions(completions, args2, current) {
        const parentCommands = this.yargs.getInternalMethods().getContext().commands;
        if (!current.match(/^-/) && parentCommands[parentCommands.length - 1] !== current && !this.previousArgHasChoices(args2)) {
          this.usage.getCommands().forEach((usageCommand) => {
            const commandName = parseCommand(usageCommand[0]).cmd;
            if (args2.indexOf(commandName) === -1) {
              if (!this.zshShell) {
                completions.push(commandName);
              } else {
                const desc = usageCommand[1] || "";
                completions.push(commandName.replace(/:/g, "\\:") + ":" + desc);
              }
            }
          });
        }
      }
      optionCompletions(completions, args2, argv, current) {
        if ((current.match(/^-/) || current === "" && completions.length === 0) && !this.previousArgHasChoices(args2)) {
          const options = this.yargs.getOptions();
          const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
          Object.keys(options.key).forEach((key) => {
            const negable = !!options.configuration["boolean-negation"] && options.boolean.includes(key);
            const isPositionalKey = positionalKeys.includes(key);
            if (!isPositionalKey && !options.hiddenOptions.includes(key) && !this.argsContainKey(args2, key, negable)) {
              this.completeOptionKey(key, completions, current, negable && !!options.default[key]);
            }
          });
        }
      }
      choicesFromOptionsCompletions(completions, args2, argv, current) {
        if (this.previousArgHasChoices(args2)) {
          const choices = this.getPreviousArgChoices(args2);
          if (choices && choices.length > 0) {
            completions.push(...choices.map((c) => c.replace(/:/g, "\\:")));
          }
        }
      }
      choicesFromPositionalsCompletions(completions, args2, argv, current) {
        if (current === "" && completions.length > 0 && this.previousArgHasChoices(args2)) {
          return;
        }
        const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
        const offset = Math.max(this.indexAfterLastReset, this.yargs.getInternalMethods().getContext().commands.length + 1);
        const positionalKey = positionalKeys[argv._.length - offset - 1];
        if (!positionalKey) {
          return;
        }
        const choices = this.yargs.getOptions().choices[positionalKey] || [];
        for (const choice of choices) {
          if (choice.startsWith(current)) {
            completions.push(choice.replace(/:/g, "\\:"));
          }
        }
      }
      getPreviousArgChoices(args2) {
        if (args2.length < 1)
          return;
        let previousArg = args2[args2.length - 1];
        let filter = "";
        if (!previousArg.startsWith("-") && args2.length > 1) {
          filter = previousArg;
          previousArg = args2[args2.length - 2];
        }
        if (!previousArg.startsWith("-"))
          return;
        const previousArgKey = previousArg.replace(/^-+/, "");
        const options = this.yargs.getOptions();
        const possibleAliases = [
          previousArgKey,
          ...this.yargs.getAliases()[previousArgKey] || []
        ];
        let choices;
        for (const possibleAlias of possibleAliases) {
          if (Object.prototype.hasOwnProperty.call(options.key, possibleAlias) && Array.isArray(options.choices[possibleAlias])) {
            choices = options.choices[possibleAlias];
            break;
          }
        }
        if (choices) {
          return choices.filter((choice) => !filter || choice.startsWith(filter));
        }
      }
      previousArgHasChoices(args2) {
        const choices = this.getPreviousArgChoices(args2);
        return choices !== void 0 && choices.length > 0;
      }
      argsContainKey(args2, key, negable) {
        const argsContains = (s) => args2.indexOf((/^[^0-9]$/.test(s) ? "-" : "--") + s) !== -1;
        if (argsContains(key))
          return true;
        if (negable && argsContains(`no-${key}`))
          return true;
        if (this.aliases) {
          for (const alias of this.aliases[key]) {
            if (argsContains(alias))
              return true;
          }
        }
        return false;
      }
      completeOptionKey(key, completions, current, negable) {
        var _a2, _b2, _c2, _d;
        let keyWithDesc = key;
        if (this.zshShell) {
          const descs = this.usage.getDescriptions();
          const aliasKey = (_b2 = (_a2 = this === null || this === void 0 ? void 0 : this.aliases) === null || _a2 === void 0 ? void 0 : _a2[key]) === null || _b2 === void 0 ? void 0 : _b2.find((alias) => {
            const desc2 = descs[alias];
            return typeof desc2 === "string" && desc2.length > 0;
          });
          const descFromAlias = aliasKey ? descs[aliasKey] : void 0;
          const desc = (_d = (_c2 = descs[key]) !== null && _c2 !== void 0 ? _c2 : descFromAlias) !== null && _d !== void 0 ? _d : "";
          keyWithDesc = `${key.replace(/:/g, "\\:")}:${desc.replace("__yargsString__:", "").replace(/(\r\n|\n|\r)/gm, " ")}`;
        }
        const startsByTwoDashes = (s) => /^--/.test(s);
        const isShortOption = (s) => /^[^0-9]$/.test(s);
        const dashes = !startsByTwoDashes(current) && isShortOption(key) ? "-" : "--";
        completions.push(dashes + keyWithDesc);
        if (negable) {
          completions.push(dashes + "no-" + keyWithDesc);
        }
      }
      customCompletion(args2, argv, current, done) {
        assertNotStrictEqual(this.customCompletionFunction, null, this.shim);
        if (isSyncCompletionFunction(this.customCompletionFunction)) {
          const result = this.customCompletionFunction(current, argv);
          if (isPromise(result)) {
            return result.then((list) => {
              this.shim.process.nextTick(() => {
                done(null, list);
              });
            }).catch((err) => {
              this.shim.process.nextTick(() => {
                done(err, void 0);
              });
            });
          }
          return done(null, result);
        } else if (isFallbackCompletionFunction(this.customCompletionFunction)) {
          return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args2, argv, current, onCompleted), (completions) => {
            done(null, completions);
          });
        } else {
          return this.customCompletionFunction(current, argv, (completions) => {
            done(null, completions);
          });
        }
      }
      getCompletion(args2, done) {
        const current = args2.length ? args2[args2.length - 1] : "";
        const argv = this.yargs.parse(args2, true);
        const completionFunction = this.customCompletionFunction ? (argv2) => this.customCompletion(args2, argv2, current, done) : (argv2) => this.defaultCompletion(args2, argv2, current, done);
        return isPromise(argv) ? argv.then(completionFunction) : completionFunction(argv);
      }
      generateCompletionScript($0, cmd) {
        let script = this.zshShell ? completionZshTemplate : completionShTemplate;
        const name = this.shim.path.basename($0);
        if ($0.match(/\.js$/))
          $0 = `./${$0}`;
        script = script.replace(/{{app_name}}/g, name);
        script = script.replace(/{{completion_command}}/g, cmd);
        return script.replace(/{{app_path}}/g, $0);
      }
      registerFunction(fn) {
        this.customCompletionFunction = fn;
      }
      setParsed(parsed) {
        this.aliases = parsed.aliases;
      }
    };
  }
});

// node_modules/yargs/build/lib/utils/levenshtein.js
function levenshtein(a, b) {
  if (a.length === 0)
    return b.length;
  if (b.length === 0)
    return a.length;
  const matrix = [];
  let i;
  for (i = 0; i <= b.length; i++) {
    matrix[i] = [i];
  }
  let j;
  for (j = 0; j <= a.length; j++) {
    matrix[0][j] = j;
  }
  for (i = 1; i <= b.length; i++) {
    for (j = 1; j <= a.length; j++) {
      if (b.charAt(i - 1) === a.charAt(j - 1)) {
        matrix[i][j] = matrix[i - 1][j - 1];
      } else {
        if (i > 1 && j > 1 && b.charAt(i - 2) === a.charAt(j - 1) && b.charAt(i - 1) === a.charAt(j - 2)) {
          matrix[i][j] = matrix[i - 2][j - 2] + 1;
        } else {
          matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1));
        }
      }
    }
  }
  return matrix[b.length][a.length];
}
var init_levenshtein = __esm({
  "node_modules/yargs/build/lib/utils/levenshtein.js"() {
    init_prefix();
  }
});

// node_modules/yargs/build/lib/validation.js
function validation(yargs, usage2, shim3) {
  const __ = shim3.y18n.__;
  const __n = shim3.y18n.__n;
  const self2 = {};
  self2.nonOptionCount = function nonOptionCount(argv) {
    const demandedCommands = yargs.getDemandedCommands();
    const positionalCount = argv._.length + (argv["--"] ? argv["--"].length : 0);
    const _s = positionalCount - yargs.getInternalMethods().getContext().commands.length;
    if (demandedCommands._ && (_s < demandedCommands._.min || _s > demandedCommands._.max)) {
      if (_s < demandedCommands._.min) {
        if (demandedCommands._.minMsg !== void 0) {
          usage2.fail(demandedCommands._.minMsg ? demandedCommands._.minMsg.replace(/\$0/g, _s.toString()).replace(/\$1/, demandedCommands._.min.toString()) : null);
        } else {
          usage2.fail(__n("Not enough non-option arguments: got %s, need at least %s", "Not enough non-option arguments: got %s, need at least %s", _s, _s.toString(), demandedCommands._.min.toString()));
        }
      } else if (_s > demandedCommands._.max) {
        if (demandedCommands._.maxMsg !== void 0) {
          usage2.fail(demandedCommands._.maxMsg ? demandedCommands._.maxMsg.replace(/\$0/g, _s.toString()).replace(/\$1/, demandedCommands._.max.toString()) : null);
        } else {
          usage2.fail(__n("Too many non-option arguments: got %s, maximum of %s", "Too many non-option arguments: got %s, maximum of %s", _s, _s.toString(), demandedCommands._.max.toString()));
        }
      }
    }
  };
  self2.positionalCount = function positionalCount(required, observed) {
    if (observed < required) {
      usage2.fail(__n("Not enough non-option arguments: got %s, need at least %s", "Not enough non-option arguments: got %s, need at least %s", observed, observed + "", required + ""));
    }
  };
  self2.requiredArguments = function requiredArguments(argv, demandedOptions) {
    let missing = null;
    for (const key of Object.keys(demandedOptions)) {
      if (!Object.prototype.hasOwnProperty.call(argv, key) || typeof argv[key] === "undefined") {
        missing = missing || {};
        missing[key] = demandedOptions[key];
      }
    }
    if (missing) {
      const customMsgs = [];
      for (const key of Object.keys(missing)) {
        const msg = missing[key];
        if (msg && customMsgs.indexOf(msg) < 0) {
          customMsgs.push(msg);
        }
      }
      const customMsg = customMsgs.length ? `
${customMsgs.join("\n")}` : "";
      usage2.fail(__n("Missing required argument: %s", "Missing required arguments: %s", Object.keys(missing).length, Object.keys(missing).join(", ") + customMsg));
    }
  };
  self2.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand, checkPositionals = true) {
    var _a2;
    const commandKeys = yargs.getInternalMethods().getCommandInstance().getCommands();
    const unknown = [];
    const currentContext = yargs.getInternalMethods().getContext();
    Object.keys(argv).forEach((key) => {
      if (!specialKeys.includes(key) && !Object.prototype.hasOwnProperty.call(positionalMap, key) && !Object.prototype.hasOwnProperty.call(yargs.getInternalMethods().getParseContext(), key) && !self2.isValidAndSomeAliasIsNotNew(key, aliases)) {
        unknown.push(key);
      }
    });
    if (checkPositionals && (currentContext.commands.length > 0 || commandKeys.length > 0 || isDefaultCommand)) {
      argv._.slice(currentContext.commands.length).forEach((key) => {
        if (!commandKeys.includes("" + key)) {
          unknown.push("" + key);
        }
      });
    }
    if (checkPositionals) {
      const demandedCommands = yargs.getDemandedCommands();
      const maxNonOptDemanded = ((_a2 = demandedCommands._) === null || _a2 === void 0 ? void 0 : _a2.max) || 0;
      const expected = currentContext.commands.length + maxNonOptDemanded;
      if (expected < argv._.length) {
        argv._.slice(expected).forEach((key) => {
          key = String(key);
          if (!currentContext.commands.includes(key) && !unknown.includes(key)) {
            unknown.push(key);
          }
        });
      }
    }
    if (unknown.length) {
      usage2.fail(__n("Unknown argument: %s", "Unknown arguments: %s", unknown.length, unknown.map((s) => s.trim() ? s : `"${s}"`).join(", ")));
    }
  };
  self2.unknownCommands = function unknownCommands(argv) {
    const commandKeys = yargs.getInternalMethods().getCommandInstance().getCommands();
    const unknown = [];
    const currentContext = yargs.getInternalMethods().getContext();
    if (currentContext.commands.length > 0 || commandKeys.length > 0) {
      argv._.slice(currentContext.commands.length).forEach((key) => {
        if (!commandKeys.includes("" + key)) {
          unknown.push("" + key);
        }
      });
    }
    if (unknown.length > 0) {
      usage2.fail(__n("Unknown command: %s", "Unknown commands: %s", unknown.length, unknown.join(", ")));
      return true;
    } else {
      return false;
    }
  };
  self2.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) {
    if (!Object.prototype.hasOwnProperty.call(aliases, key)) {
      return false;
    }
    const newAliases = yargs.parsed.newAliases;
    return [key, ...aliases[key]].some((a) => !Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]);
  };
  self2.limitedChoices = function limitedChoices(argv) {
    const options = yargs.getOptions();
    const invalid = {};
    if (!Object.keys(options.choices).length)
      return;
    Object.keys(argv).forEach((key) => {
      if (specialKeys.indexOf(key) === -1 && Object.prototype.hasOwnProperty.call(options.choices, key)) {
        [].concat(argv[key]).forEach((value) => {
          if (options.choices[key].indexOf(value) === -1 && value !== void 0) {
            invalid[key] = (invalid[key] || []).concat(value);
          }
        });
      }
    });
    const invalidKeys = Object.keys(invalid);
    if (!invalidKeys.length)
      return;
    let msg = __("Invalid values:");
    invalidKeys.forEach((key) => {
      msg += `
  ${__("Argument: %s, Given: %s, Choices: %s", key, usage2.stringifiedValues(invalid[key]), usage2.stringifiedValues(options.choices[key]))}`;
    });
    usage2.fail(msg);
  };
  let implied = {};
  self2.implies = function implies(key, value) {
    argsert("<string|object> [array|number|string]", [key, value], arguments.length);
    if (typeof key === "object") {
      Object.keys(key).forEach((k) => {
        self2.implies(k, key[k]);
      });
    } else {
      yargs.global(key);
      if (!implied[key]) {
        implied[key] = [];
      }
      if (Array.isArray(value)) {
        value.forEach((i) => self2.implies(key, i));
      } else {
        assertNotStrictEqual(value, void 0, shim3);
        implied[key].push(value);
      }
    }
  };
  self2.getImplied = function getImplied() {
    return implied;
  };
  function keyExists(argv, val) {
    const num = Number(val);
    val = isNaN(num) ? val : num;
    if (typeof val === "number") {
      val = argv._.length >= val;
    } else if (val.match(/^--no-.+/)) {
      val = val.match(/^--no-(.+)/)[1];
      val = !Object.prototype.hasOwnProperty.call(argv, val);
    } else {
      val = Object.prototype.hasOwnProperty.call(argv, val);
    }
    return val;
  }
  self2.implications = function implications(argv) {
    const implyFail = [];
    Object.keys(implied).forEach((key) => {
      const origKey = key;
      (implied[key] || []).forEach((value) => {
        let key2 = origKey;
        const origValue = value;
        key2 = keyExists(argv, key2);
        value = keyExists(argv, value);
        if (key2 && !value) {
          implyFail.push(` ${origKey} -> ${origValue}`);
        }
      });
    });
    if (implyFail.length) {
      let msg = `${__("Implications failed:")}
`;
      implyFail.forEach((value) => {
        msg += value;
      });
      usage2.fail(msg);
    }
  };
  let conflicting = {};
  self2.conflicts = function conflicts(key, value) {
    argsert("<string|object> [array|string]", [key, value], arguments.length);
    if (typeof key === "object") {
      Object.keys(key).forEach((k) => {
        self2.conflicts(k, key[k]);
      });
    } else {
      yargs.global(key);
      if (!conflicting[key]) {
        conflicting[key] = [];
      }
      if (Array.isArray(value)) {
        value.forEach((i) => self2.conflicts(key, i));
      } else {
        conflicting[key].push(value);
      }
    }
  };
  self2.getConflicting = () => conflicting;
  self2.conflicting = function conflictingFn(argv) {
    Object.keys(argv).forEach((key) => {
      if (conflicting[key]) {
        conflicting[key].forEach((value) => {
          if (value && argv[key] !== void 0 && argv[value] !== void 0) {
            usage2.fail(__("Arguments %s and %s are mutually exclusive", key, value));
          }
        });
      }
    });
    if (yargs.getInternalMethods().getParserConfiguration()["strip-dashed"]) {
      Object.keys(conflicting).forEach((key) => {
        conflicting[key].forEach((value) => {
          if (value && argv[shim3.Parser.camelCase(key)] !== void 0 && argv[shim3.Parser.camelCase(value)] !== void 0) {
            usage2.fail(__("Arguments %s and %s are mutually exclusive", key, value));
          }
        });
      });
    }
  };
  self2.recommendCommands = function recommendCommands(cmd, potentialCommands) {
    const threshold = 3;
    potentialCommands = potentialCommands.sort((a, b) => b.length - a.length);
    let recommended = null;
    let bestDistance = Infinity;
    for (let i = 0, candidate; (candidate = potentialCommands[i]) !== void 0; i++) {
      const d = levenshtein(cmd, candidate);
      if (d <= threshold && d < bestDistance) {
        bestDistance = d;
        recommended = candidate;
      }
    }
    if (recommended)
      usage2.fail(__("Did you mean %s?", recommended));
  };
  self2.reset = function reset(localLookup) {
    implied = objFilter(implied, (k) => !localLookup[k]);
    conflicting = objFilter(conflicting, (k) => !localLookup[k]);
    return self2;
  };
  const frozens = [];
  self2.freeze = function freeze() {
    frozens.push({
      implied,
      conflicting
    });
  };
  self2.unfreeze = function unfreeze() {
    const frozen = frozens.pop();
    assertNotStrictEqual(frozen, void 0, shim3);
    ({ implied, conflicting } = frozen);
  };
  return self2;
}
var specialKeys;
var init_validation = __esm({
  "node_modules/yargs/build/lib/validation.js"() {
    init_prefix();
    init_argsert();
    init_common_types();
    init_levenshtein();
    init_obj_filter();
    specialKeys = ["$0", "--", "_"];
  }
});

// node_modules/yargs/build/lib/utils/apply-extends.js
function applyExtends(config2, cwd, mergeExtends, _shim) {
  shim2 = _shim;
  let defaultConfig = {};
  if (Object.prototype.hasOwnProperty.call(config2, "extends")) {
    if (typeof config2.extends !== "string")
      return defaultConfig;
    const isPath = /\.json|\..*rc$/.test(config2.extends);
    let pathToDefault = null;
    if (!isPath) {
      try {
        pathToDefault = require.resolve(config2.extends);
      } catch (_err) {
        return config2;
      }
    } else {
      pathToDefault = getPathToDefaultConfig(cwd, config2.extends);
    }
    checkForCircularExtends(pathToDefault);
    previouslyVisitedConfigs.push(pathToDefault);
    defaultConfig = isPath ? JSON.parse(shim2.readFileSync(pathToDefault, "utf8")) : require(config2.extends);
    delete config2.extends;
    defaultConfig = applyExtends(defaultConfig, shim2.path.dirname(pathToDefault), mergeExtends, shim2);
  }
  previouslyVisitedConfigs = [];
  return mergeExtends ? mergeDeep(defaultConfig, config2) : Object.assign({}, defaultConfig, config2);
}
function checkForCircularExtends(cfgPath) {
  if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
    throw new YError(`Circular extended configurations: '${cfgPath}'.`);
  }
}
function getPathToDefaultConfig(cwd, pathToExtend) {
  return shim2.path.resolve(cwd, pathToExtend);
}
function mergeDeep(config1, config2) {
  const target = {};
  function isObject(obj) {
    return obj && typeof obj === "object" && !Array.isArray(obj);
  }
  Object.assign(target, config1);
  for (const key of Object.keys(config2)) {
    if (isObject(config2[key]) && isObject(target[key])) {
      target[key] = mergeDeep(config1[key], config2[key]);
    } else {
      target[key] = config2[key];
    }
  }
  return target;
}
var previouslyVisitedConfigs, shim2;
var init_apply_extends = __esm({
  "node_modules/yargs/build/lib/utils/apply-extends.js"() {
    init_prefix();
    init_yerror();
    previouslyVisitedConfigs = [];
  }
});

// node_modules/yargs/build/lib/yargs-factory.js
function YargsFactory(_shim) {
  return (processArgs = [], cwd = _shim.process.cwd(), parentRequire) => {
    const yargs = new YargsInstance(processArgs, cwd, parentRequire, _shim);
    Object.defineProperty(yargs, "argv", {
      get: () => {
        return yargs.parse();
      },
      enumerable: true
    });
    yargs.help();
    yargs.version();
    return yargs;
  };
}
function isYargsInstance(y) {
  return !!y && typeof y.getInternalMethods === "function";
}
var __classPrivateFieldSet2, __classPrivateFieldGet2, _YargsInstance_command, _YargsInstance_cwd, _YargsInstance_context, _YargsInstance_completion, _YargsInstance_completionCommand, _YargsInstance_defaultShowHiddenOpt, _YargsInstance_exitError, _YargsInstance_detectLocale, _YargsInstance_emittedWarnings, _YargsInstance_exitProcess, _YargsInstance_frozens, _YargsInstance_globalMiddleware, _YargsInstance_groups, _YargsInstance_hasOutput, _YargsInstance_helpOpt, _YargsInstance_isGlobalContext, _YargsInstance_logger, _YargsInstance_output, _YargsInstance_options, _YargsInstance_parentRequire, _YargsInstance_parserConfig, _YargsInstance_parseFn, _YargsInstance_parseContext, _YargsInstance_pkgs, _YargsInstance_preservedGroups, _YargsInstance_processArgs, _YargsInstance_recommendCommands, _YargsInstance_shim, _YargsInstance_strict, _YargsInstance_strictCommands, _YargsInstance_strictOptions, _YargsInstance_usage, _YargsInstance_usageConfig, _YargsInstance_versionOpt, _YargsInstance_validation, kCopyDoubleDash, kCreateLogger, kDeleteFromParserHintObject, kEmitWarning, kFreeze, kGetDollarZero, kGetParserConfiguration, kGetUsageConfiguration, kGuessLocale, kGuessVersion, kParsePositionalNumbers, kPkgUp, kPopulateParserHintArray, kPopulateParserHintSingleValueDictionary, kPopulateParserHintArrayDictionary, kPopulateParserHintDictionary, kSanitizeKey, kSetKey, kUnfreeze, kValidateAsync, kGetCommandInstance, kGetContext, kGetHasOutput, kGetLoggerInstance, kGetParseContext, kGetUsageInstance, kGetValidationInstance, kHasParseCallback, kIsGlobalContext, kPostProcess, kRebase, kReset, kRunYargsParserAndExecuteCommands, kRunValidation, kSetHasOutput, kTrackManuallySetKeys, YargsInstance;
var init_yargs_factory = __esm({
  "node_modules/yargs/build/lib/yargs-factory.js"() {
    init_prefix();
    init_command();
    init_common_types();
    init_yerror();
    init_usage();
    init_argsert();
    init_completion();
    init_validation();
    init_obj_filter();
    init_apply_extends();
    init_middleware();
    init_is_promise();
    init_maybe_async_result();
    init_set_blocking();
    __classPrivateFieldSet2 = function(receiver, state, value, kind, f) {
      if (kind === "m") throw new TypeError("Private method is not writable");
      if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
      if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
      return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
    };
    __classPrivateFieldGet2 = function(receiver, state, kind, f) {
      if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
      if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
      return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    };
    kCopyDoubleDash = /* @__PURE__ */ Symbol("copyDoubleDash");
    kCreateLogger = /* @__PURE__ */ Symbol("copyDoubleDash");
    kDeleteFromParserHintObject = /* @__PURE__ */ Symbol("deleteFromParserHintObject");
    kEmitWarning = /* @__PURE__ */ Symbol("emitWarning");
    kFreeze = /* @__PURE__ */ Symbol("freeze");
    kGetDollarZero = /* @__PURE__ */ Symbol("getDollarZero");
    kGetParserConfiguration = /* @__PURE__ */ Symbol("getParserConfiguration");
    kGetUsageConfiguration = /* @__PURE__ */ Symbol("getUsageConfiguration");
    kGuessLocale = /* @__PURE__ */ Symbol("guessLocale");
    kGuessVersion = /* @__PURE__ */ Symbol("guessVersion");
    kParsePositionalNumbers = /* @__PURE__ */ Symbol("parsePositionalNumbers");
    kPkgUp = /* @__PURE__ */ Symbol("pkgUp");
    kPopulateParserHintArray = /* @__PURE__ */ Symbol("populateParserHintArray");
    kPopulateParserHintSingleValueDictionary = /* @__PURE__ */ Symbol("populateParserHintSingleValueDictionary");
    kPopulateParserHintArrayDictionary = /* @__PURE__ */ Symbol("populateParserHintArrayDictionary");
    kPopulateParserHintDictionary = /* @__PURE__ */ Symbol("populateParserHintDictionary");
    kSanitizeKey = /* @__PURE__ */ Symbol("sanitizeKey");
    kSetKey = /* @__PURE__ */ Symbol("setKey");
    kUnfreeze = /* @__PURE__ */ Symbol("unfreeze");
    kValidateAsync = /* @__PURE__ */ Symbol("validateAsync");
    kGetCommandInstance = /* @__PURE__ */ Symbol("getCommandInstance");
    kGetContext = /* @__PURE__ */ Symbol("getContext");
    kGetHasOutput = /* @__PURE__ */ Symbol("getHasOutput");
    kGetLoggerInstance = /* @__PURE__ */ Symbol("getLoggerInstance");
    kGetParseContext = /* @__PURE__ */ Symbol("getParseContext");
    kGetUsageInstance = /* @__PURE__ */ Symbol("getUsageInstance");
    kGetValidationInstance = /* @__PURE__ */ Symbol("getValidationInstance");
    kHasParseCallback = /* @__PURE__ */ Symbol("hasParseCallback");
    kIsGlobalContext = /* @__PURE__ */ Symbol("isGlobalContext");
    kPostProcess = /* @__PURE__ */ Symbol("postProcess");
    kRebase = /* @__PURE__ */ Symbol("rebase");
    kReset = /* @__PURE__ */ Symbol("reset");
    kRunYargsParserAndExecuteCommands = /* @__PURE__ */ Symbol("runYargsParserAndExecuteCommands");
    kRunValidation = /* @__PURE__ */ Symbol("runValidation");
    kSetHasOutput = /* @__PURE__ */ Symbol("setHasOutput");
    kTrackManuallySetKeys = /* @__PURE__ */ Symbol("kTrackManuallySetKeys");
    YargsInstance = class {
      constructor(processArgs = [], cwd, parentRequire, shim3) {
        this.customScriptName = false;
        this.parsed = false;
        _YargsInstance_command.set(this, void 0);
        _YargsInstance_cwd.set(this, void 0);
        _YargsInstance_context.set(this, { commands: [], fullCommands: [] });
        _YargsInstance_completion.set(this, null);
        _YargsInstance_completionCommand.set(this, null);
        _YargsInstance_defaultShowHiddenOpt.set(this, "show-hidden");
        _YargsInstance_exitError.set(this, null);
        _YargsInstance_detectLocale.set(this, true);
        _YargsInstance_emittedWarnings.set(this, {});
        _YargsInstance_exitProcess.set(this, true);
        _YargsInstance_frozens.set(this, []);
        _YargsInstance_globalMiddleware.set(this, void 0);
        _YargsInstance_groups.set(this, {});
        _YargsInstance_hasOutput.set(this, false);
        _YargsInstance_helpOpt.set(this, null);
        _YargsInstance_isGlobalContext.set(this, true);
        _YargsInstance_logger.set(this, void 0);
        _YargsInstance_output.set(this, "");
        _YargsInstance_options.set(this, void 0);
        _YargsInstance_parentRequire.set(this, void 0);
        _YargsInstance_parserConfig.set(this, {});
        _YargsInstance_parseFn.set(this, null);
        _YargsInstance_parseContext.set(this, null);
        _YargsInstance_pkgs.set(this, {});
        _YargsInstance_preservedGroups.set(this, {});
        _YargsInstance_processArgs.set(this, void 0);
        _YargsInstance_recommendCommands.set(this, false);
        _YargsInstance_shim.set(this, void 0);
        _YargsInstance_strict.set(this, false);
        _YargsInstance_strictCommands.set(this, false);
        _YargsInstance_strictOptions.set(this, false);
        _YargsInstance_usage.set(this, void 0);
        _YargsInstance_usageConfig.set(this, {});
        _YargsInstance_versionOpt.set(this, null);
        _YargsInstance_validation.set(this, void 0);
        __classPrivateFieldSet2(this, _YargsInstance_shim, shim3, "f");
        __classPrivateFieldSet2(this, _YargsInstance_processArgs, processArgs, "f");
        __classPrivateFieldSet2(this, _YargsInstance_cwd, cwd, "f");
        __classPrivateFieldSet2(this, _YargsInstance_parentRequire, parentRequire, "f");
        __classPrivateFieldSet2(this, _YargsInstance_globalMiddleware, new GlobalMiddleware(this), "f");
        this.$0 = this[kGetDollarZero]();
        this[kReset]();
        __classPrivateFieldSet2(this, _YargsInstance_command, __classPrivateFieldGet2(this, _YargsInstance_command, "f"), "f");
        __classPrivateFieldSet2(this, _YargsInstance_usage, __classPrivateFieldGet2(this, _YargsInstance_usage, "f"), "f");
        __classPrivateFieldSet2(this, _YargsInstance_validation, __classPrivateFieldGet2(this, _YargsInstance_validation, "f"), "f");
        __classPrivateFieldSet2(this, _YargsInstance_options, __classPrivateFieldGet2(this, _YargsInstance_options, "f"), "f");
        __classPrivateFieldGet2(this, _YargsInstance_options, "f").showHiddenOpt = __classPrivateFieldGet2(this, _YargsInstance_defaultShowHiddenOpt, "f");
        __classPrivateFieldSet2(this, _YargsInstance_logger, this[kCreateLogger](), "f");
      }
      addHelpOpt(opt, msg) {
        const defaultHelpOpt = "help";
        argsert("[string|boolean] [string]", [opt, msg], arguments.length);
        if (__classPrivateFieldGet2(this, _YargsInstance_helpOpt, "f")) {
          this[kDeleteFromParserHintObject](__classPrivateFieldGet2(this, _YargsInstance_helpOpt, "f"));
          __classPrivateFieldSet2(this, _YargsInstance_helpOpt, null, "f");
        }
        if (opt === false && msg === void 0)
          return this;
        __classPrivateFieldSet2(this, _YargsInstance_helpOpt, typeof opt === "string" ? opt : defaultHelpOpt, "f");
        this.boolean(__classPrivateFieldGet2(this, _YargsInstance_helpOpt, "f"));
        this.describe(__classPrivateFieldGet2(this, _YargsInstance_helpOpt, "f"), msg || __classPrivateFieldGet2(this, _YargsInstance_usage, "f").deferY18nLookup("Show help"));
        return this;
      }
      help(opt, msg) {
        return this.addHelpOpt(opt, msg);
      }
      addShowHiddenOpt(opt, msg) {
        argsert("[string|boolean] [string]", [opt, msg], arguments.length);
        if (opt === false && msg === void 0)
          return this;
        const showHiddenOpt = typeof opt === "string" ? opt : __classPrivateFieldGet2(this, _YargsInstance_defaultShowHiddenOpt, "f");
        this.boolean(showHiddenOpt);
        this.describe(showHiddenOpt, msg || __classPrivateFieldGet2(this, _YargsInstance_usage, "f").deferY18nLookup("Show hidden options"));
        __classPrivateFieldGet2(this, _YargsInstance_options, "f").showHiddenOpt = showHiddenOpt;
        return this;
      }
      showHidden(opt, msg) {
        return this.addShowHiddenOpt(opt, msg);
      }
      alias(key, value) {
        argsert("<object|string|array> [string|array]", [key, value], arguments.length);
        this[kPopulateParserHintArrayDictionary](this.alias.bind(this), "alias", key, value);
        return this;
      }
      array(keys) {
        argsert("<array|string>", [keys], arguments.length);
        this[kPopulateParserHintArray]("array", keys);
        this[kTrackManuallySetKeys](keys);
        return this;
      }
      boolean(keys) {
        argsert("<array|string>", [keys], arguments.length);
        this[kPopulateParserHintArray]("boolean", keys);
        this[kTrackManuallySetKeys](keys);
        return this;
      }
      check(f, global2) {
        argsert("<function> [boolean]", [f, global2], arguments.length);
        this.middleware((argv, _yargs) => {
          return maybeAsyncResult(() => {
            return f(argv, _yargs.getOptions());
          }, (result) => {
            if (!result) {
              __classPrivateFieldGet2(this, _YargsInstance_usage, "f").fail(__classPrivateFieldGet2(this, _YargsInstance_shim, "f").y18n.__("Argument check failed: %s", f.toString()));
            } else if (typeof result === "string" || result instanceof Error) {
              __classPrivateFieldGet2(this, _YargsInstance_usage, "f").fail(result.toString(), result);
            }
            return argv;
          }, (err) => {
            __classPrivateFieldGet2(this, _YargsInstance_usage, "f").fail(err.message ? err.message : err.toString(), err);
            return argv;
          });
        }, false, global2);
        return this;
      }
      choices(key, value) {
        argsert("<object|string|array> [string|array]", [key, value], arguments.length);
        this[kPopulateParserHintArrayDictionary](this.choices.bind(this), "choices", key, value);
        return this;
      }
      coerce(keys, value) {
        argsert("<object|string|array> [function]", [keys, value], arguments.length);
        if (Array.isArray(keys)) {
          if (!value) {
            throw new YError("coerce callback must be provided");
          }
          for (const key of keys) {
            this.coerce(key, value);
          }
          return this;
        } else if (typeof keys === "object") {
          for (const key of Object.keys(keys)) {
            this.coerce(key, keys[key]);
          }
          return this;
        }
        if (!value) {
          throw new YError("coerce callback must be provided");
        }
        __classPrivateFieldGet2(this, _YargsInstance_options, "f").key[keys] = true;
        __classPrivateFieldGet2(this, _YargsInstance_globalMiddleware, "f").addCoerceMiddleware((argv, yargs) => {
          let aliases;
          const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys);
          if (!shouldCoerce) {
            return argv;
          }
          return maybeAsyncResult(() => {
            aliases = yargs.getAliases();
            return value(argv[keys]);
          }, (result) => {
            argv[keys] = result;
            const stripAliased = yargs.getInternalMethods().getParserConfiguration()["strip-aliased"];
            if (aliases[keys] && stripAliased !== true) {
              for (const alias of aliases[keys]) {
                argv[alias] = result;
              }
            }
            return argv;
          }, (err) => {
            throw new YError(err.message);
          });
        }, keys);
        return this;
      }
      conflicts(key1, key2) {
        argsert("<string|object> [string|array]", [key1, key2], arguments.length);
        __classPrivateFieldGet2(this, _YargsInstance_validation, "f").conflicts(key1, key2);
        return this;
      }
      config(key = "config", msg, parseFn) {
        argsert("[object|string] [string|function] [function]", [key, msg, parseFn], arguments.length);
        if (typeof key === "object" && !Array.isArray(key)) {
          key = applyExtends(key, __classPrivateFieldGet2(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()["deep-merge-config"] || false, __classPrivateFieldGet2(this, _YargsInstance_shim, "f"));
          __classPrivateFieldGet2(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet2(this, _YargsInstance_options, "f").configObjects || []).concat(key);
          return this;
        }
        if (typeof msg === "function") {
          parseFn = msg;
          msg = void 0;
        }
        this.describe(key, msg || __classPrivateFieldGet2(this, _YargsInstance_usage, "f").deferY18nLookup("Path to JSON config file"));
        (Array.isArray(key) ? key : [key]).forEach((k) => {
          __classPrivateFieldGet2(this, _YargsInstance_options, "f").config[k] = parseFn || true;
        });
        return this;
      }
      completion(cmd, desc, fn) {
        argsert("[string] [string|boolean|function] [function]", [cmd, desc, fn], arguments.length);
        if (typeof desc === "function") {
          fn = desc;
          desc = void 0;
        }
        __classPrivateFieldSet2(this, _YargsInstance_completionCommand, cmd || __classPrivateFieldGet2(this, _YargsInstance_completionCommand, "f") || "completion", "f");
        if (!desc && desc !== false) {
          desc = "generate completion script";
        }
        this.command(__classPrivateFieldGet2(this, _YargsInstance_completionCommand, "f"), desc);
        if (fn)
          __classPrivateFieldGet2(this, _YargsInstance_completion, "f").registerFunction(fn);
        return this;
      }
      command(cmd, description, builder, handler, middlewares, deprecated) {
        argsert("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]", [cmd, description, builder, handler, middlewares, deprecated], arguments.length);
        __classPrivateFieldGet2(this, _YargsInstance_command, "f").addHandler(cmd, description, builder, handler, middlewares, deprecated);
        return this;
      }
      commands(cmd, description, builder, handler, middlewares, deprecated) {
        return this.command(cmd, description, builder, handler, middlewares, deprecated);
      }
      commandDir(dir, opts) {
        argsert("<string> [object]", [dir, opts], arguments.length);
        const req = __classPrivateFieldGet2(this, _YargsInstance_parentRequire, "f") || __classPrivateFieldGet2(this, _YargsInstance_shim, "f").require;
        __classPrivateFieldGet2(this, _YargsInstance_command, "f").addDirectory(dir, req, __classPrivateFieldGet2(this, _YargsInstance_shim, "f").getCallerFile(), opts);
        return this;
      }
      count(keys) {
        argsert("<array|string>", [keys], arguments.length);
        this[kPopulateParserHintArray]("count", keys);
        this[kTrackManuallySetKeys](keys);
        return this;
      }
      default(key, value, defaultDescription) {
        argsert("<object|string|array> [*] [string]", [key, value, defaultDescription], arguments.length);
        if (defaultDescription) {
          assertSingleKey(key, __classPrivateFieldGet2(this, _YargsInstance_shim, "f"));
          __classPrivateFieldGet2(this, _YargsInstance_options, "f").defaultDescription[key] = defaultDescription;
        }
        if (typeof value === "function") {
          assertSingleKey(key, __classPrivateFieldGet2(this, _YargsInstance_shim, "f"));
          if (!__classPrivateFieldGet2(this, _YargsInstance_options, "f").defaultDescription[key])
            __classPrivateFieldGet2(this, _YargsInstance_options, "f").defaultDescription[key] = __classPrivateFieldGet2(this, _YargsInstance_usage, "f").functionDescription(value);
          value = value.call();
        }
        this[kPopulateParserHintSingleValueDictionary](this.default.bind(this), "default", key, value);
        return this;
      }
      defaults(key, value, defaultDescription) {
        return this.default(key, value, defaultDescription);
      }
      demandCommand(min = 1, max, minMsg, maxMsg) {
        argsert("[number] [number|string] [string|null|undefined] [string|null|undefined]", [min, max, minMsg, maxMsg], arguments.length);
        if (typeof max !== "number") {
          minMsg = max;
          max = Infinity;
        }
        this.global("_", false);
        __classPrivateFieldGet2(this, _YargsInstance_options, "f").demandedCommands._ = {
          min,
          max,
          minMsg,
          maxMsg
        };
        return this;
      }
      demand(keys, max, msg) {
        if (Array.isArray(max)) {
          max.forEach((key) => {
            assertNotStrictEqual(msg, true, __classPrivateFieldGet2(this, _YargsInstance_shim, "f"));
            this.demandOption(key, msg);
          });
          max = Infinity;
        } else if (typeof max !== "number") {
          msg = max;
          max = Infinity;
        }
        if (typeof keys === "number") {
          assertNotStrictEqual(msg, true, __classPrivateFieldGet2(this, _YargsInstance_shim, "f"));
          this.demandCommand(keys, max, msg, msg);
        } else if (Array.isArray(keys)) {
          keys.forEach((key) => {
            assertNotStrictEqual(msg, true, __classPrivateFieldGet2(this, _YargsInstance_shim, "f"));
            this.demandOption(key, msg);
          });
        } else {
          if (typeof msg === "string") {
            this.demandOption(keys, msg);
          } else if (msg === true || typeof msg === "undefined") {
            this.demandOption(keys);
          }
        }
        return this;
      }
      demandOption(keys, msg) {
        argsert("<object|string|array> [string]", [keys, msg], arguments.length);
        this[kPopulateParserHintSingleValueDictionary](this.demandOption.bind(this), "demandedOptions", keys, msg);
        return this;
      }
      deprecateOption(option, message) {
        argsert("<string> [string|boolean]", [option, message], arguments.length);
        __classPrivateFieldGet2(this, _YargsInstance_options, "f").deprecatedOptions[option] = message;
        return this;
      }
      describe(keys, description) {
        argsert("<object|string|array> [string]", [keys, description], arguments.length);
        this[kSetKey](keys, true);
        __classPrivateFieldGet2(this, _YargsInstance_usage, "f").describe(keys, description);
        return this;
      }
      detectLocale(detect) {
        argsert("<boolean>", [detect], arguments.length);
        __classPrivateFieldSet2(this, _YargsInstance_detectLocale, detect, "f");
        return this;
      }
      env(prefix) {
        argsert("[string|boolean]", [prefix], arguments.length);
        if (prefix === false)
          delete __classPrivateFieldGet2(this, _YargsInstance_options, "f").envPrefix;
        else
          __classPrivateFieldGet2(this, _YargsInstance_options, "f").envPrefix = prefix || "";
        return this;
      }
      epilogue(msg) {
        argsert("<string>", [msg], arguments.length);
        __classPrivateFieldGet2(this, _YargsInstance_usage, "f").epilog(msg);
        return this;
      }
      epilog(msg) {
        return this.epilogue(msg);
      }
      example(cmd, description) {
        argsert("<string|array> [string]", [cmd, description], arguments.length);
        if (Array.isArray(cmd)) {
          cmd.forEach((exampleParams) => this.example(...exampleParams));
        } else {
          __classPrivateFieldGet2(this, _YargsInstance_usage, "f").example(cmd, description);
        }
        return this;
      }
      exit(code, err) {
        __classPrivateFieldSet2(this, _YargsInstance_hasOutput, true, "f");
        __classPrivateFieldSet2(this, _YargsInstance_exitError, err, "f");
        if (__classPrivateFieldGet2(this, _YargsInstance_exitProcess, "f"))
          __classPrivateFieldGet2(this, _YargsInstance_shim, "f").process.exit(code);
      }
      exitProcess(enabled = true) {
        argsert("[boolean]", [enabled], arguments.length);
        __classPrivateFieldSet2(this, _YargsInstance_exitProcess, enabled, "f");
        return this;
      }
      fail(f) {
        argsert("<function|boolean>", [f], arguments.length);
        if (typeof f === "boolean" && f !== false) {
          throw new YError("Invalid first argument. Expected function or boolean 'false'");
        }
        __classPrivateFieldGet2(this, _YargsInstance_usage, "f").failFn(f);
        return this;
      }
      getAliases() {
        return this.parsed ? this.parsed.aliases : {};
      }
      async getCompletion(args2, done) {
        argsert("<array> [function]", [args2, done], arguments.length);
        if (!done) {
          return new Promise((resolve5, reject) => {
            __classPrivateFieldGet2(this, _YargsInstance_completion, "f").getCompletion(args2, (err, completions) => {
              if (err)
                reject(err);
              else
                resolve5(completions);
            });
          });
        } else {
          return __classPrivateFieldGet2(this, _YargsInstance_completion, "f").getCompletion(args2, done);
        }
      }
      getDemandedOptions() {
        argsert([], 0);
        return __classPrivateFieldGet2(this, _YargsInstance_options, "f").demandedOptions;
      }
      getDemandedCommands() {
        argsert([], 0);
        return __classPrivateFieldGet2(this, _YargsInstance_options, "f").demandedCommands;
      }
      getDeprecatedOptions() {
        argsert([], 0);
        return __classPrivateFieldGet2(this, _YargsInstance_options, "f").deprecatedOptions;
      }
      getDetectLocale() {
        return __classPrivateFieldGet2(this, _YargsInstance_detectLocale, "f");
      }
      getExitProcess() {
        return __classPrivateFieldGet2(this, _YargsInstance_exitProcess, "f");
      }
      getGroups() {
        return Object.assign({}, __classPrivateFieldGet2(this, _YargsInstance_groups, "f"), __classPrivateFieldGet2(this, _YargsInstance_preservedGroups, "f"));
      }
      getHelp() {
        __classPrivateFieldSet2(this, _YargsInstance_hasOutput, true, "f");
        if (!__classPrivateFieldGet2(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) {
          if (!this.parsed) {
            const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet2(this, _YargsInstance_processArgs, "f"), void 0, void 0, 0, true);
            if (isPromise(parse)) {
              return parse.then(() => {
                return __classPrivateFieldGet2(this, _YargsInstance_usage, "f").help();
              });
            }
          }
          const builderResponse = __classPrivateFieldGet2(this, _YargsInstance_command, "f").runDefaultBuilderOn(this);
          if (isPromise(builderResponse)) {
            return builderResponse.then(() => {
              return __classPrivateFieldGet2(this, _YargsInstance_usage, "f").help();
            });
          }
        }
        return Promise.resolve(__classPrivateFieldGet2(this, _YargsInstance_usage, "f").help());
      }
      getOptions() {
        return __classPrivateFieldGet2(this, _YargsInstance_options, "f");
      }
      getStrict() {
        return __classPrivateFieldGet2(this, _YargsInstance_strict, "f");
      }
      getStrictCommands() {
        return __classPrivateFieldGet2(this, _YargsInstance_strictCommands, "f");
      }
      getStrictOptions() {
        return __classPrivateFieldGet2(this, _YargsInstance_strictOptions, "f");
      }
      global(globals, global2) {
        argsert("<string|array> [boolean]", [globals, global2], arguments.length);
        globals = [].concat(globals);
        if (global2 !== false) {
          __classPrivateFieldGet2(this, _YargsInstance_options, "f").local = __classPrivateFieldGet2(this, _YargsInstance_options, "f").local.filter((l) => globals.indexOf(l) === -1);
        } else {
          globals.forEach((g) => {
            if (!__classPrivateFieldGet2(this, _YargsInstance_options, "f").local.includes(g))
              __classPrivateFieldGet2(this, _YargsInstance_options, "f").local.push(g);
          });
        }
        return this;
      }
      group(opts, groupName) {
        argsert("<string|array> <string>", [opts, groupName], arguments.length);
        const existing = __classPrivateFieldGet2(this, _YargsInstance_preservedGroups, "f")[groupName] || __classPrivateFieldGet2(this, _YargsInstance_groups, "f")[groupName];
        if (__classPrivateFieldGet2(this, _YargsInstance_preservedGroups, "f")[groupName]) {
          delete __classPrivateFieldGet2(this, _YargsInstance_preservedGroups, "f")[groupName];
        }
        const seen = {};
        __classPrivateFieldGet2(this, _YargsInstance_groups, "f")[groupName] = (existing || []).concat(opts).filter((key) => {
          if (seen[key])
            return false;
          return seen[key] = true;
        });
        return this;
      }
      hide(key) {
        argsert("<string>", [key], arguments.length);
        __classPrivateFieldGet2(this, _YargsInstance_options, "f").hiddenOptions.push(key);
        return this;
      }
      implies(key, value) {
        argsert("<string|object> [number|string|array]", [key, value], arguments.length);
        __classPrivateFieldGet2(this, _YargsInstance_validation, "f").implies(key, value);
        return this;
      }
      locale(locale) {
        argsert("[string]", [locale], arguments.length);
        if (locale === void 0) {
          this[kGuessLocale]();
          return __classPrivateFieldGet2(this, _YargsInstance_shim, "f").y18n.getLocale();
        }
        __classPrivateFieldSet2(this, _YargsInstance_detectLocale, false, "f");
        __classPrivateFieldGet2(this, _YargsInstance_shim, "f").y18n.setLocale(locale);
        return this;
      }
      middleware(callback, applyBeforeValidation, global2) {
        return __classPrivateFieldGet2(this, _YargsInstance_globalMiddleware, "f").addMiddleware(callback, !!applyBeforeValidation, global2);
      }
      nargs(key, value) {
        argsert("<string|object|array> [number]", [key, value], arguments.length);
        this[kPopulateParserHintSingleValueDictionary](this.nargs.bind(this), "narg", key, value);
        return this;
      }
      normalize(keys) {
        argsert("<array|string>", [keys], arguments.length);
        this[kPopulateParserHintArray]("normalize", keys);
        return this;
      }
      number(keys) {
        argsert("<array|string>", [keys], arguments.length);
        this[kPopulateParserHintArray]("number", keys);
        this[kTrackManuallySetKeys](keys);
        return this;
      }
      option(key, opt) {
        argsert("<string|object> [object]", [key, opt], arguments.length);
        if (typeof key === "object") {
          Object.keys(key).forEach((k) => {
            this.options(k, key[k]);
          });
        } else {
          if (typeof opt !== "object") {
            opt = {};
          }
          this[kTrackManuallySetKeys](key);
          if (__classPrivateFieldGet2(this, _YargsInstance_versionOpt, "f") && (key === "version" || (opt === null || opt === void 0 ? void 0 : opt.alias) === "version")) {
            this[kEmitWarning]([
              '"version" is a reserved word.',
              "Please do one of the following:",
              '- Disable version with `yargs.version(false)` if using "version" as an option',
              "- Use the built-in `yargs.version` method instead (if applicable)",
              "- Use a different option key",
              "https://yargs.js.org/docs/#api-reference-version"
            ].join("\n"), void 0, "versionWarning");
          }
          __classPrivateFieldGet2(this, _YargsInstance_options, "f").key[key] = true;
          if (opt.alias)
            this.alias(key, opt.alias);
          const deprecate = opt.deprecate || opt.deprecated;
          if (deprecate) {
            this.deprecateOption(key, deprecate);
          }
          const demand = opt.demand || opt.required || opt.require;
          if (demand) {
            this.demand(key, demand);
          }
          if (opt.demandOption) {
            this.demandOption(key, typeof opt.demandOption === "string" ? opt.demandOption : void 0);
          }
          if (opt.conflicts) {
            this.conflicts(key, opt.conflicts);
          }
          if ("default" in opt) {
            this.default(key, opt.default);
          }
          if (opt.implies !== void 0) {
            this.implies(key, opt.implies);
          }
          if (opt.nargs !== void 0) {
            this.nargs(key, opt.nargs);
          }
          if (opt.config) {
            this.config(key, opt.configParser);
          }
          if (opt.normalize) {
            this.normalize(key);
          }
          if (opt.choices) {
            this.choices(key, opt.choices);
          }
          if (opt.coerce) {
            this.coerce(key, opt.coerce);
          }
          if (opt.group) {
            this.group(key, opt.group);
          }
          if (opt.boolean || opt.type === "boolean") {
            this.boolean(key);
            if (opt.alias)
              this.boolean(opt.alias);
          }
          if (opt.array || opt.type === "array") {
            this.array(key);
            if (opt.alias)
              this.array(opt.alias);
          }
          if (opt.number || opt.type === "number") {
            this.number(key);
            if (opt.alias)
              this.number(opt.alias);
          }
          if (opt.string || opt.type === "string") {
            this.string(key);
            if (opt.alias)
              this.string(opt.alias);
          }
          if (opt.count || opt.type === "count") {
            this.count(key);
          }
          if (typeof opt.global === "boolean") {
            this.global(key, opt.global);
          }
          if (opt.defaultDescription) {
            __classPrivateFieldGet2(this, _YargsInstance_options, "f").defaultDescription[key] = opt.defaultDescription;
          }
          if (opt.skipValidation) {
            this.skipValidation(key);
          }
          const desc = opt.describe || opt.description || opt.desc;
          const descriptions = __classPrivateFieldGet2(this, _YargsInstance_usage, "f").getDescriptions();
          if (!Object.prototype.hasOwnProperty.call(descriptions, key) || typeof desc === "string") {
            this.describe(key, desc);
          }
          if (opt.hidden) {
            this.hide(key);
          }
          if (opt.requiresArg) {
            this.requiresArg(key);
          }
        }
        return this;
      }
      options(key, opt) {
        return this.option(key, opt);
      }
      parse(args2, shortCircuit, _parseFn) {
        argsert("[string|array] [function|boolean|object] [function]", [args2, shortCircuit, _parseFn], arguments.length);
        this[kFreeze]();
        if (typeof args2 === "undefined") {
          args2 = __classPrivateFieldGet2(this, _YargsInstance_processArgs, "f");
        }
        if (typeof shortCircuit === "object") {
          __classPrivateFieldSet2(this, _YargsInstance_parseContext, shortCircuit, "f");
          shortCircuit = _parseFn;
        }
        if (typeof shortCircuit === "function") {
          __classPrivateFieldSet2(this, _YargsInstance_parseFn, shortCircuit, "f");
          shortCircuit = false;
        }
        if (!shortCircuit)
          __classPrivateFieldSet2(this, _YargsInstance_processArgs, args2, "f");
        if (__classPrivateFieldGet2(this, _YargsInstance_parseFn, "f"))
          __classPrivateFieldSet2(this, _YargsInstance_exitProcess, false, "f");
        const parsed = this[kRunYargsParserAndExecuteCommands](args2, !!shortCircuit);
        const tmpParsed = this.parsed;
        __classPrivateFieldGet2(this, _YargsInstance_completion, "f").setParsed(this.parsed);
        if (isPromise(parsed)) {
          return parsed.then((argv) => {
            if (__classPrivateFieldGet2(this, _YargsInstance_parseFn, "f"))
              __classPrivateFieldGet2(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet2(this, _YargsInstance_exitError, "f"), argv, __classPrivateFieldGet2(this, _YargsInstance_output, "f"));
            return argv;
          }).catch((err) => {
            if (__classPrivateFieldGet2(this, _YargsInstance_parseFn, "f")) {
              __classPrivateFieldGet2(this, _YargsInstance_parseFn, "f")(err, this.parsed.argv, __classPrivateFieldGet2(this, _YargsInstance_output, "f"));
            }
            throw err;
          }).finally(() => {
            this[kUnfreeze]();
            this.parsed = tmpParsed;
          });
        } else {
          if (__classPrivateFieldGet2(this, _YargsInstance_parseFn, "f"))
            __classPrivateFieldGet2(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet2(this, _YargsInstance_exitError, "f"), parsed, __classPrivateFieldGet2(this, _YargsInstance_output, "f"));
          this[kUnfreeze]();
          this.parsed = tmpParsed;
        }
        return parsed;
      }
      parseAsync(args2, shortCircuit, _parseFn) {
        const maybePromise = this.parse(args2, shortCircuit, _parseFn);
        return !isPromise(maybePromise) ? Promise.resolve(maybePromise) : maybePromise;
      }
      parseSync(args2, shortCircuit, _parseFn) {
        const maybePromise = this.parse(args2, shortCircuit, _parseFn);
        if (isPromise(maybePromise)) {
          throw new YError(".parseSync() must not be used with asynchronous builders, handlers, or middleware");
        }
        return maybePromise;
      }
      parserConfiguration(config2) {
        argsert("<object>", [config2], arguments.length);
        __classPrivateFieldSet2(this, _YargsInstance_parserConfig, config2, "f");
        return this;
      }
      pkgConf(key, rootPath) {
        argsert("<string> [string]", [key, rootPath], arguments.length);
        let conf = null;
        const obj = this[kPkgUp](rootPath || __classPrivateFieldGet2(this, _YargsInstance_cwd, "f"));
        if (obj[key] && typeof obj[key] === "object") {
          conf = applyExtends(obj[key], rootPath || __classPrivateFieldGet2(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()["deep-merge-config"] || false, __classPrivateFieldGet2(this, _YargsInstance_shim, "f"));
          __classPrivateFieldGet2(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet2(this, _YargsInstance_options, "f").configObjects || []).concat(conf);
        }
        return this;
      }
      positional(key, opts) {
        argsert("<string> <object>", [key, opts], arguments.length);
        const supportedOpts = [
          "default",
          "defaultDescription",
          "implies",
          "normalize",
          "choices",
          "conflicts",
          "coerce",
          "type",
          "describe",
          "desc",
          "description",
          "alias"
        ];
        opts = objFilter(opts, (k, v) => {
          if (k === "type" && !["string", "number", "boolean"].includes(v))
            return false;
          return supportedOpts.includes(k);
        });
        const fullCommand = __classPrivateFieldGet2(this, _YargsInstance_context, "f").fullCommands[__classPrivateFieldGet2(this, _YargsInstance_context, "f").fullCommands.length - 1];
        const parseOptions = fullCommand ? __classPrivateFieldGet2(this, _YargsInstance_command, "f").cmdToParseOptions(fullCommand) : {
          array: [],
          alias: {},
          default: {},
          demand: {}
        };
        objectKeys(parseOptions).forEach((pk) => {
          const parseOption = parseOptions[pk];
          if (Array.isArray(parseOption)) {
            if (parseOption.indexOf(key) !== -1)
              opts[pk] = true;
          } else {
            if (parseOption[key] && !(pk in opts))
              opts[pk] = parseOption[key];
          }
        });
        this.group(key, __classPrivateFieldGet2(this, _YargsInstance_usage, "f").getPositionalGroupName());
        return this.option(key, opts);
      }
      recommendCommands(recommend = true) {
        argsert("[boolean]", [recommend], arguments.length);
        __classPrivateFieldSet2(this, _YargsInstance_recommendCommands, recommend, "f");
        return this;
      }
      required(keys, max, msg) {
        return this.demand(keys, max, msg);
      }
      require(keys, max, msg) {
        return this.demand(keys, max, msg);
      }
      requiresArg(keys) {
        argsert("<array|string|object> [number]", [keys], arguments.length);
        if (typeof keys === "string" && __classPrivateFieldGet2(this, _YargsInstance_options, "f").narg[keys]) {
          return this;
        } else {
          this[kPopulateParserHintSingleValueDictionary](this.requiresArg.bind(this), "narg", keys, NaN);
        }
        return this;
      }
      showCompletionScript($0, cmd) {
        argsert("[string] [string]", [$0, cmd], arguments.length);
        $0 = $0 || this.$0;
        __classPrivateFieldGet2(this, _YargsInstance_logger, "f").log(__classPrivateFieldGet2(this, _YargsInstance_completion, "f").generateCompletionScript($0, cmd || __classPrivateFieldGet2(this, _YargsInstance_completionCommand, "f") || "completion"));
        return this;
      }
      showHelp(level) {
        argsert("[string|function]", [level], arguments.length);
        __classPrivateFieldSet2(this, _YargsInstance_hasOutput, true, "f");
        if (!__classPrivateFieldGet2(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) {
          if (!this.parsed) {
            const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet2(this, _YargsInstance_processArgs, "f"), void 0, void 0, 0, true);
            if (isPromise(parse)) {
              parse.then(() => {
                __classPrivateFieldGet2(this, _YargsInstance_usage, "f").showHelp(level);
              });
              return this;
            }
          }
          const builderResponse = __classPrivateFieldGet2(this, _YargsInstance_command, "f").runDefaultBuilderOn(this);
          if (isPromise(builderResponse)) {
            builderResponse.then(() => {
              __classPrivateFieldGet2(this, _YargsInstance_usage, "f").showHelp(level);
            });
            return this;
          }
        }
        __classPrivateFieldGet2(this, _YargsInstance_usage, "f").showHelp(level);
        return this;
      }
      scriptName(scriptName) {
        this.customScriptName = true;
        this.$0 = scriptName;
        return this;
      }
      showHelpOnFail(enabled, message) {
        argsert("[boolean|string] [string]", [enabled, message], arguments.length);
        __classPrivateFieldGet2(this, _YargsInstance_usage, "f").showHelpOnFail(enabled, message);
        return this;
      }
      showVersion(level) {
        argsert("[string|function]", [level], arguments.length);
        __classPrivateFieldGet2(this, _YargsInstance_usage, "f").showVersion(level);
        return this;
      }
      skipValidation(keys) {
        argsert("<array|string>", [keys], arguments.length);
        this[kPopulateParserHintArray]("skipValidation", keys);
        return this;
      }
      strict(enabled) {
        argsert("[boolean]", [enabled], arguments.length);
        __classPrivateFieldSet2(this, _YargsInstance_strict, enabled !== false, "f");
        return this;
      }
      strictCommands(enabled) {
        argsert("[boolean]", [enabled], arguments.length);
        __classPrivateFieldSet2(this, _YargsInstance_strictCommands, enabled !== false, "f");
        return this;
      }
      strictOptions(enabled) {
        argsert("[boolean]", [enabled], arguments.length);
        __classPrivateFieldSet2(this, _YargsInstance_strictOptions, enabled !== false, "f");
        return this;
      }
      string(keys) {
        argsert("<array|string>", [keys], arguments.length);
        this[kPopulateParserHintArray]("string", keys);
        this[kTrackManuallySetKeys](keys);
        return this;
      }
      terminalWidth() {
        argsert([], 0);
        return __classPrivateFieldGet2(this, _YargsInstance_shim, "f").process.stdColumns;
      }
      updateLocale(obj) {
        return this.updateStrings(obj);
      }
      updateStrings(obj) {
        argsert("<object>", [obj], arguments.length);
        __classPrivateFieldSet2(this, _YargsInstance_detectLocale, false, "f");
        __classPrivateFieldGet2(this, _YargsInstance_shim, "f").y18n.updateLocale(obj);
        return this;
      }
      usage(msg, description, builder, handler) {
        argsert("<string|null|undefined> [string|boolean] [function|object] [function]", [msg, description, builder, handler], arguments.length);
        if (description !== void 0) {
          assertNotStrictEqual(msg, null, __classPrivateFieldGet2(this, _YargsInstance_shim, "f"));
          if ((msg || "").match(/^\$0( |$)/)) {
            return this.command(msg, description, builder, handler);
          } else {
            throw new YError(".usage() description must start with $0 if being used as alias for .command()");
          }
        } else {
          __classPrivateFieldGet2(this, _YargsInstance_usage, "f").usage(msg);
          return this;
        }
      }
      usageConfiguration(config2) {
        argsert("<object>", [config2], arguments.length);
        __classPrivateFieldSet2(this, _YargsInstance_usageConfig, config2, "f");
        return this;
      }
      version(opt, msg, ver) {
        const defaultVersionOpt = "version";
        argsert("[boolean|string] [string] [string]", [opt, msg, ver], arguments.length);
        if (__classPrivateFieldGet2(this, _YargsInstance_versionOpt, "f")) {
          this[kDeleteFromParserHintObject](__classPrivateFieldGet2(this, _YargsInstance_versionOpt, "f"));
          __classPrivateFieldGet2(this, _YargsInstance_usage, "f").version(void 0);
          __classPrivateFieldSet2(this, _YargsInstance_versionOpt, null, "f");
        }
        if (arguments.length === 0) {
          ver = this[kGuessVersion]();
          opt = defaultVersionOpt;
        } else if (arguments.length === 1) {
          if (opt === false) {
            return this;
          }
          ver = opt;
          opt = defaultVersionOpt;
        } else if (arguments.length === 2) {
          ver = msg;
          msg = void 0;
        }
        __classPrivateFieldSet2(this, _YargsInstance_versionOpt, typeof opt === "string" ? opt : defaultVersionOpt, "f");
        msg = msg || __classPrivateFieldGet2(this, _YargsInstance_usage, "f").deferY18nLookup("Show version number");
        __classPrivateFieldGet2(this, _YargsInstance_usage, "f").version(ver || void 0);
        this.boolean(__classPrivateFieldGet2(this, _YargsInstance_versionOpt, "f"));
        this.describe(__classPrivateFieldGet2(this, _YargsInstance_versionOpt, "f"), msg);
        return this;
      }
      wrap(cols) {
        argsert("<number|null|undefined>", [cols], arguments.length);
        __classPrivateFieldGet2(this, _YargsInstance_usage, "f").wrap(cols);
        return this;
      }
      [(_YargsInstance_command = /* @__PURE__ */ new WeakMap(), _YargsInstance_cwd = /* @__PURE__ */ new WeakMap(), _YargsInstance_context = /* @__PURE__ */ new WeakMap(), _YargsInstance_completion = /* @__PURE__ */ new WeakMap(), _YargsInstance_completionCommand = /* @__PURE__ */ new WeakMap(), _YargsInstance_defaultShowHiddenOpt = /* @__PURE__ */ new WeakMap(), _YargsInstance_exitError = /* @__PURE__ */ new WeakMap(), _YargsInstance_detectLocale = /* @__PURE__ */ new WeakMap(), _YargsInstance_emittedWarnings = /* @__PURE__ */ new WeakMap(), _YargsInstance_exitProcess = /* @__PURE__ */ new WeakMap(), _YargsInstance_frozens = /* @__PURE__ */ new WeakMap(), _YargsInstance_globalMiddleware = /* @__PURE__ */ new WeakMap(), _YargsInstance_groups = /* @__PURE__ */ new WeakMap(), _YargsInstance_hasOutput = /* @__PURE__ */ new WeakMap(), _YargsInstance_helpOpt = /* @__PURE__ */ new WeakMap(), _YargsInstance_isGlobalContext = /* @__PURE__ */ new WeakMap(), _YargsInstance_logger = /* @__PURE__ */ new WeakMap(), _YargsInstance_output = /* @__PURE__ */ new WeakMap(), _YargsInstance_options = /* @__PURE__ */ new WeakMap(), _YargsInstance_parentRequire = /* @__PURE__ */ new WeakMap(), _YargsInstance_parserConfig = /* @__PURE__ */ new WeakMap(), _YargsInstance_parseFn = /* @__PURE__ */ new WeakMap(), _YargsInstance_parseContext = /* @__PURE__ */ new WeakMap(), _YargsInstance_pkgs = /* @__PURE__ */ new WeakMap(), _YargsInstance_preservedGroups = /* @__PURE__ */ new WeakMap(), _YargsInstance_processArgs = /* @__PURE__ */ new WeakMap(), _YargsInstance_recommendCommands = /* @__PURE__ */ new WeakMap(), _YargsInstance_shim = /* @__PURE__ */ new WeakMap(), _YargsInstance_strict = /* @__PURE__ */ new WeakMap(), _YargsInstance_strictCommands = /* @__PURE__ */ new WeakMap(), _YargsInstance_strictOptions = /* @__PURE__ */ new WeakMap(), _YargsInstance_usage = /* @__PURE__ */ new WeakMap(), _YargsInstance_usageConfig = /* @__PURE__ */ new WeakMap(), _YargsInstance_versionOpt = /* @__PURE__ */ new WeakMap(), _YargsInstance_validation = /* @__PURE__ */ new WeakMap(), kCopyDoubleDash)](argv) {
        if (!argv._ || !argv["--"])
          return argv;
        argv._.push.apply(argv._, argv["--"]);
        try {
          delete argv["--"];
        } catch (_err) {
        }
        return argv;
      }
      [kCreateLogger]() {
        return {
          log: (...args2) => {
            if (!this[kHasParseCallback]())
              console.log(...args2);
            __classPrivateFieldSet2(this, _YargsInstance_hasOutput, true, "f");
            if (__classPrivateFieldGet2(this, _YargsInstance_output, "f").length)
              __classPrivateFieldSet2(this, _YargsInstance_output, __classPrivateFieldGet2(this, _YargsInstance_output, "f") + "\n", "f");
            __classPrivateFieldSet2(this, _YargsInstance_output, __classPrivateFieldGet2(this, _YargsInstance_output, "f") + args2.join(" "), "f");
          },
          error: (...args2) => {
            if (!this[kHasParseCallback]())
              console.error(...args2);
            __classPrivateFieldSet2(this, _YargsInstance_hasOutput, true, "f");
            if (__classPrivateFieldGet2(this, _YargsInstance_output, "f").length)
              __classPrivateFieldSet2(this, _YargsInstance_output, __classPrivateFieldGet2(this, _YargsInstance_output, "f") + "\n", "f");
            __classPrivateFieldSet2(this, _YargsInstance_output, __classPrivateFieldGet2(this, _YargsInstance_output, "f") + args2.join(" "), "f");
          }
        };
      }
      [kDeleteFromParserHintObject](optionKey) {
        objectKeys(__classPrivateFieldGet2(this, _YargsInstance_options, "f")).forEach((hintKey) => {
          if (/* @__PURE__ */ ((key) => key === "configObjects")(hintKey))
            return;
          const hint = __classPrivateFieldGet2(this, _YargsInstance_options, "f")[hintKey];
          if (Array.isArray(hint)) {
            if (hint.includes(optionKey))
              hint.splice(hint.indexOf(optionKey), 1);
          } else if (typeof hint === "object") {
            delete hint[optionKey];
          }
        });
        delete __classPrivateFieldGet2(this, _YargsInstance_usage, "f").getDescriptions()[optionKey];
      }
      [kEmitWarning](warning, type, deduplicationId) {
        if (!__classPrivateFieldGet2(this, _YargsInstance_emittedWarnings, "f")[deduplicationId]) {
          __classPrivateFieldGet2(this, _YargsInstance_shim, "f").process.emitWarning(warning, type);
          __classPrivateFieldGet2(this, _YargsInstance_emittedWarnings, "f")[deduplicationId] = true;
        }
      }
      [kFreeze]() {
        __classPrivateFieldGet2(this, _YargsInstance_frozens, "f").push({
          options: __classPrivateFieldGet2(this, _YargsInstance_options, "f"),
          configObjects: __classPrivateFieldGet2(this, _YargsInstance_options, "f").configObjects.slice(0),
          exitProcess: __classPrivateFieldGet2(this, _YargsInstance_exitProcess, "f"),
          groups: __classPrivateFieldGet2(this, _YargsInstance_groups, "f"),
          strict: __classPrivateFieldGet2(this, _YargsInstance_strict, "f"),
          strictCommands: __classPrivateFieldGet2(this, _YargsInstance_strictCommands, "f"),
          strictOptions: __classPrivateFieldGet2(this, _YargsInstance_strictOptions, "f"),
          completionCommand: __classPrivateFieldGet2(this, _YargsInstance_completionCommand, "f"),
          output: __classPrivateFieldGet2(this, _YargsInstance_output, "f"),
          exitError: __classPrivateFieldGet2(this, _YargsInstance_exitError, "f"),
          hasOutput: __classPrivateFieldGet2(this, _YargsInstance_hasOutput, "f"),
          parsed: this.parsed,
          parseFn: __classPrivateFieldGet2(this, _YargsInstance_parseFn, "f"),
          parseContext: __classPrivateFieldGet2(this, _YargsInstance_parseContext, "f")
        });
        __classPrivateFieldGet2(this, _YargsInstance_usage, "f").freeze();
        __classPrivateFieldGet2(this, _YargsInstance_validation, "f").freeze();
        __classPrivateFieldGet2(this, _YargsInstance_command, "f").freeze();
        __classPrivateFieldGet2(this, _YargsInstance_globalMiddleware, "f").freeze();
      }
      [kGetDollarZero]() {
        let $0 = "";
        let default$0;
        if (/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet2(this, _YargsInstance_shim, "f").process.argv()[0])) {
          default$0 = __classPrivateFieldGet2(this, _YargsInstance_shim, "f").process.argv().slice(1, 2);
        } else {
          default$0 = __classPrivateFieldGet2(this, _YargsInstance_shim, "f").process.argv().slice(0, 1);
        }
        $0 = default$0.map((x) => {
          const b = this[kRebase](__classPrivateFieldGet2(this, _YargsInstance_cwd, "f"), x);
          return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
        }).join(" ").trim();
        if (__classPrivateFieldGet2(this, _YargsInstance_shim, "f").getEnv("_") && __classPrivateFieldGet2(this, _YargsInstance_shim, "f").getProcessArgvBin() === __classPrivateFieldGet2(this, _YargsInstance_shim, "f").getEnv("_")) {
          $0 = __classPrivateFieldGet2(this, _YargsInstance_shim, "f").getEnv("_").replace(`${__classPrivateFieldGet2(this, _YargsInstance_shim, "f").path.dirname(__classPrivateFieldGet2(this, _YargsInstance_shim, "f").process.execPath())}/`, "");
        }
        return $0;
      }
      [kGetParserConfiguration]() {
        return __classPrivateFieldGet2(this, _YargsInstance_parserConfig, "f");
      }
      [kGetUsageConfiguration]() {
        return __classPrivateFieldGet2(this, _YargsInstance_usageConfig, "f");
      }
      [kGuessLocale]() {
        if (!__classPrivateFieldGet2(this, _YargsInstance_detectLocale, "f"))
          return;
        const locale = __classPrivateFieldGet2(this, _YargsInstance_shim, "f").getEnv("LC_ALL") || __classPrivateFieldGet2(this, _YargsInstance_shim, "f").getEnv("LC_MESSAGES") || __classPrivateFieldGet2(this, _YargsInstance_shim, "f").getEnv("LANG") || __classPrivateFieldGet2(this, _YargsInstance_shim, "f").getEnv("LANGUAGE") || "en_US";
        this.locale(locale.replace(/[.:].*/, ""));
      }
      [kGuessVersion]() {
        const obj = this[kPkgUp]();
        return obj.version || "unknown";
      }
      [kParsePositionalNumbers](argv) {
        const args2 = argv["--"] ? argv["--"] : argv._;
        for (let i = 0, arg; (arg = args2[i]) !== void 0; i++) {
          if (__classPrivateFieldGet2(this, _YargsInstance_shim, "f").Parser.looksLikeNumber(arg) && Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) {
            args2[i] = Number(arg);
          }
        }
        return argv;
      }
      [kPkgUp](rootPath) {
        const npath = rootPath || "*";
        if (__classPrivateFieldGet2(this, _YargsInstance_pkgs, "f")[npath])
          return __classPrivateFieldGet2(this, _YargsInstance_pkgs, "f")[npath];
        let obj = {};
        try {
          let startDir = rootPath || __classPrivateFieldGet2(this, _YargsInstance_shim, "f").mainFilename;
          if (!rootPath && __classPrivateFieldGet2(this, _YargsInstance_shim, "f").path.extname(startDir)) {
            startDir = __classPrivateFieldGet2(this, _YargsInstance_shim, "f").path.dirname(startDir);
          }
          const pkgJsonPath = __classPrivateFieldGet2(this, _YargsInstance_shim, "f").findUp(startDir, (dir, names) => {
            if (names.includes("package.json")) {
              return "package.json";
            } else {
              return void 0;
            }
          });
          assertNotStrictEqual(pkgJsonPath, void 0, __classPrivateFieldGet2(this, _YargsInstance_shim, "f"));
          obj = JSON.parse(__classPrivateFieldGet2(this, _YargsInstance_shim, "f").readFileSync(pkgJsonPath, "utf8"));
        } catch (_noop) {
        }
        __classPrivateFieldGet2(this, _YargsInstance_pkgs, "f")[npath] = obj || {};
        return __classPrivateFieldGet2(this, _YargsInstance_pkgs, "f")[npath];
      }
      [kPopulateParserHintArray](type, keys) {
        keys = [].concat(keys);
        keys.forEach((key) => {
          key = this[kSanitizeKey](key);
          __classPrivateFieldGet2(this, _YargsInstance_options, "f")[type].push(key);
        });
      }
      [kPopulateParserHintSingleValueDictionary](builder, type, key, value) {
        this[kPopulateParserHintDictionary](builder, type, key, value, (type2, key2, value2) => {
          __classPrivateFieldGet2(this, _YargsInstance_options, "f")[type2][key2] = value2;
        });
      }
      [kPopulateParserHintArrayDictionary](builder, type, key, value) {
        this[kPopulateParserHintDictionary](builder, type, key, value, (type2, key2, value2) => {
          __classPrivateFieldGet2(this, _YargsInstance_options, "f")[type2][key2] = (__classPrivateFieldGet2(this, _YargsInstance_options, "f")[type2][key2] || []).concat(value2);
        });
      }
      [kPopulateParserHintDictionary](builder, type, key, value, singleKeyHandler) {
        if (Array.isArray(key)) {
          key.forEach((k) => {
            builder(k, value);
          });
        } else if (/* @__PURE__ */ ((key2) => typeof key2 === "object")(key)) {
          for (const k of objectKeys(key)) {
            builder(k, key[k]);
          }
        } else {
          singleKeyHandler(type, this[kSanitizeKey](key), value);
        }
      }
      [kSanitizeKey](key) {
        if (key === "__proto__")
          return "___proto___";
        return key;
      }
      [kSetKey](key, set) {
        this[kPopulateParserHintSingleValueDictionary](this[kSetKey].bind(this), "key", key, set);
        return this;
      }
      [kUnfreeze]() {
        var _a2, _b2, _c2, _d, _e, _f, _g, _h, _j, _k, _l, _m;
        const frozen = __classPrivateFieldGet2(this, _YargsInstance_frozens, "f").pop();
        assertNotStrictEqual(frozen, void 0, __classPrivateFieldGet2(this, _YargsInstance_shim, "f"));
        let configObjects;
        _a2 = this, _b2 = this, _c2 = this, _d = this, _e = this, _f = this, _g = this, _h = this, _j = this, _k = this, _l = this, _m = this, {
          options: { set value(_o) {
            __classPrivateFieldSet2(_a2, _YargsInstance_options, _o, "f");
          } }.value,
          configObjects,
          exitProcess: { set value(_o) {
            __classPrivateFieldSet2(_b2, _YargsInstance_exitProcess, _o, "f");
          } }.value,
          groups: { set value(_o) {
            __classPrivateFieldSet2(_c2, _YargsInstance_groups, _o, "f");
          } }.value,
          output: { set value(_o) {
            __classPrivateFieldSet2(_d, _YargsInstance_output, _o, "f");
          } }.value,
          exitError: { set value(_o) {
            __classPrivateFieldSet2(_e, _YargsInstance_exitError, _o, "f");
          } }.value,
          hasOutput: { set value(_o) {
            __classPrivateFieldSet2(_f, _YargsInstance_hasOutput, _o, "f");
          } }.value,
          parsed: this.parsed,
          strict: { set value(_o) {
            __classPrivateFieldSet2(_g, _YargsInstance_strict, _o, "f");
          } }.value,
          strictCommands: { set value(_o) {
            __classPrivateFieldSet2(_h, _YargsInstance_strictCommands, _o, "f");
          } }.value,
          strictOptions: { set value(_o) {
            __classPrivateFieldSet2(_j, _YargsInstance_strictOptions, _o, "f");
          } }.value,
          completionCommand: { set value(_o) {
            __classPrivateFieldSet2(_k, _YargsInstance_completionCommand, _o, "f");
          } }.value,
          parseFn: { set value(_o) {
            __classPrivateFieldSet2(_l, _YargsInstance_parseFn, _o, "f");
          } }.value,
          parseContext: { set value(_o) {
            __classPrivateFieldSet2(_m, _YargsInstance_parseContext, _o, "f");
          } }.value
        } = frozen;
        __classPrivateFieldGet2(this, _YargsInstance_options, "f").configObjects = configObjects;
        __classPrivateFieldGet2(this, _YargsInstance_usage, "f").unfreeze();
        __classPrivateFieldGet2(this, _YargsInstance_validation, "f").unfreeze();
        __classPrivateFieldGet2(this, _YargsInstance_command, "f").unfreeze();
        __classPrivateFieldGet2(this, _YargsInstance_globalMiddleware, "f").unfreeze();
      }
      [kValidateAsync](validation2, argv) {
        return maybeAsyncResult(argv, (result) => {
          validation2(result);
          return result;
        });
      }
      getInternalMethods() {
        return {
          getCommandInstance: this[kGetCommandInstance].bind(this),
          getContext: this[kGetContext].bind(this),
          getHasOutput: this[kGetHasOutput].bind(this),
          getLoggerInstance: this[kGetLoggerInstance].bind(this),
          getParseContext: this[kGetParseContext].bind(this),
          getParserConfiguration: this[kGetParserConfiguration].bind(this),
          getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
          getUsageInstance: this[kGetUsageInstance].bind(this),
          getValidationInstance: this[kGetValidationInstance].bind(this),
          hasParseCallback: this[kHasParseCallback].bind(this),
          isGlobalContext: this[kIsGlobalContext].bind(this),
          postProcess: this[kPostProcess].bind(this),
          reset: this[kReset].bind(this),
          runValidation: this[kRunValidation].bind(this),
          runYargsParserAndExecuteCommands: this[kRunYargsParserAndExecuteCommands].bind(this),
          setHasOutput: this[kSetHasOutput].bind(this)
        };
      }
      [kGetCommandInstance]() {
        return __classPrivateFieldGet2(this, _YargsInstance_command, "f");
      }
      [kGetContext]() {
        return __classPrivateFieldGet2(this, _YargsInstance_context, "f");
      }
      [kGetHasOutput]() {
        return __classPrivateFieldGet2(this, _YargsInstance_hasOutput, "f");
      }
      [kGetLoggerInstance]() {
        return __classPrivateFieldGet2(this, _YargsInstance_logger, "f");
      }
      [kGetParseContext]() {
        return __classPrivateFieldGet2(this, _YargsInstance_parseContext, "f") || {};
      }
      [kGetUsageInstance]() {
        return __classPrivateFieldGet2(this, _YargsInstance_usage, "f");
      }
      [kGetValidationInstance]() {
        return __classPrivateFieldGet2(this, _YargsInstance_validation, "f");
      }
      [kHasParseCallback]() {
        return !!__classPrivateFieldGet2(this, _YargsInstance_parseFn, "f");
      }
      [kIsGlobalContext]() {
        return __classPrivateFieldGet2(this, _YargsInstance_isGlobalContext, "f");
      }
      [kPostProcess](argv, populateDoubleDash, calledFromCommand, runGlobalMiddleware) {
        if (calledFromCommand)
          return argv;
        if (isPromise(argv))
          return argv;
        if (!populateDoubleDash) {
          argv = this[kCopyDoubleDash](argv);
        }
        const parsePositionalNumbers = this[kGetParserConfiguration]()["parse-positional-numbers"] || this[kGetParserConfiguration]()["parse-positional-numbers"] === void 0;
        if (parsePositionalNumbers) {
          argv = this[kParsePositionalNumbers](argv);
        }
        if (runGlobalMiddleware) {
          argv = applyMiddleware(argv, this, __classPrivateFieldGet2(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false);
        }
        return argv;
      }
      [kReset](aliases = {}) {
        __classPrivateFieldSet2(this, _YargsInstance_options, __classPrivateFieldGet2(this, _YargsInstance_options, "f") || {}, "f");
        const tmpOptions = {};
        tmpOptions.local = __classPrivateFieldGet2(this, _YargsInstance_options, "f").local || [];
        tmpOptions.configObjects = __classPrivateFieldGet2(this, _YargsInstance_options, "f").configObjects || [];
        const localLookup = {};
        tmpOptions.local.forEach((l) => {
          localLookup[l] = true;
          (aliases[l] || []).forEach((a) => {
            localLookup[a] = true;
          });
        });
        Object.assign(__classPrivateFieldGet2(this, _YargsInstance_preservedGroups, "f"), Object.keys(__classPrivateFieldGet2(this, _YargsInstance_groups, "f")).reduce((acc, groupName) => {
          const keys = __classPrivateFieldGet2(this, _YargsInstance_groups, "f")[groupName].filter((key) => !(key in localLookup));
          if (keys.length > 0) {
            acc[groupName] = keys;
          }
          return acc;
        }, {}));
        __classPrivateFieldSet2(this, _YargsInstance_groups, {}, "f");
        const arrayOptions = [
          "array",
          "boolean",
          "string",
          "skipValidation",
          "count",
          "normalize",
          "number",
          "hiddenOptions"
        ];
        const objectOptions = [
          "narg",
          "key",
          "alias",
          "default",
          "defaultDescription",
          "config",
          "choices",
          "demandedOptions",
          "demandedCommands",
          "deprecatedOptions"
        ];
        arrayOptions.forEach((k) => {
          tmpOptions[k] = (__classPrivateFieldGet2(this, _YargsInstance_options, "f")[k] || []).filter((k2) => !localLookup[k2]);
        });
        objectOptions.forEach((k) => {
          tmpOptions[k] = objFilter(__classPrivateFieldGet2(this, _YargsInstance_options, "f")[k], (k2) => !localLookup[k2]);
        });
        tmpOptions.envPrefix = __classPrivateFieldGet2(this, _YargsInstance_options, "f").envPrefix;
        __classPrivateFieldSet2(this, _YargsInstance_options, tmpOptions, "f");
        __classPrivateFieldSet2(this, _YargsInstance_usage, __classPrivateFieldGet2(this, _YargsInstance_usage, "f") ? __classPrivateFieldGet2(this, _YargsInstance_usage, "f").reset(localLookup) : usage(this, __classPrivateFieldGet2(this, _YargsInstance_shim, "f")), "f");
        __classPrivateFieldSet2(this, _YargsInstance_validation, __classPrivateFieldGet2(this, _YargsInstance_validation, "f") ? __classPrivateFieldGet2(this, _YargsInstance_validation, "f").reset(localLookup) : validation(this, __classPrivateFieldGet2(this, _YargsInstance_usage, "f"), __classPrivateFieldGet2(this, _YargsInstance_shim, "f")), "f");
        __classPrivateFieldSet2(this, _YargsInstance_command, __classPrivateFieldGet2(this, _YargsInstance_command, "f") ? __classPrivateFieldGet2(this, _YargsInstance_command, "f").reset() : command(__classPrivateFieldGet2(this, _YargsInstance_usage, "f"), __classPrivateFieldGet2(this, _YargsInstance_validation, "f"), __classPrivateFieldGet2(this, _YargsInstance_globalMiddleware, "f"), __classPrivateFieldGet2(this, _YargsInstance_shim, "f")), "f");
        if (!__classPrivateFieldGet2(this, _YargsInstance_completion, "f"))
          __classPrivateFieldSet2(this, _YargsInstance_completion, completion(this, __classPrivateFieldGet2(this, _YargsInstance_usage, "f"), __classPrivateFieldGet2(this, _YargsInstance_command, "f"), __classPrivateFieldGet2(this, _YargsInstance_shim, "f")), "f");
        __classPrivateFieldGet2(this, _YargsInstance_globalMiddleware, "f").reset();
        __classPrivateFieldSet2(this, _YargsInstance_completionCommand, null, "f");
        __classPrivateFieldSet2(this, _YargsInstance_output, "", "f");
        __classPrivateFieldSet2(this, _YargsInstance_exitError, null, "f");
        __classPrivateFieldSet2(this, _YargsInstance_hasOutput, false, "f");
        this.parsed = false;
        return this;
      }
      [kRebase](base, dir) {
        return __classPrivateFieldGet2(this, _YargsInstance_shim, "f").path.relative(base, dir);
      }
      [kRunYargsParserAndExecuteCommands](args2, shortCircuit, calledFromCommand, commandIndex = 0, helpOnly = false) {
        let skipValidation = !!calledFromCommand || helpOnly;
        args2 = args2 || __classPrivateFieldGet2(this, _YargsInstance_processArgs, "f");
        __classPrivateFieldGet2(this, _YargsInstance_options, "f").__ = __classPrivateFieldGet2(this, _YargsInstance_shim, "f").y18n.__;
        __classPrivateFieldGet2(this, _YargsInstance_options, "f").configuration = this[kGetParserConfiguration]();
        const populateDoubleDash = !!__classPrivateFieldGet2(this, _YargsInstance_options, "f").configuration["populate--"];
        const config2 = Object.assign({}, __classPrivateFieldGet2(this, _YargsInstance_options, "f").configuration, {
          "populate--": true
        });
        const parsed = __classPrivateFieldGet2(this, _YargsInstance_shim, "f").Parser.detailed(args2, Object.assign({}, __classPrivateFieldGet2(this, _YargsInstance_options, "f"), {
          configuration: { "parse-positional-numbers": false, ...config2 }
        }));
        const argv = Object.assign(parsed.argv, __classPrivateFieldGet2(this, _YargsInstance_parseContext, "f"));
        let argvPromise = void 0;
        const aliases = parsed.aliases;
        let helpOptSet = false;
        let versionOptSet = false;
        Object.keys(argv).forEach((key) => {
          if (key === __classPrivateFieldGet2(this, _YargsInstance_helpOpt, "f") && argv[key]) {
            helpOptSet = true;
          } else if (key === __classPrivateFieldGet2(this, _YargsInstance_versionOpt, "f") && argv[key]) {
            versionOptSet = true;
          }
        });
        argv.$0 = this.$0;
        this.parsed = parsed;
        if (commandIndex === 0) {
          __classPrivateFieldGet2(this, _YargsInstance_usage, "f").clearCachedHelpMessage();
        }
        try {
          this[kGuessLocale]();
          if (shortCircuit) {
            return this[kPostProcess](argv, populateDoubleDash, !!calledFromCommand, false);
          }
          if (__classPrivateFieldGet2(this, _YargsInstance_helpOpt, "f")) {
            const helpCmds = [__classPrivateFieldGet2(this, _YargsInstance_helpOpt, "f")].concat(aliases[__classPrivateFieldGet2(this, _YargsInstance_helpOpt, "f")] || []).filter((k) => k.length > 1);
            if (helpCmds.includes("" + argv._[argv._.length - 1])) {
              argv._.pop();
              helpOptSet = true;
            }
          }
          __classPrivateFieldSet2(this, _YargsInstance_isGlobalContext, false, "f");
          const handlerKeys = __classPrivateFieldGet2(this, _YargsInstance_command, "f").getCommands();
          const requestCompletions = __classPrivateFieldGet2(this, _YargsInstance_completion, "f").completionKey in argv;
          const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
          if (argv._.length) {
            if (handlerKeys.length) {
              let firstUnknownCommand;
              for (let i = commandIndex || 0, cmd; argv._[i] !== void 0; i++) {
                cmd = String(argv._[i]);
                if (handlerKeys.includes(cmd) && cmd !== __classPrivateFieldGet2(this, _YargsInstance_completionCommand, "f")) {
                  const innerArgv = __classPrivateFieldGet2(this, _YargsInstance_command, "f").runCommand(cmd, this, parsed, i + 1, helpOnly, helpOptSet || versionOptSet || helpOnly);
                  return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false);
                } else if (!firstUnknownCommand && cmd !== __classPrivateFieldGet2(this, _YargsInstance_completionCommand, "f")) {
                  firstUnknownCommand = cmd;
                  break;
                }
              }
              if (!__classPrivateFieldGet2(this, _YargsInstance_command, "f").hasDefaultCommand() && __classPrivateFieldGet2(this, _YargsInstance_recommendCommands, "f") && firstUnknownCommand && !skipRecommendation) {
                __classPrivateFieldGet2(this, _YargsInstance_validation, "f").recommendCommands(firstUnknownCommand, handlerKeys);
              }
            }
            if (__classPrivateFieldGet2(this, _YargsInstance_completionCommand, "f") && argv._.includes(__classPrivateFieldGet2(this, _YargsInstance_completionCommand, "f")) && !requestCompletions) {
              if (__classPrivateFieldGet2(this, _YargsInstance_exitProcess, "f"))
                setBlocking(true);
              this.showCompletionScript();
              this.exit(0);
            }
          }
          if (__classPrivateFieldGet2(this, _YargsInstance_command, "f").hasDefaultCommand() && !skipRecommendation) {
            const innerArgv = __classPrivateFieldGet2(this, _YargsInstance_command, "f").runCommand(null, this, parsed, 0, helpOnly, helpOptSet || versionOptSet || helpOnly);
            return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false);
          }
          if (requestCompletions) {
            if (__classPrivateFieldGet2(this, _YargsInstance_exitProcess, "f"))
              setBlocking(true);
            args2 = [].concat(args2);
            const completionArgs = args2.slice(args2.indexOf(`--${__classPrivateFieldGet2(this, _YargsInstance_completion, "f").completionKey}`) + 1);
            __classPrivateFieldGet2(this, _YargsInstance_completion, "f").getCompletion(completionArgs, (err, completions) => {
              if (err)
                throw new YError(err.message);
              (completions || []).forEach((completion2) => {
                __classPrivateFieldGet2(this, _YargsInstance_logger, "f").log(completion2);
              });
              this.exit(0);
            });
            return this[kPostProcess](argv, !populateDoubleDash, !!calledFromCommand, false);
          }
          if (!__classPrivateFieldGet2(this, _YargsInstance_hasOutput, "f")) {
            if (helpOptSet) {
              if (__classPrivateFieldGet2(this, _YargsInstance_exitProcess, "f"))
                setBlocking(true);
              skipValidation = true;
              this.showHelp("log");
              this.exit(0);
            } else if (versionOptSet) {
              if (__classPrivateFieldGet2(this, _YargsInstance_exitProcess, "f"))
                setBlocking(true);
              skipValidation = true;
              __classPrivateFieldGet2(this, _YargsInstance_usage, "f").showVersion("log");
              this.exit(0);
            }
          }
          if (!skipValidation && __classPrivateFieldGet2(this, _YargsInstance_options, "f").skipValidation.length > 0) {
            skipValidation = Object.keys(argv).some((key) => __classPrivateFieldGet2(this, _YargsInstance_options, "f").skipValidation.indexOf(key) >= 0 && argv[key] === true);
          }
          if (!skipValidation) {
            if (parsed.error)
              throw new YError(parsed.error.message);
            if (!requestCompletions) {
              const validation2 = this[kRunValidation](aliases, {}, parsed.error);
              if (!calledFromCommand) {
                argvPromise = applyMiddleware(argv, this, __classPrivateFieldGet2(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), true);
              }
              argvPromise = this[kValidateAsync](validation2, argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv);
              if (isPromise(argvPromise) && !calledFromCommand) {
                argvPromise = argvPromise.then(() => {
                  return applyMiddleware(argv, this, __classPrivateFieldGet2(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false);
                });
              }
            }
          }
        } catch (err) {
          if (err instanceof YError)
            __classPrivateFieldGet2(this, _YargsInstance_usage, "f").fail(err.message, err);
          else
            throw err;
        }
        return this[kPostProcess](argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv, populateDoubleDash, !!calledFromCommand, true);
      }
      [kRunValidation](aliases, positionalMap, parseErrors, isDefaultCommand) {
        const demandedOptions = { ...this.getDemandedOptions() };
        return (argv) => {
          if (parseErrors)
            throw new YError(parseErrors.message);
          __classPrivateFieldGet2(this, _YargsInstance_validation, "f").nonOptionCount(argv);
          __classPrivateFieldGet2(this, _YargsInstance_validation, "f").requiredArguments(argv, demandedOptions);
          let failedStrictCommands = false;
          if (__classPrivateFieldGet2(this, _YargsInstance_strictCommands, "f")) {
            failedStrictCommands = __classPrivateFieldGet2(this, _YargsInstance_validation, "f").unknownCommands(argv);
          }
          if (__classPrivateFieldGet2(this, _YargsInstance_strict, "f") && !failedStrictCommands) {
            __classPrivateFieldGet2(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, positionalMap, !!isDefaultCommand);
          } else if (__classPrivateFieldGet2(this, _YargsInstance_strictOptions, "f")) {
            __classPrivateFieldGet2(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, {}, false, false);
          }
          __classPrivateFieldGet2(this, _YargsInstance_validation, "f").limitedChoices(argv);
          __classPrivateFieldGet2(this, _YargsInstance_validation, "f").implications(argv);
          __classPrivateFieldGet2(this, _YargsInstance_validation, "f").conflicting(argv);
        };
      }
      [kSetHasOutput]() {
        __classPrivateFieldSet2(this, _YargsInstance_hasOutput, true, "f");
      }
      [kTrackManuallySetKeys](keys) {
        if (typeof keys === "string") {
          __classPrivateFieldGet2(this, _YargsInstance_options, "f").key[keys] = true;
        } else {
          for (const k of keys) {
            __classPrivateFieldGet2(this, _YargsInstance_options, "f").key[k] = true;
          }
        }
      }
    };
  }
});

// node_modules/yargs/index.mjs
var yargs_exports = {};
__export(yargs_exports, {
  default: () => yargs_default
});
var Yargs, yargs_default;
var init_yargs = __esm({
  "node_modules/yargs/index.mjs"() {
    "use strict";
    init_prefix();
    init_esm();
    init_yargs_factory();
    Yargs = YargsFactory(esm_default);
    yargs_default = Yargs;
  }
});

// node_modules/yargs/helpers/helpers.mjs
var helpers_exports = {};
__export(helpers_exports, {
  Parser: () => lib_default,
  applyExtends: () => applyExtends2,
  hideBin: () => hideBin
});
var applyExtends2;
var init_helpers = __esm({
  "node_modules/yargs/helpers/helpers.mjs"() {
    init_prefix();
    init_apply_extends();
    init_process_argv();
    init_lib2();
    init_esm();
    applyExtends2 = (config2, cwd, mergeExtends) => {
      return applyExtends(config2, cwd, mergeExtends, esm_default);
    };
  }
});

// node_modules/@puppeteer/browsers/lib/cjs/CLI.js
var require_CLI = __commonJS({
  "node_modules/@puppeteer/browsers/lib/cjs/CLI.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
      var ownKeys2 = function(o) {
        ownKeys2 = 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 ownKeys2(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]);
        }
        __setModuleDefault2(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CLI = void 0;
    var node_process_1 = require("node:process");
    var readline2 = __importStar2(require("node:readline"));
    var browser_data_js_1 = require_browser_data();
    var Cache_js_1 = require_Cache();
    var detectPlatform_js_1 = require_detectPlatform();
    var install_js_1 = require_install();
    var launch_js_1 = require_launch();
    function isValidBrowser(browser) {
      return Object.values(browser_data_js_1.Browser).includes(browser);
    }
    function isValidPlatform(platform) {
      return Object.values(browser_data_js_1.BrowserPlatform).includes(platform);
    }
    var packageVersion = "2.13.0";
    var CLI = class {
      #cachePath;
      #rl;
      #scriptName;
      #version;
      #allowCachePathOverride;
      #pinnedBrowsers;
      #prefixCommand;
      constructor(opts, rl) {
        if (!opts) {
          opts = {};
        }
        if (typeof opts === "string") {
          opts = {
            cachePath: opts
          };
        }
        this.#cachePath = opts.cachePath ?? process.cwd();
        this.#rl = rl;
        this.#scriptName = opts.scriptName ?? "@puppeteer/browsers";
        this.#version = opts.version ?? packageVersion;
        this.#allowCachePathOverride = opts.allowCachePathOverride ?? true;
        this.#pinnedBrowsers = opts.pinnedBrowsers;
        this.#prefixCommand = opts.prefixCommand;
      }
      #defineBrowserParameter(yargs, required) {
        return yargs.positional("browser", {
          description: "Which browser to install <browser>[@<buildId|latest>]. `latest` will try to find the latest available build. `buildId` is a browser-specific identifier such as a version or a revision.",
          type: "string",
          coerce: (opt) => {
            const browser = {
              name: this.#parseBrowser(opt),
              buildId: this.#parseBuildId(opt)
            };
            if (!isValidBrowser(browser.name)) {
              throw new Error(`Unsupported browser '${browser.name}'`);
            }
            return browser;
          },
          demandOption: required
        });
      }
      #definePlatformParameter(yargs) {
        return yargs.option("platform", {
          type: "string",
          desc: "Platform that the binary needs to be compatible with.",
          choices: Object.values(browser_data_js_1.BrowserPlatform),
          default: (0, detectPlatform_js_1.detectBrowserPlatform)(),
          coerce: (platform) => {
            if (!isValidPlatform(platform)) {
              throw new Error(`Unsupported platform '${platform}'`);
            }
            return platform;
          },
          defaultDescription: "Auto-detected"
        });
      }
      #definePathParameter(yargs, required = false) {
        if (!this.#allowCachePathOverride) {
          return yargs;
        }
        return yargs.option("path", {
          type: "string",
          desc: "Path to the root folder for the browser downloads and installation. If a relative path is provided, it will be resolved relative to the current working directory. The installation folder structure is compatible with the cache structure used by Puppeteer.",
          defaultDescription: "Current working directory",
          ...required ? {} : { default: process.cwd() },
          demandOption: required
        });
      }
      async run(argv) {
        const { default: yargs } = await Promise.resolve().then(() => (init_yargs(), yargs_exports));
        const { hideBin: hideBin2 } = await Promise.resolve().then(() => (init_helpers(), helpers_exports));
        const yargsInstance = yargs(hideBin2(argv));
        let target = yargsInstance.scriptName(this.#scriptName).version(this.#version);
        if (this.#prefixCommand) {
          target = target.command(this.#prefixCommand.cmd, this.#prefixCommand.description, (yargs2) => {
            return this.#build(yargs2);
          });
        } else {
          target = this.#build(target);
        }
        await target.demandCommand(1).help().wrap(Math.min(120, yargsInstance.terminalWidth())).parseAsync();
      }
      #build(yargs) {
        const latestOrPinned = this.#pinnedBrowsers ? "pinned" : "latest";
        const browserArgType = this.#pinnedBrowsers ? "[browser]" : "<browser>";
        return yargs.command(`install ${browserArgType}`, "Download and install the specified browser. If successful, the command outputs the actual browser buildId that was installed and the absolute path to the browser executable (see --format).", (yargs2) => {
          if (this.#pinnedBrowsers) {
            yargs2.example("$0 install", "Install all pinned browsers");
          }
          yargs2.example("$0 install chrome", `Install the ${latestOrPinned} available build of the Chrome browser.`).example("$0 install chrome@latest", "Install the latest available build for the Chrome browser.").example("$0 install chrome@stable", "Install the latest available build for the Chrome browser from the stable channel.").example("$0 install chrome@beta", "Install the latest available build for the Chrome browser from the beta channel.").example("$0 install chrome@dev", "Install the latest available build for the Chrome browser from the dev channel.").example("$0 install chrome@canary", "Install the latest available build for the Chrome Canary browser.").example("$0 install chrome@115", "Install the latest available build for Chrome 115.").example("$0 install chromedriver@canary", "Install the latest available build for ChromeDriver Canary.").example("$0 install chromedriver@115", "Install the latest available build for ChromeDriver 115.").example("$0 install chromedriver@115.0.5790", "Install the latest available patch (115.0.5790.X) build for ChromeDriver.").example("$0 install chrome-headless-shell", "Install the latest available chrome-headless-shell build.").example("$0 install chrome-headless-shell@beta", "Install the latest available chrome-headless-shell build corresponding to the Beta channel.").example("$0 install chrome-headless-shell@118", "Install the latest available chrome-headless-shell 118 build.").example("$0 install chromium@1083080", "Install the revision 1083080 of the Chromium browser.").example("$0 install firefox", "Install the latest nightly available build of the Firefox browser.").example("$0 install firefox@stable", "Install the latest stable build of the Firefox browser.").example("$0 install firefox@beta", "Install the latest beta build of the Firefox browser.").example("$0 install firefox@devedition", "Install the latest devedition build of the Firefox browser.").example("$0 install firefox@esr", "Install the latest ESR build of the Firefox browser.").example("$0 install firefox@nightly", "Install the latest nightly build of the Firefox browser.").example("$0 install firefox@stable_111.0.1", "Install a specific version of the Firefox browser.").example("$0 install firefox --platform mac", "Install the latest Mac (Intel) build of the Firefox browser.");
          if (this.#allowCachePathOverride) {
            yargs2.example("$0 install firefox --path /tmp/my-browser-cache", "Install to the specified cache directory.");
          }
          const yargsWithBrowserParam = this.#defineBrowserParameter(yargs2, !Boolean(this.#pinnedBrowsers));
          const yargsWithPlatformParam = this.#definePlatformParameter(yargsWithBrowserParam);
          return this.#definePathParameter(yargsWithPlatformParam, false).option("base-url", {
            type: "string",
            desc: "Base URL to download from"
          }).option("install-deps", {
            type: "boolean",
            desc: "Whether to attempt installing system dependencies (only supported on Linux, requires root privileges).",
            default: false
          }).option("format", {
            type: "string",
            desc: "Format to use for the output. Supported placeholders: {{browser}}, {{buildId}}, {{path}}, {{platform}}",
            default: "{{browser}}@{{buildId}} {{path}}"
          });
        }, async (args2) => {
          if (this.#pinnedBrowsers && !args2.browser) {
            const result = await Promise.allSettled(Object.entries(this.#pinnedBrowsers).map(async ([browser, options]) => {
              if (options.skipDownload) {
                return;
              }
              await this.#install({
                ...args2,
                browser: {
                  name: browser,
                  buildId: options.buildId
                }
              });
            }));
            for (const install of result) {
              if (install.status === "rejected") {
                throw install.reason;
              }
            }
          } else {
            await this.#install(args2);
          }
        }).command("launch <browser>", "Launch the specified browser", (yargs2) => {
          yargs2.example("$0 launch chrome@115.0.5790.170", "Launch Chrome 115.0.5790.170").example("$0 launch firefox@112.0a1", "Launch the Firefox browser identified by the milestone 112.0a1.").example("$0 launch chrome@115.0.5790.170 --detached", "Launch the browser but detach the sub-processes.").example("$0 launch chrome@canary --system", "Try to locate the Canary build of Chrome installed on the system and launch it.").example("$0 launch chrome@115.0.5790.170 -- --version", "Launch Chrome 115.0.5790.170 and pass custom argument to the binary.");
          const yargsWithExtraAgs = yargs2.parserConfiguration({
            "populate--": true
            // Yargs does not have the correct overload for this.
          });
          const yargsWithBrowserParam = this.#defineBrowserParameter(yargsWithExtraAgs, true);
          const yargsWithPlatformParam = this.#definePlatformParameter(yargsWithBrowserParam);
          return this.#definePathParameter(yargsWithPlatformParam).option("detached", {
            type: "boolean",
            desc: "Detach the child process.",
            default: false
          }).option("system", {
            type: "boolean",
            desc: "Search for a browser installed on the system instead of the cache folder.",
            default: false
          }).option("dumpio", {
            type: "boolean",
            desc: "Forwards the browser's process stdout and stderr",
            default: false
          });
        }, async (args2) => {
          const extraArgs = args2["--"]?.filter((arg) => {
            return typeof arg === "string";
          });
          args2.browser.buildId = this.#resolvePinnedBrowserIfNeeded(args2.browser.buildId, args2.browser.name);
          const executablePath = args2.system ? (0, launch_js_1.computeSystemExecutablePath)({
            browser: args2.browser.name,
            // TODO: throw an error if not a ChromeReleaseChannel is provided.
            channel: args2.browser.buildId,
            platform: args2.platform
          }) : (0, launch_js_1.computeExecutablePath)({
            browser: args2.browser.name,
            buildId: args2.browser.buildId,
            cacheDir: args2.path ?? this.#cachePath,
            platform: args2.platform
          });
          (0, launch_js_1.launch)({
            args: extraArgs,
            executablePath,
            dumpio: args2.dumpio,
            detached: args2.detached
          });
        }).command("clear", this.#allowCachePathOverride ? "Removes all installed browsers from the specified cache directory" : `Removes all installed browsers from ${this.#cachePath}`, (yargs2) => {
          return this.#definePathParameter(yargs2, true);
        }, async (args2) => {
          const cacheDir = args2.path ?? this.#cachePath;
          const rl = this.#rl ?? readline2.createInterface({ input: node_process_1.stdin, output: node_process_1.stdout });
          rl.question(`Do you want to permanently and recursively delete the content of ${cacheDir} (yes/No)? `, (answer) => {
            rl.close();
            if (!["y", "yes"].includes(answer.toLowerCase().trim())) {
              console.log("Cancelled.");
              return;
            }
            const cache = new Cache_js_1.Cache(cacheDir);
            cache.clear();
            console.log(`${cacheDir} cleared.`);
          });
        }).command("list", "List all installed browsers in the cache directory", (yargs2) => {
          yargs2.example("$0 list", "List all installed browsers in the cache directory");
          if (this.#allowCachePathOverride) {
            yargs2.example("$0 list --path /tmp/my-browser-cache", "List browsers installed in the specified cache directory");
          }
          return this.#definePathParameter(yargs2);
        }, async (args2) => {
          const cacheDir = args2.path ?? this.#cachePath;
          const cache = new Cache_js_1.Cache(cacheDir);
          const browsers = cache.getInstalledBrowsers();
          for (const browser of browsers) {
            console.log(`${browser.browser}@${browser.buildId} (${browser.platform}) ${browser.executablePath}`);
          }
        }).demandCommand(1).help();
      }
      #parseBrowser(version) {
        return version.split("@").shift();
      }
      #parseBuildId(version) {
        const parts = version.split("@");
        return parts.length === 2 ? parts[1] : this.#pinnedBrowsers ? "pinned" : "latest";
      }
      #resolvePinnedBrowserIfNeeded(buildId, browserName) {
        if (buildId === "pinned") {
          const options = this.#pinnedBrowsers?.[browserName];
          if (!options || !options.buildId) {
            throw new Error(`No pinned version found for ${browserName}`);
          }
          return options.buildId;
        }
        return buildId;
      }
      async #install(args2) {
        if (!args2.browser) {
          throw new Error(`No browser arg provided`);
        }
        if (!args2.platform) {
          throw new Error(`Could not resolve the current platform`);
        }
        args2.browser.buildId = this.#resolvePinnedBrowserIfNeeded(args2.browser.buildId, args2.browser.name);
        const originalBuildId = args2.browser.buildId;
        args2.browser.buildId = await (0, browser_data_js_1.resolveBuildId)(args2.browser.name, args2.platform, args2.browser.buildId);
        await (0, install_js_1.install)({
          browser: args2.browser.name,
          buildId: args2.browser.buildId,
          platform: args2.platform,
          cacheDir: args2.path ?? this.#cachePath,
          downloadProgressCallback: "default",
          baseUrl: args2.baseUrl,
          buildIdAlias: originalBuildId !== args2.browser.buildId ? originalBuildId : void 0,
          installDeps: args2.installDeps
        });
        const executablePath = (0, launch_js_1.computeExecutablePath)({
          browser: args2.browser.name,
          buildId: args2.browser.buildId,
          cacheDir: args2.path ?? this.#cachePath,
          platform: args2.platform
        });
        console.log(args2.format.replace(/{{browser}}/g, args2.browser.name).replace(/{{buildId}}/g, args2.browser.buildId).replace(/{{path}}/g, executablePath).replace(/{{platform}}/g, args2.platform));
      }
    };
    exports2.CLI = CLI;
  }
});

// node_modules/@puppeteer/browsers/lib/cjs/provider.js
var require_provider = __commonJS({
  "node_modules/@puppeteer/browsers/lib/cjs/provider.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.buildArchiveFilename = buildArchiveFilename;
    function buildArchiveFilename(browser, platform, buildId, extension = "zip") {
      return `${browser}-${platform}-${buildId}.${extension}`;
    }
  }
});

// node_modules/@puppeteer/browsers/lib/cjs/main.js
var require_main2 = __commonJS({
  "node_modules/@puppeteer/browsers/lib/cjs/main.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.buildArchiveFilename = exports2.DefaultProvider = exports2.BrowserTag = exports2.InstalledBrowser = exports2.Cache = exports2.CLI = exports2.resolveDefaultUserDataDir = exports2.getVersionComparator = exports2.createProfile = exports2.ChromeReleaseChannel = exports2.BrowserPlatform = exports2.Browser = exports2.resolveBuildId = exports2.detectBrowserPlatform = exports2.getDownloadUrl = exports2.uninstall = exports2.canDownload = exports2.getInstalledBrowsers = exports2.makeProgressCallback = exports2.install = exports2.Process = exports2.WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX = exports2.CDP_WEBSOCKET_ENDPOINT_REGEX = exports2.TimeoutError = exports2.computeSystemExecutablePath = exports2.computeExecutablePath = exports2.launch = void 0;
    var launch_js_1 = require_launch();
    Object.defineProperty(exports2, "launch", { enumerable: true, get: function() {
      return launch_js_1.launch;
    } });
    Object.defineProperty(exports2, "computeExecutablePath", { enumerable: true, get: function() {
      return launch_js_1.computeExecutablePath;
    } });
    Object.defineProperty(exports2, "computeSystemExecutablePath", { enumerable: true, get: function() {
      return launch_js_1.computeSystemExecutablePath;
    } });
    Object.defineProperty(exports2, "TimeoutError", { enumerable: true, get: function() {
      return launch_js_1.TimeoutError;
    } });
    Object.defineProperty(exports2, "CDP_WEBSOCKET_ENDPOINT_REGEX", { enumerable: true, get: function() {
      return launch_js_1.CDP_WEBSOCKET_ENDPOINT_REGEX;
    } });
    Object.defineProperty(exports2, "WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX", { enumerable: true, get: function() {
      return launch_js_1.WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX;
    } });
    Object.defineProperty(exports2, "Process", { enumerable: true, get: function() {
      return launch_js_1.Process;
    } });
    var install_js_1 = require_install();
    Object.defineProperty(exports2, "install", { enumerable: true, get: function() {
      return install_js_1.install;
    } });
    Object.defineProperty(exports2, "makeProgressCallback", { enumerable: true, get: function() {
      return install_js_1.makeProgressCallback;
    } });
    Object.defineProperty(exports2, "getInstalledBrowsers", { enumerable: true, get: function() {
      return install_js_1.getInstalledBrowsers;
    } });
    Object.defineProperty(exports2, "canDownload", { enumerable: true, get: function() {
      return install_js_1.canDownload;
    } });
    Object.defineProperty(exports2, "uninstall", { enumerable: true, get: function() {
      return install_js_1.uninstall;
    } });
    Object.defineProperty(exports2, "getDownloadUrl", { enumerable: true, get: function() {
      return install_js_1.getDownloadUrl;
    } });
    var detectPlatform_js_1 = require_detectPlatform();
    Object.defineProperty(exports2, "detectBrowserPlatform", { enumerable: true, get: function() {
      return detectPlatform_js_1.detectBrowserPlatform;
    } });
    var browser_data_js_1 = require_browser_data();
    Object.defineProperty(exports2, "resolveBuildId", { enumerable: true, get: function() {
      return browser_data_js_1.resolveBuildId;
    } });
    Object.defineProperty(exports2, "Browser", { enumerable: true, get: function() {
      return browser_data_js_1.Browser;
    } });
    Object.defineProperty(exports2, "BrowserPlatform", { enumerable: true, get: function() {
      return browser_data_js_1.BrowserPlatform;
    } });
    Object.defineProperty(exports2, "ChromeReleaseChannel", { enumerable: true, get: function() {
      return browser_data_js_1.ChromeReleaseChannel;
    } });
    Object.defineProperty(exports2, "createProfile", { enumerable: true, get: function() {
      return browser_data_js_1.createProfile;
    } });
    Object.defineProperty(exports2, "getVersionComparator", { enumerable: true, get: function() {
      return browser_data_js_1.getVersionComparator;
    } });
    Object.defineProperty(exports2, "resolveDefaultUserDataDir", { enumerable: true, get: function() {
      return browser_data_js_1.resolveDefaultUserDataDir;
    } });
    var CLI_js_1 = require_CLI();
    Object.defineProperty(exports2, "CLI", { enumerable: true, get: function() {
      return CLI_js_1.CLI;
    } });
    var Cache_js_1 = require_Cache();
    Object.defineProperty(exports2, "Cache", { enumerable: true, get: function() {
      return Cache_js_1.Cache;
    } });
    Object.defineProperty(exports2, "InstalledBrowser", { enumerable: true, get: function() {
      return Cache_js_1.InstalledBrowser;
    } });
    var types_js_1 = require_types();
    Object.defineProperty(exports2, "BrowserTag", { enumerable: true, get: function() {
      return types_js_1.BrowserTag;
    } });
    var DefaultProvider_js_1 = require_DefaultProvider();
    Object.defineProperty(exports2, "DefaultProvider", { enumerable: true, get: function() {
      return DefaultProvider_js_1.DefaultProvider;
    } });
    var provider_js_1 = require_provider();
    Object.defineProperty(exports2, "buildArchiveFilename", { enumerable: true, get: function() {
      return provider_js_1.buildArchiveFilename;
    } });
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/node/LaunchOptions.js
var require_LaunchOptions = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/node/LaunchOptions.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.convertPuppeteerChannelToBrowsersChannel = convertPuppeteerChannelToBrowsersChannel;
    var browsers_1 = require_main2();
    function convertPuppeteerChannelToBrowsersChannel(channel) {
      switch (channel) {
        case "chrome":
          return browsers_1.ChromeReleaseChannel.STABLE;
        case "chrome-dev":
          return browsers_1.ChromeReleaseChannel.DEV;
        case "chrome-beta":
          return browsers_1.ChromeReleaseChannel.BETA;
        case "chrome-canary":
          return browsers_1.ChromeReleaseChannel.CANARY;
      }
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/BrowserConnector.js
var require_BrowserConnector3 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/BrowserConnector.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
      var ownKeys2 = function(o) {
        ownKeys2 = 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 ownKeys2(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]);
        }
        __setModuleDefault2(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2._connectToBrowser = _connectToBrowser;
    var BrowserConnector_js_1 = require_BrowserConnector2();
    var BrowserConnector_js_2 = require_BrowserConnector();
    var environment_js_1 = require_environment();
    var assert_js_1 = require_assert();
    var ErrorLike_js_1 = require_ErrorLike();
    var getWebSocketTransportClass = async () => {
      return environment_js_1.isNode ? (await Promise.resolve().then(() => __importStar2(require_NodeWebSocketTransport()))).NodeWebSocketTransport : (await Promise.resolve().then(() => __importStar2(require_BrowserWebSocketTransport()))).BrowserWebSocketTransport;
    };
    async function _connectToBrowser(options) {
      const { connectionTransport, endpointUrl } = await getConnectionTransport(options);
      if (options.protocol === "webDriverBiDi") {
        const bidiBrowser = await (0, BrowserConnector_js_1._connectToBiDiBrowser)(connectionTransport, endpointUrl, options);
        return bidiBrowser;
      } else {
        const cdpBrowser = await (0, BrowserConnector_js_2._connectToCdpBrowser)(connectionTransport, endpointUrl, options);
        return cdpBrowser;
      }
    }
    async function getConnectionTransport(options) {
      const { browserWSEndpoint, browserURL, channel, transport, headers = {} } = options;
      (0, assert_js_1.assert)(Number(!!browserWSEndpoint) + Number(!!browserURL) + Number(!!transport) + Number(!!channel) === 1, "Exactly one of browserWSEndpoint, browserURL, transport or channel must be passed to puppeteer.connect");
      if (transport) {
        return { connectionTransport: transport, endpointUrl: "" };
      } else if (browserWSEndpoint) {
        const WebSocketClass = await getWebSocketTransportClass();
        const connectionTransport = await WebSocketClass.create(browserWSEndpoint, headers);
        return {
          connectionTransport,
          endpointUrl: browserWSEndpoint
        };
      } else if (browserURL) {
        const connectionURL = await getWSEndpoint(browserURL);
        const WebSocketClass = await getWebSocketTransportClass();
        const connectionTransport = await WebSocketClass.create(connectionURL);
        return {
          connectionTransport,
          endpointUrl: connectionURL
        };
      } else if (options.channel && environment_js_1.isNode) {
        const { detectBrowserPlatform, resolveDefaultUserDataDir, Browser } = await Promise.resolve().then(() => __importStar2(require_main2()));
        const platform = detectBrowserPlatform();
        if (!platform) {
          throw new Error("Could not detect required browser platform");
        }
        const { convertPuppeteerChannelToBrowsersChannel } = await Promise.resolve().then(() => __importStar2(require_LaunchOptions()));
        const { join } = await Promise.resolve().then(() => __importStar2(require("node:path")));
        const userDataDir = resolveDefaultUserDataDir(Browser.CHROME, platform, convertPuppeteerChannelToBrowsersChannel(options.channel));
        const portPath = join(userDataDir, "DevToolsActivePort");
        try {
          const fileContent = await environment_js_1.environment.value.fs.promises.readFile(portPath, "ascii");
          const [rawPort, rawPath] = fileContent.split("\n").map((line) => {
            return line.trim();
          }).filter((line) => {
            return !!line;
          });
          if (!rawPort || !rawPath) {
            throw new Error(`Invalid DevToolsActivePort '${fileContent}' found`);
          }
          const port = parseInt(rawPort, 10);
          if (isNaN(port) || port <= 0 || port > 65535) {
            throw new Error(`Invalid port '${rawPort}' found`);
          }
          const browserWSEndpoint2 = `ws://localhost:${port}${rawPath}`;
          const WebSocketClass = await getWebSocketTransportClass();
          const connectionTransport = await WebSocketClass.create(browserWSEndpoint2, headers);
          return {
            connectionTransport,
            endpointUrl: browserWSEndpoint2
          };
        } catch (error) {
          throw new Error(`Could not find DevToolsActivePort for ${options.channel} at ${portPath}`, {
            cause: error
          });
        }
      }
      throw new Error("Invalid connection options");
    }
    async function getWSEndpoint(browserURL) {
      const endpointURL = new URL("/json/version", browserURL);
      try {
        const result = await globalThis.fetch(endpointURL.toString(), {
          method: "GET"
        });
        if (!result.ok) {
          throw new Error(`HTTP ${result.statusText}`);
        }
        const data = await result.json();
        return data.webSocketDebuggerUrl;
      } catch (error) {
        if ((0, ErrorLike_js_1.isErrorLike)(error)) {
          error.message = `Failed to fetch browser webSocket URL from ${endpointURL}: ` + error.message;
        }
        throw error;
      }
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/Puppeteer.js
var require_Puppeteer = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/Puppeteer.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Puppeteer = void 0;
    var BrowserConnector_js_1 = require_BrowserConnector3();
    var CustomQueryHandler_js_1 = require_CustomQueryHandler();
    var Puppeteer = class {
      /**
       * Operations for {@link CustomQueryHandler | custom query handlers}. See
       * {@link CustomQueryHandlerRegistry}.
       *
       * @internal
       */
      static customQueryHandlers = CustomQueryHandler_js_1.customQueryHandlers;
      /**
       * Registers a {@link CustomQueryHandler | custom query handler}.
       *
       * @remarks
       * After registration, the handler can be used everywhere where a selector is
       * expected by prepending the selection string with `<name>/`. The name is only
       * allowed to consist of lower- and upper case latin letters.
       *
       * @example
       *
       * ```
       * import {Puppeteer}, puppeteer from 'puppeteer';
       *
       * Puppeteer.registerCustomQueryHandler('text', { … });
       * const aHandle = await page.$('text/…');
       * ```
       *
       * @param name - The name that the custom query handler will be registered
       * under.
       * @param queryHandler - The {@link CustomQueryHandler | custom query handler}
       * to register.
       *
       * @public
       */
      static registerCustomQueryHandler(name, queryHandler) {
        return this.customQueryHandlers.register(name, queryHandler);
      }
      /**
       * Unregisters a custom query handler for a given name.
       */
      static unregisterCustomQueryHandler(name) {
        return this.customQueryHandlers.unregister(name);
      }
      /**
       * Gets the names of all custom query handlers.
       */
      static customQueryHandlerNames() {
        return this.customQueryHandlers.names();
      }
      /**
       * Unregisters all custom query handlers.
       */
      static clearCustomQueryHandlers() {
        return this.customQueryHandlers.clear();
      }
      /**
       * @internal
       */
      _isPuppeteerCore;
      /**
       * @internal
       */
      _changedBrowsers = false;
      /**
       * @internal
       */
      constructor(settings) {
        this._isPuppeteerCore = settings.isPuppeteerCore;
        this.connect = this.connect.bind(this);
      }
      /**
       * This method attaches Puppeteer to an existing browser instance.
       *
       * @remarks
       *
       * @param options - Set of configurable options to set on the browser.
       * @returns Promise which resolves to browser instance.
       */
      connect(options) {
        return (0, BrowserConnector_js_1._connectToBrowser)(options);
      }
    };
    exports2.Puppeteer = Puppeteer;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/TaskQueue.js
var require_TaskQueue = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/TaskQueue.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.TaskQueue = void 0;
    var TaskQueue = class {
      #chain;
      constructor() {
        this.#chain = Promise.resolve();
      }
      postTask(task) {
        const result = this.#chain.then(task);
        this.#chain = result.then(() => {
          return void 0;
        }, () => {
          return void 0;
        });
        return result;
      }
    };
    exports2.TaskQueue = TaskQueue;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/common/common.js
var require_common4 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/common/common.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    __exportStar2(require_BrowserWebSocketTransport(), exports2);
    __exportStar2(require_CallbackRegistry(), exports2);
    __exportStar2(require_AriaQueryHandler(), exports2);
    __exportStar2(require_ConsoleMessage(), exports2);
    __exportStar2(require_CustomQueryHandler(), exports2);
    __exportStar2(require_Debug(), exports2);
    __exportStar2(require_Device(), exports2);
    __exportStar2(require_Errors(), exports2);
    __exportStar2(require_EventEmitter(), exports2);
    __exportStar2(require_FileChooser(), exports2);
    __exportStar2(require_GetQueryHandler(), exports2);
    __exportStar2(require_HandleIterator(), exports2);
    __exportStar2(require_LazyArg(), exports2);
    __exportStar2(require_NetworkManagerEvents(), exports2);
    __exportStar2(require_PDFOptions(), exports2);
    __exportStar2(require_PierceQueryHandler(), exports2);
    __exportStar2(require_PQueryHandler(), exports2);
    __exportStar2(require_PSelectorParser(), exports2);
    __exportStar2(require_Puppeteer(), exports2);
    __exportStar2(require_QueryHandler(), exports2);
    __exportStar2(require_ScriptInjector(), exports2);
    __exportStar2(require_SecurityDetails(), exports2);
    __exportStar2(require_TaskQueue(), exports2);
    __exportStar2(require_TextQueryHandler(), exports2);
    __exportStar2(require_TimeoutSettings(), exports2);
    __exportStar2(require_USKeyboardLayout(), exports2);
    __exportStar2(require_util(), exports2);
    __exportStar2(require_WaitTask(), exports2);
    __exportStar2(require_XPathQueryHandler(), exports2);
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/revisions.js
var require_revisions = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/revisions.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PUPPETEER_REVISIONS = void 0;
    exports2.PUPPETEER_REVISIONS = Object.freeze({
      chrome: "146.0.7680.153",
      "chrome-headless-shell": "146.0.7680.153",
      firefox: "stable_148.0.2"
    });
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/util/util.js
var require_util6 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/util/util.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    __exportStar2(require_assert(), exports2);
    __exportStar2(require_Deferred(), exports2);
    __exportStar2(require_Mutex(), exports2);
    __exportStar2(require_ErrorLike(), exports2);
    __exportStar2(require_AsyncIterableUtil(), exports2);
    __exportStar2(require_disposable(), exports2);
    __exportStar2(require_incremental_id_generator(), exports2);
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/index-browser.js
var require_index_browser = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/index-browser.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    __exportStar2(require_api(), exports2);
    __exportStar2(require_cdp(), exports2);
    __exportStar2(require_common4(), exports2);
    __exportStar2(require_revisions(), exports2);
    __exportStar2(require_util6(), exports2);
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/node/PipeTransport.js
var require_PipeTransport = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/node/PipeTransport.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PipeTransport = void 0;
    var EventEmitter_js_1 = require_EventEmitter();
    var util_js_1 = require_util();
    var assert_js_1 = require_assert();
    var disposable_js_1 = require_disposable();
    var PipeTransport = class {
      #pipeWrite;
      #subscriptions = new disposable_js_1.DisposableStack();
      #isClosed = false;
      #pendingMessage = [];
      onclose;
      onmessage;
      constructor(pipeWrite, pipeRead) {
        this.#pipeWrite = pipeWrite;
        const pipeReadEmitter = this.#subscriptions.use(
          // NodeJS event emitters don't support `*` so we need to typecast
          // As long as we don't use it we should be OK.
          new EventEmitter_js_1.EventEmitter(pipeRead)
        );
        pipeReadEmitter.on("data", (buffer) => {
          return this.#dispatch(buffer);
        });
        pipeReadEmitter.on("close", () => {
          if (this.onclose) {
            this.onclose.call(null);
          }
        });
        pipeReadEmitter.on("error", util_js_1.debugError);
        const pipeWriteEmitter = this.#subscriptions.use(
          // NodeJS event emitters don't support `*` so we need to typecast
          // As long as we don't use it we should be OK.
          new EventEmitter_js_1.EventEmitter(pipeWrite)
        );
        pipeWriteEmitter.on("error", util_js_1.debugError);
      }
      send(message) {
        (0, assert_js_1.assert)(!this.#isClosed, "`PipeTransport` is closed.");
        this.#pipeWrite.write(message);
        this.#pipeWrite.write("\0");
      }
      #dispatch(buffer) {
        (0, assert_js_1.assert)(!this.#isClosed, "`PipeTransport` is closed.");
        this.#pendingMessage.push(buffer);
        if (buffer.indexOf("\0") === -1) {
          return;
        }
        const concatBuffer = Buffer.concat(this.#pendingMessage);
        let start = 0;
        let end = concatBuffer.indexOf("\0");
        while (end !== -1) {
          const message = concatBuffer.toString(void 0, start, end);
          setImmediate(() => {
            if (this.onmessage) {
              this.onmessage.call(null, message);
            }
          });
          start = end + 1;
          end = concatBuffer.indexOf("\0", start);
        }
        if (start >= concatBuffer.length) {
          this.#pendingMessage = [];
        } else {
          this.#pendingMessage = [concatBuffer.subarray(start)];
        }
      }
      close() {
        this.#isClosed = true;
        this.#subscriptions.dispose();
      }
    };
    exports2.PipeTransport = PipeTransport;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/node/BrowserLauncher.js
var require_BrowserLauncher = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/node/BrowserLauncher.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
      var ownKeys2 = function(o) {
        ownKeys2 = 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 ownKeys2(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]);
        }
        __setModuleDefault2(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.BrowserLauncher = void 0;
    var node_fs_1 = require("node:fs");
    var node_os_1 = require("node:os");
    var node_path_1 = require("node:path");
    var browsers_1 = require_main2();
    var rxjs_js_1 = require_rxjs();
    var Browser_js_1 = require_Browser2();
    var Connection_js_1 = require_Connection();
    var Errors_js_1 = require_Errors();
    var util_js_1 = require_util();
    var incremental_id_generator_js_1 = require_incremental_id_generator();
    var NodeWebSocketTransport_js_1 = require_NodeWebSocketTransport();
    var PipeTransport_js_1 = require_PipeTransport();
    var BrowserLauncher = class {
      #browser;
      /**
       * @internal
       */
      puppeteer;
      /**
       * @internal
       */
      constructor(puppeteer, browser) {
        this.puppeteer = puppeteer;
        this.#browser = browser;
      }
      get browser() {
        return this.#browser;
      }
      async launch(options = {}) {
        const { dumpio = false, enableExtensions = false, env: env2 = process.env, handleSIGINT = true, handleSIGTERM = true, handleSIGHUP = true, acceptInsecureCerts = false, networkEnabled = true, defaultViewport = util_js_1.DEFAULT_VIEWPORT, downloadBehavior, slowMo = 0, timeout = 3e4, waitForInitialPage = true, protocolTimeout, handleDevToolsAsPage, idGenerator = (0, incremental_id_generator_js_1.createIncrementalIdGenerator)() } = options;
        let { protocol } = options;
        if (this.#browser === "firefox" && protocol === void 0) {
          protocol = "webDriverBiDi";
        }
        if (this.#browser === "firefox" && protocol === "cdp") {
          throw new Error("Connecting to Firefox using CDP is no longer supported");
        }
        const launchArgs = await this.computeLaunchArguments({
          ...options,
          protocol
        });
        if (!(0, node_fs_1.existsSync)(launchArgs.executablePath)) {
          throw new Error(`Browser was not found at the configured executablePath (${launchArgs.executablePath})`);
        }
        const usePipe = launchArgs.args.includes("--remote-debugging-pipe");
        const onProcessExit = async () => {
          await this.cleanUserDataDir(launchArgs.userDataDir, {
            isTemp: launchArgs.isTempUserDataDir
          });
        };
        if (this.#browser === "firefox" && protocol === "webDriverBiDi" && usePipe) {
          throw new Error("Pipe connections are not supported with Firefox and WebDriver BiDi");
        }
        const browserProcess = (0, browsers_1.launch)({
          executablePath: launchArgs.executablePath,
          args: launchArgs.args,
          handleSIGHUP,
          handleSIGTERM,
          handleSIGINT,
          dumpio,
          env: env2,
          pipe: usePipe,
          onExit: onProcessExit,
          signal: options.signal
        });
        let browser;
        let cdpConnection;
        let closing = false;
        const browserCloseCallback = async () => {
          if (closing) {
            return;
          }
          closing = true;
          await this.closeBrowser(browserProcess, cdpConnection);
        };
        try {
          if (this.#browser === "firefox") {
            browser = await this.createBiDiBrowser(browserProcess, browserCloseCallback, {
              timeout,
              protocolTimeout,
              slowMo,
              defaultViewport,
              acceptInsecureCerts,
              networkEnabled,
              idGenerator
            });
          } else {
            if (usePipe) {
              cdpConnection = await this.createCdpPipeConnection(browserProcess, {
                timeout,
                protocolTimeout,
                slowMo,
                idGenerator
              });
            } else {
              cdpConnection = await this.createCdpSocketConnection(browserProcess, {
                timeout,
                protocolTimeout,
                slowMo,
                idGenerator
              });
            }
            if (protocol === "webDriverBiDi") {
              browser = await this.createBiDiOverCdpBrowser(browserProcess, cdpConnection, browserCloseCallback, {
                defaultViewport,
                acceptInsecureCerts,
                networkEnabled
              });
            } else {
              browser = await Browser_js_1.CdpBrowser._create(cdpConnection, [], acceptInsecureCerts, defaultViewport, downloadBehavior, browserProcess.nodeProcess, browserCloseCallback, options.targetFilter, void 0, void 0, networkEnabled, handleDevToolsAsPage);
            }
          }
        } catch (error) {
          void browserCloseCallback();
          const logs = browserProcess.getRecentLogs().join("\n");
          if (logs.includes("Failed to create a ProcessSingleton for your profile directory") || // On Windows we will not get logs due to the singleton process
          // handover. See
          // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/process_singleton_win.cc;l=46;drc=fc7952f0422b5073515a205a04ec9c3a1ae81658
          process.platform === "win32" && (0, node_fs_1.existsSync)((0, node_path_1.join)(launchArgs.userDataDir, "lockfile"))) {
            throw new Error(`The browser is already running for ${launchArgs.userDataDir}. Use a different \`userDataDir\` or stop the running browser first.`);
          }
          if (logs.includes("Missing X server") && options.headless === false) {
            throw new Error(`Missing X server to start the headful browser. Either set headless to true or use xvfb-run to run your Puppeteer script.`);
          }
          if (error instanceof browsers_1.TimeoutError) {
            throw new Errors_js_1.TimeoutError(error.message);
          }
          throw error;
        }
        if (Array.isArray(enableExtensions)) {
          if (this.#browser === "chrome" && !usePipe) {
            throw new Error("To use `enableExtensions` with a list of paths in Chrome, you must be connected with `--remote-debugging-pipe` (`pipe: true`).");
          }
          await Promise.all([
            enableExtensions.map((path2) => {
              return browser.installExtension(path2);
            })
          ]);
        }
        if (waitForInitialPage) {
          await this.waitForPageTarget(browser, timeout);
        }
        return browser;
      }
      /**
       * @internal
       */
      async closeBrowser(browserProcess, cdpConnection) {
        if (cdpConnection) {
          try {
            await cdpConnection.closeBrowser();
            await browserProcess.hasClosed();
          } catch (error) {
            (0, util_js_1.debugError)(error);
            await browserProcess.close();
          }
        } else {
          await (0, rxjs_js_1.firstValueFrom)((0, rxjs_js_1.race)((0, rxjs_js_1.from)(browserProcess.hasClosed()), (0, rxjs_js_1.timer)(5e3).pipe((0, rxjs_js_1.map)(() => {
            return (0, rxjs_js_1.from)(browserProcess.close());
          }))));
        }
      }
      /**
       * @internal
       */
      async waitForPageTarget(browser, timeout) {
        try {
          await browser.waitForTarget((t) => {
            return t.type() === "page";
          }, { timeout });
        } catch (error) {
          await browser.close();
          throw error;
        }
      }
      /**
       * @internal
       */
      async createCdpSocketConnection(browserProcess, opts) {
        const browserWSEndpoint = await browserProcess.waitForLineOutput(browsers_1.CDP_WEBSOCKET_ENDPOINT_REGEX, opts.timeout);
        const transport = await NodeWebSocketTransport_js_1.NodeWebSocketTransport.create(browserWSEndpoint);
        return new Connection_js_1.Connection(
          browserWSEndpoint,
          transport,
          opts.slowMo,
          opts.protocolTimeout,
          /* rawErrors */
          false,
          opts.idGenerator
        );
      }
      /**
       * @internal
       */
      async createCdpPipeConnection(browserProcess, opts) {
        const { 3: pipeWrite, 4: pipeRead } = browserProcess.nodeProcess.stdio;
        const transport = new PipeTransport_js_1.PipeTransport(pipeWrite, pipeRead);
        return new Connection_js_1.Connection(
          "",
          transport,
          opts.slowMo,
          opts.protocolTimeout,
          /* rawErrors */
          false,
          opts.idGenerator
        );
      }
      /**
       * @internal
       */
      async createBiDiOverCdpBrowser(browserProcess, cdpConnection, closeCallback, opts) {
        const bidiOnly = process.env["PUPPETEER_WEBDRIVER_BIDI_ONLY"] === "true";
        const BiDi = await Promise.resolve().then(() => __importStar2(require_bidi()));
        const bidiConnection = await BiDi.connectBidiOverCdp(cdpConnection);
        return await BiDi.BidiBrowser.create({
          connection: bidiConnection,
          // Do not provide CDP connection to Browser, if BiDi-only mode is enabled. This
          // would restrict Browser to use only BiDi endpoint.
          cdpConnection: bidiOnly ? void 0 : cdpConnection,
          closeCallback,
          process: browserProcess.nodeProcess,
          defaultViewport: opts.defaultViewport,
          acceptInsecureCerts: opts.acceptInsecureCerts,
          networkEnabled: opts.networkEnabled
        });
      }
      /**
       * @internal
       */
      async createBiDiBrowser(browserProcess, closeCallback, opts) {
        const browserWSEndpoint = await browserProcess.waitForLineOutput(browsers_1.WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX, opts.timeout) + "/session";
        const transport = await NodeWebSocketTransport_js_1.NodeWebSocketTransport.create(browserWSEndpoint);
        const BiDi = await Promise.resolve().then(() => __importStar2(require_bidi()));
        const bidiConnection = new BiDi.BidiConnection(browserWSEndpoint, transport, opts.idGenerator, opts.slowMo, opts.protocolTimeout);
        return await BiDi.BidiBrowser.create({
          connection: bidiConnection,
          closeCallback,
          process: browserProcess.nodeProcess,
          defaultViewport: opts.defaultViewport,
          acceptInsecureCerts: opts.acceptInsecureCerts,
          networkEnabled: opts.networkEnabled ?? true
        });
      }
      /**
       * @internal
       */
      getProfilePath() {
        return (0, node_path_1.join)(this.puppeteer.configuration.temporaryDirectory ?? (0, node_os_1.tmpdir)(), `puppeteer_dev_${this.browser}_profile-`);
      }
      /**
       * @internal
       */
      resolveExecutablePath(headless, validatePath = true) {
        let executablePath = this.puppeteer.configuration.executablePath;
        if (executablePath) {
          if (validatePath && !(0, node_fs_1.existsSync)(executablePath)) {
            throw new Error(`Tried to find the browser at the configured path (${executablePath}), but no executable was found.`);
          }
          return executablePath;
        }
        function puppeteerBrowserToInstalledBrowser(browser, headless2) {
          switch (browser) {
            case "chrome":
              if (headless2 === "shell") {
                return browsers_1.Browser.CHROMEHEADLESSSHELL;
              }
              return browsers_1.Browser.CHROME;
            case "firefox":
              return browsers_1.Browser.FIREFOX;
          }
          return browsers_1.Browser.CHROME;
        }
        const browserType = puppeteerBrowserToInstalledBrowser(this.browser, headless);
        executablePath = (0, browsers_1.computeExecutablePath)({
          cacheDir: this.puppeteer.defaultDownloadPath,
          browser: browserType,
          buildId: this.puppeteer.browserVersion
        });
        if (validatePath && !(0, node_fs_1.existsSync)(executablePath)) {
          const configVersion = this.puppeteer.configuration?.[this.browser]?.version;
          if (configVersion) {
            throw new Error(`Tried to find the browser at the configured path (${executablePath}) for version ${configVersion}, but no executable was found.`);
          }
          switch (this.browser) {
            case "chrome":
              throw new Error(`Could not find Chrome (ver. ${this.puppeteer.browserVersion}). This can occur if either
 1. you did not perform an installation before running the script (e.g. \`npx puppeteer browsers install ${browserType}\`) or
 2. your cache path is incorrectly configured (which is: ${this.puppeteer.configuration.cacheDirectory}).
For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides/configuration.`);
            case "firefox":
              throw new Error(`Could not find Firefox (rev. ${this.puppeteer.browserVersion}). This can occur if either
 1. you did not perform an installation for Firefox before running the script (e.g. \`npx puppeteer browsers install firefox\`) or
 2. your cache path is incorrectly configured (which is: ${this.puppeteer.configuration.cacheDirectory}).
For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides/configuration.`);
          }
        }
        return executablePath;
      }
    };
    exports2.BrowserLauncher = BrowserLauncher;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/node/util/fs.js
var require_fs = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/node/util/fs.js"(exports2) {
    "use strict";
    init_prefix();
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.rm = rm;
    exports2.rmSync = rmSync;
    var node_fs_1 = __importDefault2(require("node:fs"));
    var rmOptions = {
      force: true,
      recursive: true,
      maxRetries: 5
    };
    async function rm(path2) {
      await node_fs_1.default.promises.rm(path2, rmOptions);
    }
    function rmSync(path2) {
      node_fs_1.default.rmSync(path2, rmOptions);
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/node/ChromeLauncher.js
var require_ChromeLauncher = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/node/ChromeLauncher.js"(exports2) {
    "use strict";
    init_prefix();
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ChromeLauncher = void 0;
    exports2.getFeatures = getFeatures;
    exports2.removeMatchingFlags = removeMatchingFlags;
    var promises_1 = require("node:fs/promises");
    var node_os_1 = __importDefault2(require("node:os"));
    var node_path_1 = __importDefault2(require("node:path"));
    var browsers_1 = require_main2();
    var util_js_1 = require_util();
    var assert_js_1 = require_assert();
    var BrowserLauncher_js_1 = require_BrowserLauncher();
    var LaunchOptions_js_1 = require_LaunchOptions();
    var fs_js_1 = require_fs();
    var ChromeLauncher = class extends BrowserLauncher_js_1.BrowserLauncher {
      constructor(puppeteer) {
        super(puppeteer, "chrome");
      }
      launch(options = {}) {
        if (this.puppeteer.configuration.logLevel === "warn" && process.platform === "darwin" && process.arch === "x64") {
          const cpus = node_os_1.default.cpus();
          if (cpus[0]?.model.includes("Apple")) {
            console.warn([
              "\x1B[1m\x1B[43m\x1B[30m",
              "Degraded performance warning:\x1B[0m\x1B[33m",
              "Launching Chrome on Mac Silicon (arm64) from an x64 Node installation results in",
              "Rosetta translating the Chrome binary, even if Chrome is already arm64. This would",
              "result in huge performance issues. To resolve this, you must run Puppeteer with",
              "a version of Node built for arm64."
            ].join("\n  "));
          }
        }
        return super.launch(options);
      }
      /**
       * @internal
       */
      async computeLaunchArguments(options = {}) {
        const { ignoreDefaultArgs = false, args: args2 = [], pipe = false, debuggingPort, channel, executablePath } = options;
        const chromeArguments = [];
        if (!ignoreDefaultArgs) {
          chromeArguments.push(...this.defaultArgs(options));
        } else if (Array.isArray(ignoreDefaultArgs)) {
          chromeArguments.push(...this.defaultArgs(options).filter((arg) => {
            return !ignoreDefaultArgs.includes(arg);
          }));
        } else {
          chromeArguments.push(...args2);
        }
        if (!chromeArguments.some((argument) => {
          return argument.startsWith("--remote-debugging-");
        })) {
          if (pipe) {
            (0, assert_js_1.assert)(!debuggingPort, "Browser should be launched with either pipe or debugging port - not both.");
            chromeArguments.push("--remote-debugging-pipe");
          } else {
            chromeArguments.push(`--remote-debugging-port=${debuggingPort || 0}`);
          }
        }
        let isTempUserDataDir = false;
        let userDataDirIndex = chromeArguments.findIndex((arg) => {
          return arg.startsWith("--user-data-dir");
        });
        if (userDataDirIndex < 0) {
          isTempUserDataDir = true;
          chromeArguments.push(`--user-data-dir=${await (0, promises_1.mkdtemp)(this.getProfilePath())}`);
          userDataDirIndex = chromeArguments.length - 1;
        }
        const userDataDir = chromeArguments[userDataDirIndex].split("=", 2)[1];
        (0, assert_js_1.assert)(typeof userDataDir === "string", "`--user-data-dir` is malformed");
        let chromeExecutable = executablePath;
        if (!chromeExecutable) {
          (0, assert_js_1.assert)(channel || !this.puppeteer._isPuppeteerCore, `An \`executablePath\` or \`channel\` must be specified for \`puppeteer-core\``);
          chromeExecutable = channel ? this.executablePath(channel) : this.resolveExecutablePath(options.headless ?? true);
        }
        return {
          executablePath: chromeExecutable,
          args: chromeArguments,
          isTempUserDataDir,
          userDataDir
        };
      }
      /**
       * @internal
       */
      async cleanUserDataDir(path2, opts) {
        if (opts.isTemp) {
          try {
            await (0, fs_js_1.rm)(path2);
          } catch (error) {
            (0, util_js_1.debugError)(error);
            throw error;
          }
        }
      }
      defaultArgs(options = {}) {
        const userDisabledFeatures = getFeatures("--disable-features", options.args);
        if (options.args && userDisabledFeatures.length > 0) {
          removeMatchingFlags(options.args, "--disable-features");
        }
        const turnOnExperimentalFeaturesForTesting = process.env["PUPPETEER_TEST_EXPERIMENTAL_CHROME_FEATURES"] === "true";
        const disabledFeatures = [
          "Translate",
          // AcceptCHFrame disabled because of crbug.com/1348106.
          "AcceptCHFrame",
          "MediaRouter",
          "OptimizationHints",
          "RenderDocument",
          // https://crbug.com/444150315
          "PartitionAllocSchedulerLoopQuarantineTaskControlledPurge",
          // https://crbug.com/489314676
          ...turnOnExperimentalFeaturesForTesting ? [] : [
            // https://crbug.com/1492053
            "ProcessPerSiteUpToMainFrameThreshold",
            // https://github.com/puppeteer/puppeteer/issues/10715
            "IsolateSandboxedIframes"
          ],
          ...userDisabledFeatures
        ].filter((feature) => {
          return feature !== "";
        });
        const userEnabledFeatures = getFeatures("--enable-features", options.args);
        if (options.args && userEnabledFeatures.length > 0) {
          removeMatchingFlags(options.args, "--enable-features");
        }
        const enabledFeatures = [
          "PdfOopif",
          // Add features to enable by default here.
          ...userEnabledFeatures
        ].filter((feature) => {
          return feature !== "";
        });
        const chromeArguments = [
          "--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(",")}`,
          `--enable-features=${enabledFeatures.join(",")}`
        ].filter((arg) => {
          return arg !== "";
        });
        const { devtools = false, headless = !devtools, args: args2 = [], userDataDir, enableExtensions = false } = options;
        if (process.env["PUPPETEER_DANGEROUS_NO_SANDBOX"] === "true" && !args2.includes("--no-sandbox")) {
          chromeArguments.push("--no-sandbox");
        }
        if (userDataDir) {
          chromeArguments.push(`--user-data-dir=${node_path_1.default.posix.isAbsolute(userDataDir) || node_path_1.default.win32.isAbsolute(userDataDir) ? userDataDir : node_path_1.default.resolve(userDataDir)}`);
        }
        if (devtools) {
          chromeArguments.push("--auto-open-devtools-for-tabs");
        }
        if (headless) {
          chromeArguments.push(headless === "shell" ? "--headless" : "--headless=new", "--hide-scrollbars", "--mute-audio");
        }
        chromeArguments.push(enableExtensions ? "--enable-unsafe-extension-debugging" : "--disable-extensions");
        if (args2.every((arg) => {
          return arg.startsWith("-");
        })) {
          chromeArguments.push("about:blank");
        }
        chromeArguments.push(...args2);
        return chromeArguments;
      }
      executablePath(channel, validatePath = true) {
        if (channel) {
          return (0, browsers_1.computeSystemExecutablePath)({
            browser: browsers_1.Browser.CHROME,
            channel: (0, LaunchOptions_js_1.convertPuppeteerChannelToBrowsersChannel)(channel)
          });
        } else {
          return this.resolveExecutablePath(void 0, validatePath);
        }
      }
    };
    exports2.ChromeLauncher = ChromeLauncher;
    function getFeatures(flag, options = []) {
      return options.filter((s) => {
        return s.startsWith(flag.endsWith("=") ? flag : `${flag}=`);
      }).map((s) => {
        return s.split(new RegExp(`${flag}=\\s*`))[1]?.trim();
      }).filter((s) => {
        return s;
      });
    }
    function removeMatchingFlags(array, flag) {
      const regex = new RegExp(`^${flag}=.*`);
      let i = 0;
      while (i < array.length) {
        if (regex.test(array[i])) {
          array.splice(i, 1);
        } else {
          i++;
        }
      }
      return array;
    }
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/node/FirefoxLauncher.js
var require_FirefoxLauncher = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/node/FirefoxLauncher.js"(exports2) {
    "use strict";
    init_prefix();
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.FirefoxLauncher = void 0;
    var node_fs_1 = __importDefault2(require("node:fs"));
    var promises_1 = require("node:fs/promises");
    var node_os_1 = __importDefault2(require("node:os"));
    var node_path_1 = __importDefault2(require("node:path"));
    var browsers_1 = require_main2();
    var util_js_1 = require_util();
    var assert_js_1 = require_assert();
    var BrowserLauncher_js_1 = require_BrowserLauncher();
    var fs_js_1 = require_fs();
    var FirefoxLauncher = class _FirefoxLauncher extends BrowserLauncher_js_1.BrowserLauncher {
      constructor(puppeteer) {
        super(puppeteer, "firefox");
      }
      static getPreferences(extraPrefsFirefox) {
        return {
          ...extraPrefsFirefox,
          // Force all web content to use a single content process. TODO: remove
          // this once Firefox supports mouse event dispatch from the main frame
          // context. See https://bugzilla.mozilla.org/show_bug.cgi?id=1773393.
          "fission.webContentIsolationStrategy": 0
        };
      }
      /**
       * @internal
       */
      async computeLaunchArguments(options = {}) {
        const { ignoreDefaultArgs = false, args: args2 = [], executablePath, pipe = false, extraPrefsFirefox = {}, debuggingPort = null } = options;
        const firefoxArguments = [];
        if (!ignoreDefaultArgs) {
          firefoxArguments.push(...this.defaultArgs(options));
        } else if (Array.isArray(ignoreDefaultArgs)) {
          firefoxArguments.push(...this.defaultArgs(options).filter((arg) => {
            return !ignoreDefaultArgs.includes(arg);
          }));
        } else {
          firefoxArguments.push(...args2);
        }
        if (!firefoxArguments.some((argument) => {
          return argument.startsWith("--remote-debugging-");
        })) {
          if (pipe) {
            (0, assert_js_1.assert)(debuggingPort === null, "Browser should be launched with either pipe or debugging port - not both.");
          }
          firefoxArguments.push(`--remote-debugging-port=${debuggingPort || 0}`);
        }
        let userDataDir;
        let isTempUserDataDir = true;
        const profileArgIndex = firefoxArguments.findIndex((arg) => {
          return ["-profile", "--profile"].includes(arg);
        });
        if (profileArgIndex !== -1) {
          userDataDir = firefoxArguments[profileArgIndex + 1];
          if (!userDataDir) {
            throw new Error(`Missing value for profile command line argument`);
          }
          isTempUserDataDir = false;
        } else {
          userDataDir = await (0, promises_1.mkdtemp)(this.getProfilePath());
          firefoxArguments.push("--profile");
          firefoxArguments.push(userDataDir);
        }
        await (0, browsers_1.createProfile)(browsers_1.Browser.FIREFOX, {
          path: userDataDir,
          preferences: _FirefoxLauncher.getPreferences(extraPrefsFirefox)
        });
        let firefoxExecutable;
        if (this.puppeteer._isPuppeteerCore || executablePath) {
          (0, assert_js_1.assert)(executablePath, `An \`executablePath\` must be specified for \`puppeteer-core\``);
          firefoxExecutable = executablePath;
        } else {
          firefoxExecutable = this.executablePath(void 0);
        }
        return {
          isTempUserDataDir,
          userDataDir,
          args: firefoxArguments,
          executablePath: firefoxExecutable
        };
      }
      /**
       * @internal
       */
      async cleanUserDataDir(userDataDir, opts) {
        if (opts.isTemp) {
          try {
            await (0, fs_js_1.rm)(userDataDir);
          } catch (error) {
            (0, util_js_1.debugError)(error);
            throw error;
          }
        } else {
          try {
            const backupSuffix = ".puppeteer";
            const backupFiles = ["prefs.js", "user.js"];
            const results = await Promise.allSettled(backupFiles.map(async (file) => {
              const prefsBackupPath = node_path_1.default.join(userDataDir, file + backupSuffix);
              if (node_fs_1.default.existsSync(prefsBackupPath)) {
                const prefsPath = node_path_1.default.join(userDataDir, file);
                await (0, promises_1.unlink)(prefsPath);
                await (0, promises_1.rename)(prefsBackupPath, prefsPath);
              }
            }));
            for (const result of results) {
              if (result.status === "rejected") {
                throw result.reason;
              }
            }
          } catch (error) {
            (0, util_js_1.debugError)(error);
          }
        }
      }
      executablePath(_, validatePath = true) {
        return this.resolveExecutablePath(
          void 0,
          /* validatePath=*/
          validatePath
        );
      }
      defaultArgs(options = {}) {
        const { devtools = false, headless = !devtools, args: args2 = [], userDataDir = null } = options;
        const firefoxArguments = [];
        switch (node_os_1.default.platform()) {
          case "darwin":
            firefoxArguments.push("--foreground");
            break;
          case "win32":
            firefoxArguments.push("--wait-for-browser");
            break;
        }
        if (userDataDir) {
          firefoxArguments.push("--profile");
          firefoxArguments.push(userDataDir);
        }
        if (headless) {
          firefoxArguments.push("--headless");
        }
        if (devtools) {
          firefoxArguments.push("--devtools");
        }
        if (args2.every((arg) => {
          return arg.startsWith("-");
        })) {
          firefoxArguments.push("about:blank");
        }
        firefoxArguments.push(...args2);
        return firefoxArguments;
      }
    };
    exports2.FirefoxLauncher = FirefoxLauncher;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/node/PuppeteerNode.js
var require_PuppeteerNode = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/node/PuppeteerNode.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PuppeteerNode = void 0;
    var browsers_1 = require_main2();
    var Puppeteer_js_1 = require_Puppeteer();
    var revisions_js_1 = require_revisions();
    var ChromeLauncher_js_1 = require_ChromeLauncher();
    var FirefoxLauncher_js_1 = require_FirefoxLauncher();
    var PuppeteerNode = class extends Puppeteer_js_1.Puppeteer {
      #launcher;
      #lastLaunchedBrowser;
      /**
       * @internal
       */
      defaultBrowserRevision;
      /**
       * @internal
       */
      configuration = {};
      /**
       * @internal
       */
      constructor(settings) {
        const { configuration, ...commonSettings } = settings;
        super(commonSettings);
        if (configuration) {
          this.configuration = configuration;
        }
        switch (this.configuration.defaultBrowser) {
          case "firefox":
            this.defaultBrowserRevision = revisions_js_1.PUPPETEER_REVISIONS.firefox;
            break;
          default:
            this.configuration.defaultBrowser = "chrome";
            this.defaultBrowserRevision = revisions_js_1.PUPPETEER_REVISIONS.chrome;
            break;
        }
        this.connect = this.connect.bind(this);
        this.launch = this.launch.bind(this);
        this.executablePath = this.executablePath.bind(this);
        this.defaultArgs = this.defaultArgs.bind(this);
        this.trimCache = this.trimCache.bind(this);
      }
      /**
       * This method attaches Puppeteer to an existing browser instance.
       *
       * @param options - Set of configurable options to set on the browser.
       * @returns Promise which resolves to browser instance.
       */
      connect(options) {
        return super.connect(options);
      }
      /**
       * Launches a browser instance with given arguments and options when
       * specified.
       *
       * When using with `puppeteer-core`,
       * {@link LaunchOptions.executablePath | options.executablePath} or
       * {@link LaunchOptions.channel | options.channel} must be provided.
       *
       * @example
       * You can use {@link LaunchOptions.ignoreDefaultArgs | options.ignoreDefaultArgs}
       * to filter out `--mute-audio` from default arguments:
       *
       * ```ts
       * const browser = await puppeteer.launch({
       *   ignoreDefaultArgs: ['--mute-audio'],
       * });
       * ```
       *
       * @remarks
       * Puppeteer can also be used to control the Chrome browser, but it works best
       * with the version of Chrome for Testing downloaded by default.
       * There is no guarantee it will work with any other version. If Google Chrome
       * (rather than Chrome for Testing) is preferred, a
       * {@link https://www.google.com/chrome/browser/canary.html | Chrome Canary}
       * or
       * {@link https://www.chromium.org/getting-involved/dev-channel | Dev Channel}
       * build is suggested. See
       * {@link https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/ | this article}
       * for a description of the differences between Chromium and Chrome.
       * {@link https://chromium.googlesource.com/chromium/src/+/lkgr/docs/chromium_browser_vs_google_chrome.md | This article}
       * describes some differences for Linux users. See
       * {@link https://developer.chrome.com/blog/chrome-for-testing/ | this doc} for the description
       * of Chrome for Testing.
       *
       * @param options - Options to configure launching behavior.
       */
      launch(options = {}) {
        const { browser = this.defaultBrowser } = options;
        this.#lastLaunchedBrowser = browser;
        switch (browser) {
          case "chrome":
            this.defaultBrowserRevision = revisions_js_1.PUPPETEER_REVISIONS.chrome;
            break;
          case "firefox":
            this.defaultBrowserRevision = revisions_js_1.PUPPETEER_REVISIONS.firefox;
            break;
          default:
            throw new Error(`Unknown product: ${browser}`);
        }
        this.#launcher = this.#getLauncher(browser);
        return this.#launcher.launch(options);
      }
      /**
       * @internal
       */
      #getLauncher(browser) {
        if (this.#launcher && this.#launcher.browser === browser) {
          return this.#launcher;
        }
        switch (browser) {
          case "chrome":
            return new ChromeLauncher_js_1.ChromeLauncher(this);
          case "firefox":
            return new FirefoxLauncher_js_1.FirefoxLauncher(this);
          default:
            throw new Error(`Unknown product: ${browser}`);
        }
      }
      executablePath(optsOrChannel) {
        if (optsOrChannel === void 0) {
          return this.#getLauncher(this.lastLaunchedBrowser).executablePath(
            void 0,
            /* validatePath= */
            false
          );
        }
        if (typeof optsOrChannel === "string") {
          return this.#getLauncher("chrome").executablePath(
            optsOrChannel,
            /* validatePath= */
            false
          );
        }
        return this.#getLauncher(optsOrChannel.browser ?? this.lastLaunchedBrowser).resolveExecutablePath(
          optsOrChannel.headless,
          /* validatePath= */
          false
        );
      }
      /**
       * @internal
       */
      get browserVersion() {
        return this.configuration?.[this.lastLaunchedBrowser]?.version ?? this.defaultBrowserRevision;
      }
      /**
       * The default download path for puppeteer. For puppeteer-core, this
       * code should never be called as it is never defined.
       *
       * @internal
       */
      get defaultDownloadPath() {
        return this.configuration.cacheDirectory;
      }
      /**
       * The name of the browser that was last launched.
       */
      get lastLaunchedBrowser() {
        return this.#lastLaunchedBrowser ?? this.defaultBrowser;
      }
      /**
       * The name of the browser that will be launched by default. For
       * `puppeteer`, this is influenced by your configuration. Otherwise, it's
       * `chrome`.
       */
      get defaultBrowser() {
        return this.configuration.defaultBrowser ?? "chrome";
      }
      /**
       * @deprecated Do not use as this field as it does not take into account
       * multiple browsers of different types. Use
       * {@link PuppeteerNode.defaultBrowser | defaultBrowser} or
       * {@link PuppeteerNode.lastLaunchedBrowser | lastLaunchedBrowser}.
       *
       * @returns The name of the browser that is under automation.
       */
      get product() {
        return this.lastLaunchedBrowser;
      }
      /**
       * @param options - Set of configurable options to set on the browser.
       *
       * @returns The default arguments that the browser will be launched with.
       */
      defaultArgs(options = {}) {
        return this.#getLauncher(options.browser ?? this.lastLaunchedBrowser).defaultArgs(options);
      }
      /**
       * Removes all non-current Firefox and Chrome binaries in the cache directory
       * identified by the provided Puppeteer configuration. The current browser
       * version is determined by resolving PUPPETEER_REVISIONS from Puppeteer
       * unless `configuration.browserRevision` is provided.
       *
       * @remarks
       *
       * Note that the method does not check if any other Puppeteer versions
       * installed on the host that use the same cache directory require the
       * non-current binaries.
       *
       * @public
       */
      async trimCache() {
        const platform = (0, browsers_1.detectBrowserPlatform)();
        if (!platform) {
          throw new Error("The current platform is not supported.");
        }
        const cacheDir = this.configuration.cacheDirectory;
        const installedBrowsers = await (0, browsers_1.getInstalledBrowsers)({
          cacheDir
        });
        const puppeteerBrowsers = [
          {
            product: "chrome",
            browser: browsers_1.Browser.CHROME,
            currentBuildId: ""
          },
          {
            product: "firefox",
            browser: browsers_1.Browser.FIREFOX,
            currentBuildId: ""
          }
        ];
        await Promise.all(puppeteerBrowsers.map(async (item) => {
          const tag = this.configuration?.[item.product]?.version ?? revisions_js_1.PUPPETEER_REVISIONS[item.product];
          item.currentBuildId = await (0, browsers_1.resolveBuildId)(item.browser, platform, tag);
        }));
        const currentBrowserBuilds = new Set(puppeteerBrowsers.map((browser) => {
          return `${browser.browser}_${browser.currentBuildId}`;
        }));
        const currentBrowsers = new Set(puppeteerBrowsers.map((browser) => {
          return browser.browser;
        }));
        for (const installedBrowser of installedBrowsers) {
          if (!currentBrowsers.has(installedBrowser.browser)) {
            continue;
          }
          if (currentBrowserBuilds.has(`${installedBrowser.browser}_${installedBrowser.buildId}`)) {
            continue;
          }
          await (0, browsers_1.uninstall)({
            browser: installedBrowser.browser,
            platform,
            cacheDir,
            buildId: installedBrowser.buildId
          });
        }
      }
    };
    exports2.PuppeteerNode = PuppeteerNode;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/node/ScreenRecorder.js
var require_ScreenRecorder = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/node/ScreenRecorder.js"(exports2) {
    "use strict";
    init_prefix();
    var __runInitializers2 = exports2 && exports2.__runInitializers || function(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;
    };
    var __esDecorate2 = exports2 && exports2.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var 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 (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    var __setFunctionName2 = exports2 && exports2.__setFunctionName || function(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 });
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ScreenRecorder = void 0;
    var node_child_process_1 = require("node:child_process");
    var node_fs_1 = __importDefault2(require("node:fs"));
    var node_os_1 = __importDefault2(require("node:os"));
    var node_path_1 = require("node:path");
    var node_stream_1 = require("node:stream");
    var debug_1 = __importDefault2(require_src());
    var rxjs_js_1 = require_rxjs();
    var CDPSession_js_1 = require_CDPSession();
    var util_js_1 = require_util();
    var decorators_js_1 = require_decorators();
    var disposable_js_1 = require_disposable();
    var CRF_VALUE = 30;
    var DEFAULT_FPS = 30;
    var debugFfmpeg = (0, debug_1.default)("puppeteer:ffmpeg");
    var ScreenRecorder = (() => {
      let _classSuper = node_stream_1.PassThrough;
      let _instanceExtraInitializers = [];
      let _private_writeFrame_decorators;
      let _private_writeFrame_descriptor;
      let _stop_decorators;
      return class ScreenRecorder extends _classSuper {
        static {
          const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
          __esDecorate2(this, _private_writeFrame_descriptor = { value: __setFunctionName2(async function(buffer) {
            const error = await new Promise((resolve5) => {
              this.#process.stdin.write(buffer, resolve5);
            });
            if (error) {
              console.log(`ffmpeg failed to write: ${error.message}.`);
            }
          }, "#writeFrame") }, _private_writeFrame_decorators, { kind: "method", name: "#writeFrame", static: false, private: true, access: { has: (obj) => #writeFrame in obj, get: (obj) => obj.#writeFrame }, metadata: _metadata }, null, _instanceExtraInitializers);
          __esDecorate2(this, null, _stop_decorators, { kind: "method", name: "stop", static: false, private: false, access: { has: (obj) => "stop" in obj, get: (obj) => obj.stop }, metadata: _metadata }, null, _instanceExtraInitializers);
          if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #page = __runInitializers2(this, _instanceExtraInitializers);
        #process;
        #controller = new AbortController();
        #lastFrame;
        #fps;
        /**
         * @internal
         */
        constructor(page2, width, height, { ffmpegPath, speed, scale, crop, format: format3, fps, loop, delay, quality, colors, path: path2, overwrite } = {}) {
          super({ allowHalfOpen: false });
          ffmpegPath ??= "ffmpeg";
          format3 ??= "webm";
          fps ??= DEFAULT_FPS;
          loop ||= -1;
          delay ??= -1;
          quality ??= CRF_VALUE;
          colors ??= 256;
          overwrite ??= true;
          this.#fps = fps;
          const { error } = (0, node_child_process_1.spawnSync)(ffmpegPath);
          if (error) {
            throw error;
          }
          const filters = [
            `crop='min(${width},iw):min(${height},ih):0:0'`,
            `pad=${width}:${height}:0:0`
          ];
          if (speed) {
            filters.push(`setpts=${1 / speed}*PTS`);
          }
          if (crop) {
            filters.push(`crop=${crop.width}:${crop.height}:${crop.x}:${crop.y}`);
          }
          if (scale) {
            filters.push(`scale=iw*${scale}:-1:flags=lanczos`);
          }
          const formatArgs = this.#getFormatArgs(format3, fps, loop, delay, quality, colors);
          const vf = formatArgs.indexOf("-vf");
          if (vf !== -1) {
            filters.push(formatArgs.splice(vf, 2).at(-1) ?? "");
          }
          if (path2) {
            node_fs_1.default.mkdirSync((0, node_path_1.dirname)(path2), { recursive: overwrite });
          }
          this.#process = (0, node_child_process_1.spawn)(
            ffmpegPath,
            // See https://trac.ffmpeg.org/wiki/Encode/VP9 for more information on flags.
            [
              ["-loglevel", "error"],
              // Reduces general buffering.
              ["-avioflags", "direct"],
              // Reduces initial buffering while analyzing input fps and other stats.
              [
                "-fpsprobesize",
                "0",
                "-probesize",
                "32",
                "-analyzeduration",
                "0",
                "-fflags",
                "nobuffer"
              ],
              // Forces input to be read from standard input, and forces png input
              // image format.
              ["-f", "image2pipe", "-vcodec", "png", "-i", "pipe:0"],
              // No audio
              ["-an"],
              // This drastically reduces stalling when cpu is overbooked. By default
              // VP9 tries to use all available threads?
              ["-threads", "1"],
              // Specifies the frame rate we are giving ffmpeg.
              ["-framerate", `${fps}`],
              // Disable bitrate.
              ["-b:v", "0"],
              // Specifies the encoding and format we are using.
              formatArgs,
              // Filters to ensure the images are piped correctly,
              // combined with any format-specific filters.
              ["-vf", filters.join()],
              // Overwrite output, or exit immediately if file already exists.
              [overwrite ? "-y" : "-n"],
              "pipe:1"
            ].flat(),
            { stdio: ["pipe", "pipe", "pipe"] }
          );
          this.#process.stdout.pipe(this);
          this.#process.stderr.on("data", (data) => {
            debugFfmpeg(data.toString("utf8"));
          });
          this.#page = page2;
          const { client: client2 } = this.#page.mainFrame();
          client2.once(CDPSession_js_1.CDPSessionEvent.Disconnected, () => {
            void this.stop().catch(util_js_1.debugError);
          });
          this.#lastFrame = (0, rxjs_js_1.lastValueFrom)((0, util_js_1.fromEmitterEvent)(client2, "Page.screencastFrame").pipe((0, rxjs_js_1.tap)((event) => {
            void client2.send("Page.screencastFrameAck", {
              sessionId: event.sessionId
            });
          }), (0, rxjs_js_1.filter)((event) => {
            return event.metadata.timestamp !== void 0;
          }), (0, rxjs_js_1.map)((event) => {
            return {
              buffer: Buffer.from(event.data, "base64"),
              timestamp: event.metadata.timestamp
            };
          }), (0, rxjs_js_1.bufferCount)(2, 1), (0, rxjs_js_1.concatMap)(([{ timestamp: previousTimestamp, buffer }, { timestamp }]) => {
            return (0, rxjs_js_1.from)(Array(Math.round(fps * Math.max(timestamp - previousTimestamp, 0))).fill(buffer));
          }), (0, rxjs_js_1.map)((buffer) => {
            void this.#writeFrame(buffer);
            return [buffer, performance.now()];
          }), (0, rxjs_js_1.takeUntil)((0, rxjs_js_1.fromEvent)(this.#controller.signal, "abort"))), { defaultValue: [Buffer.from([]), performance.now()] });
        }
        #getFormatArgs(format3, fps, loop, delay, quality, colors) {
          const libvpx = [
            ["-vcodec", "vp9"],
            // Sets the quality. Lower the better.
            ["-crf", `${quality}`],
            // Sets the quality and how efficient the compression will be.
            [
              "-deadline",
              "realtime",
              "-cpu-used",
              `${Math.min(node_os_1.default.cpus().length / 2, 8)}`
            ]
          ];
          switch (format3) {
            case "webm":
              return [
                ...libvpx,
                // Sets the format
                ["-f", "webm"]
              ].flat();
            case "gif":
              fps = DEFAULT_FPS === fps ? 20 : "source_fps";
              if (loop === Infinity) {
                loop = 0;
              }
              if (delay !== -1) {
                delay /= 10;
              }
              return [
                // Sets the frame rate and uses a custom palette generated from the
                // input.
                [
                  "-vf",
                  `fps=${fps},split[s0][s1];[s0]palettegen=stats_mode=diff:max_colors=${colors}[p];[s1][p]paletteuse=dither=bayer`
                ],
                // Sets the number of times to loop playback.
                ["-loop", `${loop}`],
                // Sets the delay between iterations of a loop.
                ["-final_delay", `${delay}`],
                // Sets the format
                ["-f", "gif"]
              ].flat();
            case "mp4":
              return [
                ...libvpx,
                // Fragment file during stream to avoid errors.
                ["-movflags", "hybrid_fragmented"],
                // Sets the format
                ["-f", "mp4"]
              ].flat();
          }
        }
        get #writeFrame() {
          return _private_writeFrame_descriptor.value;
        }
        /**
         * Stops the recorder.
         *
         * @public
         */
        async stop() {
          if (this.#controller.signal.aborted) {
            return;
          }
          await this.#page._stopScreencast().catch(util_js_1.debugError);
          this.#controller.abort();
          const [buffer, timestamp] = await this.#lastFrame;
          await Promise.all(Array(Math.max(1, Math.round(this.#fps * (performance.now() - timestamp) / 1e3))).fill(buffer).map(this.#writeFrame.bind(this)));
          this.#process.stdin.end();
          await new Promise((resolve5) => {
            this.#process.once("close", resolve5);
          });
        }
        /**
         * @internal
         */
        async [(_private_writeFrame_decorators = [(0, decorators_js_1.guarded)()], _stop_decorators = [(0, decorators_js_1.guarded)()], disposable_js_1.asyncDisposeSymbol)]() {
          await this.stop();
        }
      };
    })();
    exports2.ScreenRecorder = ScreenRecorder;
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/node/node.js
var require_node3 = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/node/node.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    __exportStar2(require_ChromeLauncher(), exports2);
    __exportStar2(require_FirefoxLauncher(), exports2);
    __exportStar2(require_PipeTransport(), exports2);
    __exportStar2(require_BrowserLauncher(), exports2);
    __exportStar2(require_PuppeteerNode(), exports2);
    __exportStar2(require_ScreenRecorder(), exports2);
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/index.js
var require_puppeteer = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/index.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    __exportStar2(require_index_browser(), exports2);
    __exportStar2(require_node3(), exports2);
  }
});

// node_modules/puppeteer-core/lib/cjs/puppeteer/puppeteer-core.js
var require_puppeteer_core = __commonJS({
  "node_modules/puppeteer-core/lib/cjs/puppeteer/puppeteer-core.js"(exports2) {
    "use strict";
    init_prefix();
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, p);
    };
    var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
      var ownKeys2 = function(o) {
        ownKeys2 = 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 ownKeys2(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding2(result, mod, k[i]);
        }
        __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.launch = exports2.executablePath = exports2.defaultArgs = exports2.connect = void 0;
    __exportStar2(require_puppeteer(), exports2);
    var node_fs_1 = __importDefault2(require("node:fs"));
    var node_path_1 = __importDefault2(require("node:path"));
    var environment_js_1 = require_environment();
    var Puppeteer = __importStar2(require_puppeteer());
    environment_js_1.environment.value = {
      fs: node_fs_1.default,
      path: node_path_1.default,
      ScreenRecorder: Puppeteer.ScreenRecorder
    };
    var puppeteer = new Puppeteer.PuppeteerNode({
      isPuppeteerCore: true
    });
    exports2.connect = puppeteer.connect, /**
     * @public
     */
    exports2.defaultArgs = puppeteer.defaultArgs, /**
     * @public
     */
    exports2.executablePath = puppeteer.executablePath, /**
     * @public
     */
    exports2.launch = puppeteer.launch;
    exports2.default = puppeteer;
  }
});

// node_modules/puppeteer-extra/dist/index.cjs.js
var require_index_cjs = __commonJS({
  "node_modules/puppeteer-extra/dist/index.cjs.js"(exports2, module2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    function _interopDefault(ex) {
      return ex && typeof ex === "object" && "default" in ex ? ex["default"] : ex;
    }
    var Debug = _interopDefault(require_src());
    var merge = _interopDefault(require_cjs());
    var debug = Debug("puppeteer-extra");
    var PuppeteerExtra = class {
      constructor(_pptr, _requireError) {
        this._pptr = _pptr;
        this._requireError = _requireError;
        this._plugins = [];
      }
      /**
       * The **main interface** to register `puppeteer-extra` plugins.
       *
       * @example
       * puppeteer.use(plugin1).use(plugin2)
       *
       * @see [PuppeteerExtraPlugin]
       *
       * @return The same `PuppeteerExtra` instance (for optional chaining)
       */
      use(plugin) {
        if (typeof plugin !== "object" || !plugin._isPuppeteerExtraPlugin) {
          console.error(`Warning: Plugin is not derived from PuppeteerExtraPlugin, ignoring.`, plugin);
          return this;
        }
        if (!plugin.name) {
          console.error(`Warning: Plugin with no name registering, ignoring.`, plugin);
          return this;
        }
        if (plugin.requirements.has("dataFromPlugins")) {
          plugin.getDataFromPlugins = this.getPluginData.bind(this);
        }
        plugin._register(Object.getPrototypeOf(plugin));
        this._plugins.push(plugin);
        debug("plugin registered", plugin.name);
        return this;
      }
      /**
       * To stay backwards compatible with puppeteer's (and our) default export after adding `addExtra`
       * we need to defer the check if we have a puppeteer instance to work with.
       * Otherwise we would throw even if the user intends to use their non-standard puppeteer implementation.
       *
       * @private
       */
      get pptr() {
        if (this._pptr) {
          return this._pptr;
        }
        console.warn(`
    Puppeteer is missing. :-)

    Note: puppeteer is a peer dependency of puppeteer-extra,
    which means you can install your own preferred version.

    - To get the latest stable version run: 'yarn add puppeteer' or 'npm i puppeteer'

    Alternatively:
    - To get puppeteer without the bundled Chromium browser install 'puppeteer-core'
    `);
        throw this._requireError || new Error("No puppeteer instance provided.");
      }
      /**
       * The method launches a browser instance with given arguments. The browser will be closed when the parent node.js process is closed.
       *
       * Augments the original `puppeteer.launch` method with plugin lifecycle methods.
       *
       * All registered plugins that have a `beforeLaunch` method will be called
       * in sequence to potentially update the `options` Object before launching the browser.
       *
       * @example
       * const browser = await puppeteer.launch({
       *   headless: false,
       *   defaultViewport: null
       * })
       *
       * @param options - See [puppeteer docs](https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#puppeteerlaunchoptions).
       */
      async launch(options) {
        const defaultLaunchOptions = { args: [] };
        options = merge(defaultLaunchOptions, options || {});
        this.resolvePluginDependencies();
        this.orderPlugins();
        options = await this.callPluginsWithValue("beforeLaunch", options);
        const opts = {
          context: "launch",
          options,
          defaultArgs: this.defaultArgs
        };
        this.checkPluginRequirements(opts);
        const browser = await this.pptr.launch(options);
        this._patchPageCreationMethods(browser);
        await this.callPlugins("_bindBrowserEvents", browser, opts);
        return browser;
      }
      /**
       * Attach Puppeteer to an existing Chromium instance.
       *
       * Augments the original `puppeteer.connect` method with plugin lifecycle methods.
       *
       * All registered plugins that have a `beforeConnect` method will be called
       * in sequence to potentially update the `options` Object before launching the browser.
       *
       * @param options - See [puppeteer docs](https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#puppeteerconnectoptions).
       */
      async connect(options) {
        this.resolvePluginDependencies();
        this.orderPlugins();
        options = await this.callPluginsWithValue("beforeConnect", options);
        const opts = { context: "connect", options };
        this.checkPluginRequirements(opts);
        const browser = await this.pptr.connect(options);
        this._patchPageCreationMethods(browser);
        await this.callPlugins("_bindBrowserEvents", browser, opts);
        return browser;
      }
      /**
       * The default flags that Chromium will be launched with.
       *
       * @param options - See [puppeteer docs](https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#puppeteerdefaultargsoptions).
       */
      defaultArgs(options) {
        return this.pptr.defaultArgs(options);
      }
      /** Path where Puppeteer expects to find bundled Chromium. */
      executablePath() {
        return this.pptr.executablePath();
      }
      /**
       * This methods attaches Puppeteer to an existing Chromium instance.
       *
       * @param options - See [puppeteer docs](https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#puppeteercreatebrowserfetcheroptions).
       */
      createBrowserFetcher(options) {
        return this.pptr.createBrowserFetcher(options);
      }
      /**
       * Patch page creation methods (both regular and incognito contexts).
       *
       * Unfortunately it's possible that the `targetcreated` events are not triggered
       * early enough for listeners (e.g. plugins using `onPageCreated`) to be able to
       * modify the page instance (e.g. user-agent) before the browser request occurs.
       *
       * This only affects the first request of a newly created page target.
       *
       * As a workaround I've noticed that navigating to `about:blank` (again),
       * right after a page has been created reliably fixes this issue and adds
       * no noticable delay or side-effects.
       *
       * This problem is not specific to `puppeteer-extra` but default Puppeteer behaviour.
       *
       * Note: This patch only fixes explicitly created pages, implicitly created ones
       * (e.g. through `window.open`) are still subject to this issue. I didn't find a
       * reliable mitigation for implicitly created pages yet.
       *
       * Puppeteer issues:
       * https://github.com/GoogleChrome/puppeteer/issues/2669
       * https://github.com/puppeteer/puppeteer/issues/3667
       * https://github.com/GoogleChrome/puppeteer/issues/386#issuecomment-343059315
       * https://github.com/GoogleChrome/puppeteer/issues/1378#issue-273733905
       *
       * @private
       */
      _patchPageCreationMethods(browser) {
        if (!browser._createPageInContext) {
          debug("warning: _patchPageCreationMethods failed (no browser._createPageInContext)");
          return;
        }
        browser._createPageInContext = /* @__PURE__ */ (function(originalMethod, context) {
          return async function() {
            const page2 = await originalMethod.apply(context, arguments);
            await page2.goto("about:blank");
            return page2;
          };
        })(browser._createPageInContext, browser);
      }
      /**
       * Get a list of all registered plugins.
       *
       * @member {Array<PuppeteerExtraPlugin>}
       */
      get plugins() {
        return this._plugins;
      }
      /**
       * Get the names of all registered plugins.
       *
       * @member {Array<string>}
       * @private
       */
      get pluginNames() {
        return this._plugins.map((p) => p.name);
      }
      /**
       * Collects the exposed `data` property of all registered plugins.
       * Will be reduced/flattened to a single array.
       *
       * Can be accessed by plugins that listed the `dataFromPlugins` requirement.
       *
       * Implemented mainly for plugins that need data from other plugins (e.g. `user-preferences`).
       *
       * @see [PuppeteerExtraPlugin]/data
       * @param name - Filter data by optional plugin name
       *
       * @private
       */
      getPluginData(name) {
        const data = this._plugins.map((p) => Array.isArray(p.data) ? p.data : [p.data]).reduce((acc, arr) => [...acc, ...arr], []);
        return name ? data.filter((d) => d.name === name) : data;
      }
      /**
       * Get all plugins that feature a given property/class method.
       *
       * @private
       */
      getPluginsByProp(prop) {
        return this._plugins.filter((plugin) => prop in plugin);
      }
      /**
       * Lightweight plugin dependency management to require plugins and code mods on demand.
       *
       * This uses the `dependencies` stanza (a `Set`) exposed by `puppeteer-extra` plugins.
       *
       * @todo Allow objects as depdencies that contains opts for the requested plugin.
       *
       * @private
       */
      resolvePluginDependencies() {
        const missingPlugins = this._plugins.map((p) => p._getMissingDependencies(this._plugins)).reduce((combined, list) => {
          return /* @__PURE__ */ new Set([...combined, ...list]);
        }, /* @__PURE__ */ new Set());
        if (!missingPlugins.size) {
          debug("no dependencies are missing");
          return;
        }
        debug("dependencies missing", missingPlugins);
        for (let name of [...missingPlugins]) {
          if (this.pluginNames.includes(name)) {
            debug(`ignoring dependency '${name}', which has been required already.`);
            continue;
          }
          name = name.startsWith("puppeteer-extra-plugin") ? name : `puppeteer-extra-plugin-${name}`;
          const packageName = name.split("/")[0];
          let dep = null;
          try {
            dep = require(name)();
            this.use(dep);
          } catch (err) {
            console.warn(`
          A plugin listed '${name}' as dependency,
          which is currently missing. Please install it:

          yarn add ${packageName}

          Note: You don't need to require the plugin yourself,
          unless you want to modify it's default settings.
          `);
            throw err;
          }
          if (dep.dependencies.size) {
            this.resolvePluginDependencies();
          }
        }
      }
      /**
       * Order plugins that have expressed a special placement requirement.
       *
       * This is useful/necessary for e.g. plugins that depend on the data from other plugins.
       *
       * @todo Support more than 'runLast'.
       * @todo If there are multiple plugins defining 'runLast', sort them depending on who depends on whom. :D
       *
       * @private
       */
      orderPlugins() {
        debug("orderPlugins:before", this.pluginNames);
        const runLast = this._plugins.filter((p) => p.requirements.has("runLast")).map((p) => p.name);
        for (const name of runLast) {
          const index = this._plugins.findIndex((p) => p.name === name);
          this._plugins.push(this._plugins.splice(index, 1)[0]);
        }
        debug("orderPlugins:after", this.pluginNames);
      }
      /**
       * Lightweight plugin requirement checking.
       *
       * The main intent is to notify the user when a plugin won't work as expected.
       *
       * @todo This could be improved, e.g. be evaluated by the plugin base class.
       *
       * @private
       */
      checkPluginRequirements(opts = {}) {
        for (const plugin of this._plugins) {
          for (const requirement of plugin.requirements) {
            if (opts.context === "launch" && requirement === "headful" && opts.options.headless) {
              console.warn(`Warning: Plugin '${plugin.name}' is not supported in headless mode.`);
            }
            if (opts.context === "connect" && requirement === "launch") {
              console.warn(`Warning: Plugin '${plugin.name}' doesn't support puppeteer.connect().`);
            }
          }
        }
      }
      /**
       * Call plugins sequentially with the same values.
       * Plugins that expose the supplied property will be called.
       *
       * @param prop - The plugin property to call
       * @param values - Any number of values
       * @private
       */
      async callPlugins(prop, ...values) {
        for (const plugin of this.getPluginsByProp(prop)) {
          await plugin[prop].apply(plugin, values);
        }
      }
      /**
       * Call plugins sequentially and pass on a value (waterfall style).
       * Plugins that expose the supplied property will be called.
       *
       * The plugins can either modify the value or return an updated one.
       * Will return the latest, updated value which ran through all plugins.
       *
       * @param prop - The plugin property to call
       * @param value - Any value
       * @return The new updated value
       * @private
       */
      async callPluginsWithValue(prop, value) {
        for (const plugin of this.getPluginsByProp(prop)) {
          const newValue = await plugin[prop](value);
          if (newValue) {
            value = newValue;
          }
        }
        return value;
      }
    };
    var defaultExport = (() => {
      return new PuppeteerExtra(...requireVanillaPuppeteer());
    })();
    var addExtra = (puppeteer) => new PuppeteerExtra(puppeteer);
    function requireVanillaPuppeteer() {
      try {
        return [require("puppeteer"), void 0];
      } catch (_) {
      }
      try {
        return [require_puppeteer_core(), void 0];
      } catch (err) {
        return [void 0, err];
      }
    }
    exports2.PuppeteerExtra = PuppeteerExtra;
    exports2.addExtra = addExtra;
    exports2.default = defaultExport;
    module2.exports = exports2.default || {};
    Object.entries(exports2).forEach(([key, value]) => {
      module2.exports[key] = value;
    });
  }
});

// node_modules/arr-union/index.js
var require_arr_union = __commonJS({
  "node_modules/arr-union/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = function union(init) {
      if (!Array.isArray(init)) {
        throw new TypeError("arr-union expects the first argument to be an array.");
      }
      var len = arguments.length;
      var i = 0;
      while (++i < len) {
        var arg = arguments[i];
        if (!arg) continue;
        if (!Array.isArray(arg)) {
          arg = [arg];
        }
        for (var j = 0; j < arg.length; j++) {
          var ele = arg[j];
          if (init.indexOf(ele) >= 0) {
            continue;
          }
          init.push(ele);
        }
      }
      return init;
    };
  }
});

// node_modules/lazy-cache/index.js
var require_lazy_cache = __commonJS({
  "node_modules/lazy-cache/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    function lazyCache(fn) {
      var cache = {};
      var proxy = function(mod, name) {
        name = name || camelcase(mod);
        if (process.env.UNLAZY === "true" || process.env.UNLAZY === true || process.env.TRAVIS) {
          cache[name] = fn(mod);
        }
        Object.defineProperty(proxy, name, {
          enumerable: true,
          configurable: true,
          get: getter
        });
        function getter() {
          if (cache.hasOwnProperty(name)) {
            return cache[name];
          }
          return cache[name] = fn(mod);
        }
        return getter;
      };
      return proxy;
    }
    function camelcase(str) {
      if (str.length === 1) {
        return str.toLowerCase();
      }
      str = str.replace(/^[\W_]+|[\W_]+$/g, "").toLowerCase();
      return str.replace(/[\W_]+(\w|$)/g, function(_, ch) {
        return ch.toUpperCase();
      });
    }
    module2.exports = lazyCache;
  }
});

// node_modules/for-in/index.js
var require_for_in = __commonJS({
  "node_modules/for-in/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = function forIn(obj, fn, thisArg) {
      for (var key in obj) {
        if (fn.call(thisArg, obj[key], key, obj) === false) {
          break;
        }
      }
    };
  }
});

// node_modules/for-own/index.js
var require_for_own = __commonJS({
  "node_modules/for-own/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var forIn = require_for_in();
    var hasOwn = Object.prototype.hasOwnProperty;
    module2.exports = function forOwn(obj, fn, thisArg) {
      forIn(obj, function(val, key) {
        if (hasOwn.call(obj, key)) {
          return fn.call(thisArg, obj[key], key, obj);
        }
      });
    };
  }
});

// node_modules/clone-deep/utils.js
var require_utils4 = __commonJS({
  "node_modules/clone-deep/utils.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var utils = require_lazy_cache()(require);
    var fn = require;
    require = utils;
    require("is-plain-object", "isObject");
    require("shallow-clone", "clone");
    require("kind-of", "typeOf");
    require_for_own();
    require = fn;
    module2.exports = utils;
  }
});

// node_modules/clone-deep/index.js
var require_clone_deep = __commonJS({
  "node_modules/clone-deep/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var utils = require_utils4();
    function cloneDeep(val, instanceClone) {
      switch (utils.typeOf(val)) {
        case "object":
          return cloneObjectDeep(val, instanceClone);
        case "array":
          return cloneArrayDeep(val, instanceClone);
        default:
          return utils.clone(val);
      }
    }
    function cloneObjectDeep(obj, instanceClone) {
      if (utils.isObject(obj)) {
        var res = {};
        utils.forOwn(obj, function(obj2, key) {
          this[key] = cloneDeep(obj2, instanceClone);
        }, res);
        return res;
      } else if (instanceClone) {
        return instanceClone(obj);
      } else {
        return obj;
      }
    }
    function cloneArrayDeep(arr, instanceClone) {
      var len = arr.length, res = [];
      var i = -1;
      while (++i < len) {
        res[i] = cloneDeep(arr[i], instanceClone);
      }
      return res;
    }
    module2.exports = cloneDeep;
  }
});

// node_modules/is-buffer/index.js
var require_is_buffer = __commonJS({
  "node_modules/is-buffer/index.js"(exports2, module2) {
    init_prefix();
    module2.exports = function(obj) {
      return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer);
    };
    function isBuffer(obj) {
      return !!obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj);
    }
    function isSlowBuffer(obj) {
      return typeof obj.readFloatLE === "function" && typeof obj.slice === "function" && isBuffer(obj.slice(0, 0));
    }
  }
});

// node_modules/kind-of/index.js
var require_kind_of = __commonJS({
  "node_modules/kind-of/index.js"(exports2, module2) {
    init_prefix();
    var isBuffer = require_is_buffer();
    var toString = Object.prototype.toString;
    module2.exports = function kindOf(val) {
      if (typeof val === "undefined") {
        return "undefined";
      }
      if (val === null) {
        return "null";
      }
      if (val === true || val === false || val instanceof Boolean) {
        return "boolean";
      }
      if (typeof val === "string" || val instanceof String) {
        return "string";
      }
      if (typeof val === "number" || val instanceof Number) {
        return "number";
      }
      if (typeof val === "function" || val instanceof Function) {
        return "function";
      }
      if (typeof Array.isArray !== "undefined" && Array.isArray(val)) {
        return "array";
      }
      if (val instanceof RegExp) {
        return "regexp";
      }
      if (val instanceof Date) {
        return "date";
      }
      var type = toString.call(val);
      if (type === "[object RegExp]") {
        return "regexp";
      }
      if (type === "[object Date]") {
        return "date";
      }
      if (type === "[object Arguments]") {
        return "arguments";
      }
      if (type === "[object Error]") {
        return "error";
      }
      if (isBuffer(val)) {
        return "buffer";
      }
      if (type === "[object Set]") {
        return "set";
      }
      if (type === "[object WeakSet]") {
        return "weakset";
      }
      if (type === "[object Map]") {
        return "map";
      }
      if (type === "[object WeakMap]") {
        return "weakmap";
      }
      if (type === "[object Symbol]") {
        return "symbol";
      }
      if (type === "[object Int8Array]") {
        return "int8array";
      }
      if (type === "[object Uint8Array]") {
        return "uint8array";
      }
      if (type === "[object Uint8ClampedArray]") {
        return "uint8clampedarray";
      }
      if (type === "[object Int16Array]") {
        return "int16array";
      }
      if (type === "[object Uint16Array]") {
        return "uint16array";
      }
      if (type === "[object Int32Array]") {
        return "int32array";
      }
      if (type === "[object Uint32Array]") {
        return "uint32array";
      }
      if (type === "[object Float32Array]") {
        return "float32array";
      }
      if (type === "[object Float64Array]") {
        return "float64array";
      }
      return "object";
    };
  }
});

// node_modules/merge-deep/index.js
var require_merge_deep = __commonJS({
  "node_modules/merge-deep/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var union = require_arr_union();
    var clone = require_clone_deep();
    var typeOf = require_kind_of();
    module2.exports = function mergeDeep2(orig, objects) {
      if (!isObject(orig) && !Array.isArray(orig)) {
        orig = {};
      }
      var target = clone(orig);
      var len = arguments.length;
      var idx = 0;
      while (++idx < len) {
        var val = arguments[idx];
        if (isObject(val) || Array.isArray(val)) {
          merge(target, val);
        }
      }
      return target;
    };
    function merge(target, obj) {
      for (var key in obj) {
        if (!isValidKey(key) || !hasOwn(obj, key)) {
          continue;
        }
        var oldVal = obj[key];
        var newVal = target[key];
        if (isObject(newVal) && isObject(oldVal)) {
          target[key] = merge(newVal, oldVal);
        } else if (Array.isArray(newVal)) {
          target[key] = union([], newVal, oldVal);
        } else {
          target[key] = clone(oldVal);
        }
      }
      return target;
    }
    function hasOwn(obj, key) {
      return Object.prototype.hasOwnProperty.call(obj, key);
    }
    function isObject(val) {
      return typeOf(val) === "object" || typeOf(val) === "function";
    }
    function isValidKey(key) {
      return key !== "__proto__" && key !== "constructor" && key !== "prototype";
    }
  }
});

// node_modules/puppeteer-extra-plugin/dist/index.cjs.js
var require_index_cjs2 = __commonJS({
  "node_modules/puppeteer-extra-plugin/dist/index.cjs.js"(exports2) {
    "use strict";
    init_prefix();
    Object.defineProperty(exports2, "__esModule", { value: true });
    function _interopDefault(ex) {
      return ex && typeof ex === "object" && "default" in ex ? ex["default"] : ex;
    }
    var debug = _interopDefault(require_src());
    var merge = require_merge_deep();
    var PuppeteerExtraPlugin = class {
      constructor(opts) {
        this._debugBase = debug(`puppeteer-extra-plugin:base:${this.name}`);
        this._childClassMembers = [];
        this._opts = merge(this.defaults, opts || {});
        this._debugBase("Initialized.");
      }
      /**
       * Plugin name (required).
       *
       * Convention:
       * - Package: `puppeteer-extra-plugin-anonymize-ua`
       * - Name: `anonymize-ua`
       *
       * @example
       * get name () { return 'anonymize-ua' }
       */
      get name() {
        throw new Error('Plugin must override "name"');
      }
      /**
       * Plugin defaults (optional).
       *
       * If defined will be ([deep-](https://github.com/jonschlinkert/merge-deep))merged with the (optional) user supplied options (supplied during plugin instantiation).
       *
       * The result of merging defaults with user supplied options can be accessed through `this.opts`.
       *
       * @see [[opts]]
       *
       * @example
       * get defaults () {
       *   return {
       *     stripHeadless: true,
       *     makeWindows: true,
       *     customFn: null
       *   }
       * }
       *
       * // Users can overwrite plugin defaults during instantiation:
       * puppeteer.use(require('puppeteer-extra-plugin-foobar')({ makeWindows: false }))
       */
      get defaults() {
        return {};
      }
      /**
       * Plugin requirements (optional).
       *
       * Signal certain plugin requirements to the base class and the user.
       *
       * Currently supported:
       * - `launch`
       *   - If the plugin only supports locally created browser instances (no `puppeteer.connect()`),
       *     will output a warning to the user.
       * - `headful`
       *   - If the plugin doesn't work in `headless: true` mode,
       *     will output a warning to the user.
       * - `dataFromPlugins`
       *   - In case the plugin requires data from other plugins.
       *     will enable usage of `this.getDataFromPlugins()`.
       * - `runLast`
       *   - In case the plugin prefers to run after the others.
       *     Useful when the plugin needs data from others.
       *
       * @example
       * get requirements () {
       *   return new Set(['runLast', 'dataFromPlugins'])
       * }
       */
      get requirements() {
        return /* @__PURE__ */ new Set([]);
      }
      /**
       * Plugin dependencies (optional).
       *
       * Missing plugins will be required() by puppeteer-extra.
       *
       * @example
       * get dependencies () {
       *   return new Set(['user-preferences'])
       * }
       * // Will ensure the 'puppeteer-extra-plugin-user-preferences' plugin is loaded.
       */
      get dependencies() {
        return /* @__PURE__ */ new Set([]);
      }
      /**
       * Plugin data (optional).
       *
       * Plugins can expose data (an array of objects), which in turn can be consumed by other plugins,
       * that list the `dataFromPlugins` requirement (by using `this.getDataFromPlugins()`).
       *
       * Convention: `[ {name: 'Any name', value: 'Any value'} ]`
       *
       * @see [[getDataFromPlugins]]
       *
       * @example
       * // plugin1.js
       * get data () {
       *   return [
       *     {
       *       name: 'userPreferences',
       *       value: { foo: 'bar' }
       *     },
       *     {
       *       name: 'userPreferences',
       *       value: { hello: 'world' }
       *     }
       *   ]
       *
       * // plugin2.js
       * get requirements () { return new Set(['dataFromPlugins']) }
       *
       * async beforeLaunch () {
       *   const prefs = this.getDataFromPlugins('userPreferences').map(d => d.value)
       *   this.debug(prefs) // => [ { foo: 'bar' }, { hello: 'world' } ]
       * }
       */
      get data() {
        return [];
      }
      /**
       * Access the plugin options (usually the `defaults` merged with user defined options)
       *
       * To skip the auto-merging of defaults with user supplied opts don't define a `defaults`
       * property and set the `this._opts` Object in your plugin constructor directly.
       *
       * @see [[defaults]]
       *
       * @example
       * get defaults () { return { foo: "bar" } }
       *
       * async onPageCreated (page) {
       *   this.debug(this.opts.foo) // => bar
       * }
       */
      get opts() {
        return this._opts;
      }
      /**
       *  Convenience debug logger based on the [debug] module.
       *  Will automatically namespace the logging output to the plugin package name.
       *  [debug]: https://www.npmjs.com/package/debug
       *
       *  ```bash
       *  # toggle output using environment variables
       *  DEBUG=puppeteer-extra-plugin:<plugin_name> node foo.js
       *  # to debug all the things:
       *  DEBUG=puppeteer-extra,puppeteer-extra-plugin:* node foo.js
       *  ```
       *
       * @example
       * this.debug('hello world')
       * // will output e.g. 'puppeteer-extra-plugin:anonymize-ua hello world'
       */
      get debug() {
        return debug(`puppeteer-extra-plugin:${this.name}`);
      }
      /**
       * Before a new browser instance is created/launched.
       *
       * Can be used to modify the puppeteer launch options by modifying or returning them.
       *
       * Plugins using this method will be called in sequence to each
       * be able to update the launch options.
       *
       * @example
       * async beforeLaunch (options) {
       *   if (this.opts.flashPluginPath) {
       *     options.args.push(`--ppapi-flash-path=${this.opts.flashPluginPath}`)
       *   }
       * }
       *
       * @param options - Puppeteer launch options
       */
      async beforeLaunch(options) {
      }
      /**
       * After the browser has launched.
       *
       * Note: Don't assume that there will only be a single browser instance during the lifecycle of a plugin.
       * It's possible that `pupeeteer.launch` will be  called multiple times and more than one browser created.
       * In order to make the plugins as stateless as possible don't store a reference to the browser instance
       * in the plugin but rather consider alternatives.
       *
       * E.g. when using `onPageCreated` you can get a browser reference by using `page.browser()`.
       *
       * Alternatively you could expose a class method that takes a browser instance as a parameter to work with:
       *
       * ```es6
       * const fancyPlugin = require('puppeteer-extra-plugin-fancy')()
       * puppeteer.use(fancyPlugin)
       * const browser = await puppeteer.launch()
       * await fancyPlugin.killBrowser(browser)
       * ```
       *
       * @param  browser - The `puppeteer` browser instance.
       * @param  opts.options - Puppeteer launch options used.
       *
       * @example
       * async afterLaunch (browser, opts) {
       *   this.debug('browser has been launched', opts.options)
       * }
       */
      async afterLaunch(browser, opts = { options: {} }) {
      }
      /**
       * Before connecting to an existing browser instance.
       *
       * Can be used to modify the puppeteer connect options by modifying or returning them.
       *
       * Plugins using this method will be called in sequence to each
       * be able to update the launch options.
       *
       * @param  {Object} options - Puppeteer connect options
       * @return {Object=}
       */
      async beforeConnect(options) {
      }
      /**
       * After connecting to an existing browser instance.
       *
       * > Note: Don't assume that there will only be a single browser instance during the lifecycle of a plugin.
       *
       * @param browser - The `puppeteer` browser instance.
       * @param  {Object} opts
       * @param  {Object} opts.options - Puppeteer connect options used.
       *
       */
      async afterConnect(browser, opts = {}) {
      }
      /**
       * Called when a browser instance is available.
       *
       * This applies to both `puppeteer.launch()` and `puppeteer.connect()`.
       *
       * Convenience method created for plugins that need access to a browser instance
       * and don't mind if it has been created through `launch` or `connect`.
       *
       * > Note: Don't assume that there will only be a single browser instance during the lifecycle of a plugin.
       *
       * @param browser - The `puppeteer` browser instance.
       */
      async onBrowser(browser, opts) {
      }
      /**
       * Called when a target is created, for example when a new page is opened by window.open or browser.newPage.
       *
       * > Note: This includes target creations in incognito browser contexts.
       *
       * > Note: This includes browser instances created through `.launch()` as well as `.connect()`.
       *
       * @param  {Puppeteer.Target} target
       */
      async onTargetCreated(target) {
      }
      /**
       * Same as `onTargetCreated` but prefiltered to only contain Pages, for convenience.
       *
       * > Note: This includes page creations in incognito browser contexts.
       *
       * > Note: This includes browser instances created through `.launch()` as well as `.connect()`.
       *
       * @param  {Puppeteer.Target} target
       *
       * @example
       * async onPageCreated (page) {
       *   let ua = await page.browser().userAgent()
       *   if (this.opts.stripHeadless) {
       *     ua = ua.replace('HeadlessChrome/', 'Chrome/')
       *   }
       *   this.debug('new ua', ua)
       *   await page.setUserAgent(ua)
       * }
       */
      async onPageCreated(page2) {
      }
      /**
       * Called when the url of a target changes.
       *
       * > Note: This includes target changes in incognito browser contexts.
       *
       * > Note: This includes browser instances created through `.launch()` as well as `.connect()`.
       *
       * @param  {Puppeteer.Target} target
       */
      async onTargetChanged(target) {
      }
      /**
       * Called when a target is destroyed, for example when a page is closed.
       *
       * > Note: This includes target destructions in incognito browser contexts.
       *
       * > Note: This includes browser instances created through `.launch()` as well as `.connect()`.
       *
       * @param  {Puppeteer.Target} target
       */
      async onTargetDestroyed(target) {
      }
      /**
       * Called when Puppeteer gets disconnected from the Chromium instance.
       *
       * This might happen because of one of the following:
       * - Chromium is closed or crashed
       * - The `browser.disconnect` method was called
       */
      async onDisconnected() {
      }
      /**
       * **Deprecated:** Since puppeteer v1.6.0 `onDisconnected` has been improved
       * and should be used instead of `onClose`.
       *
       * In puppeteer < v1.6.0 `onDisconnected` was not catching all exit scenarios.
       * In order for plugins to clean up properly (e.g. deleting temporary files)
       * the `onClose` method had been introduced.
       *
       * > Note: Might be called multiple times on exit.
       *
       * > Note: This only includes browser instances created through `.launch()`.
       */
      async onClose() {
      }
      /**
       * After the plugin has been registered in `puppeteer-extra`.
       *
       * Normally right after `puppeteer.use(plugin)` is called
       */
      async onPluginRegistered() {
      }
      /**
       * Helper method to retrieve `data` objects from other plugins.
       *
       * A plugin needs to state the `dataFromPlugins` requirement
       * in order to use this method. Will be mapped to `puppeteer.getPluginData`.
       *
       * @param name - Filter data by `name` property
       *
       * @see [data]
       * @see [requirements]
       */
      getDataFromPlugins(name) {
        return [];
      }
      /**
       * Will match plugin dependencies against all currently registered plugins.
       * Is being called by `puppeteer-extra` and used to require missing dependencies.
       *
       * @param  {Array<Object>} plugins
       * @return {Set} - list of missing plugin names
       *
       * @private
       */
      _getMissingDependencies(plugins) {
        const pluginNames = new Set(plugins.map((p) => p.name));
        const missing = new Set(Array.from(this.dependencies.values()).filter((x) => !pluginNames.has(x)));
        return missing;
      }
      /**
       * Conditionally bind browser/process events to class members.
       * The idea is to reduce event binding boilerplate in plugins.
       *
       * For efficiency we make sure the plugin is using the respective event
       * by checking the child class members before registering the listener.
       *
       * @param  {<Puppeteer.Browser>} browser
       * @param  {Object} opts - Options
       * @param  {string} opts.context - Puppeteer context (launch/connect)
       * @param  {Object} [opts.options] - Puppeteer launch or connect options
       * @param  {Array<string>} [opts.defaultArgs] - The default flags that Chromium will be launched with
       *
       * @private
       */
      async _bindBrowserEvents(browser, opts = {}) {
        if (this._hasChildClassMember("onTargetCreated") || this._hasChildClassMember("onPageCreated")) {
          browser.on("targetcreated", this._onTargetCreated.bind(this));
        }
        if (this._hasChildClassMember("onTargetChanged") && this.onTargetChanged) {
          browser.on("targetchanged", this.onTargetChanged.bind(this));
        }
        if (this._hasChildClassMember("onTargetDestroyed") && this.onTargetDestroyed) {
          browser.on("targetdestroyed", this.onTargetDestroyed.bind(this));
        }
        if (this._hasChildClassMember("onDisconnected") && this.onDisconnected) {
          browser.on("disconnected", this.onDisconnected.bind(this));
        }
        if (opts.context === "launch" && this._hasChildClassMember("onClose")) {
          if (this.onClose) {
            process.on("exit", this.onClose.bind(this));
            browser.on("disconnected", this.onClose.bind(this));
            if (opts.options.handleSIGINT !== false) {
              process.on("SIGINT", this.onClose.bind(this));
            }
            if (opts.options.handleSIGTERM !== false) {
              process.on("SIGTERM", this.onClose.bind(this));
            }
            if (opts.options.handleSIGHUP !== false) {
              process.on("SIGHUP", this.onClose.bind(this));
            }
          }
        }
        if (opts.context === "launch" && this.afterLaunch) {
          await this.afterLaunch(browser, opts);
        }
        if (opts.context === "connect" && this.afterConnect) {
          await this.afterConnect(browser, opts);
        }
        if (this.onBrowser)
          await this.onBrowser(browser, opts);
      }
      /**
       * @private
       */
      async _onTargetCreated(target) {
        if (this.onTargetCreated)
          await this.onTargetCreated(target);
        if (target.type() === "page") {
          try {
            const page2 = await target.page();
            if (!page2) {
              return;
            }
            const validPage = "isClosed" in page2 && !page2.isClosed();
            if (this.onPageCreated && validPage) {
              await this.onPageCreated(page2);
            }
          } catch (err) {
            console.error(err);
          }
        }
      }
      /**
       * @private
       */
      _register(prototype) {
        this._registerChildClassMembers(prototype);
        if (this.onPluginRegistered)
          this.onPluginRegistered();
      }
      /**
       * @private
       */
      _registerChildClassMembers(prototype) {
        this._childClassMembers = Object.getOwnPropertyNames(prototype);
      }
      /**
       * @private
       */
      _hasChildClassMember(name) {
        return !!this._childClassMembers.includes(name);
      }
      /**
       * @private
       */
      get _isPuppeteerExtraPlugin() {
        return true;
      }
    };
    exports2.PuppeteerExtraPlugin = PuppeteerExtraPlugin;
  }
});

// node_modules/puppeteer-extra-plugin-stealth/index.js
var require_puppeteer_extra_plugin_stealth = __commonJS({
  "node_modules/puppeteer-extra-plugin-stealth/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var { PuppeteerExtraPlugin } = require_index_cjs2();
    var StealthPlugin = class extends PuppeteerExtraPlugin {
      constructor(opts = {}) {
        super(opts);
      }
      get name() {
        return "stealth";
      }
      get defaults() {
        const availableEvasions = /* @__PURE__ */ new Set([
          "chrome.app",
          "chrome.csi",
          "chrome.loadTimes",
          "chrome.runtime",
          "defaultArgs",
          "iframe.contentWindow",
          "media.codecs",
          "navigator.hardwareConcurrency",
          "navigator.languages",
          "navigator.permissions",
          "navigator.plugins",
          "navigator.webdriver",
          "sourceurl",
          "user-agent-override",
          "webgl.vendor",
          "window.outerdimensions"
        ]);
        return {
          availableEvasions,
          // Enable all available evasions by default
          enabledEvasions: /* @__PURE__ */ new Set([...availableEvasions])
        };
      }
      /**
       * Requires evasion techniques dynamically based on configuration.
       *
       * @private
       */
      get dependencies() {
        return new Set(
          [...this.opts.enabledEvasions].map((e) => `${this.name}/evasions/${e}`)
        );
      }
      /**
       * Get all available evasions.
       *
       * Please look into the [evasions directory](./evasions/) for an up to date list.
       *
       * @type {Set<string>} - A Set of all available evasions.
       *
       * @example
       * const pluginStealth = require('puppeteer-extra-plugin-stealth')()
       * console.log(pluginStealth.availableEvasions) // => Set { 'user-agent', 'console.debug' }
       * puppeteer.use(pluginStealth)
       */
      get availableEvasions() {
        return this.defaults.availableEvasions;
      }
      /**
       * Get all enabled evasions.
       *
       * Enabled evasions can be configured either through `opts` or by modifying this property.
       *
       * @type {Set<string>} - A Set of all enabled evasions.
       *
       * @example
       * // Remove specific evasion from enabled ones dynamically
       * const pluginStealth = require('puppeteer-extra-plugin-stealth')()
       * pluginStealth.enabledEvasions.delete('console.debug')
       * puppeteer.use(pluginStealth)
       */
      get enabledEvasions() {
        return this.opts.enabledEvasions;
      }
      /**
       * @private
       */
      set enabledEvasions(evasions) {
        this.opts.enabledEvasions = evasions;
      }
      async onBrowser(browser) {
        if (browser && browser.setMaxListeners) {
          browser.setMaxListeners(30);
        }
      }
    };
    var defaultExport = (opts) => new StealthPlugin(opts);
    module2.exports = defaultExport;
  }
});

// services/BrowserAutomation.js
var require_BrowserAutomation = __commonJS({
  "services/BrowserAutomation.js"(exports2, module2) {
    init_prefix();
    var puppeteer = require_index_cjs();
    var StealthPlugin = require_puppeteer_extra_plugin_stealth();
    var { URL: URL2 } = require("url");
    puppeteer.use(StealthPlugin());
    var BrowserAutomation2 = class {
      constructor(config2 = {}) {
        this.browser = null;
        this.page = null;
        this.config = config2.browser || {};
        this.cleanupFunctions = [];
        this.headless = this.config.headless !== void 0 ? this.config.headless : false;
        this.viewport = this.config.viewport || { width: 1920, height: 1080 };
        this.slowdown = this.config.slowdown || 100;
        this.scrollSpeed = this.config.scrollSpeed || 500;
        this.executablePath = this.findBrowserPath();
        this.browserType = this.detectBrowserType();
      }
      /**
       * 查找浏览器可执行文件路径
       * 优先使用 Edge (Windows 自带)，然后 Chrome，最后让 Puppeteer 使用内置 Chromium
       */
      findBrowserPath() {
        const platform = process.platform;
        const fs2 = require("fs");
        const paths = {
          win32: [
            // Edge (Windows 自带，优先使用)
            "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
            "C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe",
            process.env.PROGRAMFILES + "\\Microsoft\\Edge\\Application\\msedge.exe",
            process.env["PROGRAMFILES(X86)"] + "\\Microsoft\\Edge\\Application\\msedge.exe",
            // Chrome
            "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
            "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
            process.env.LOCALAPPDATA + "\\Google\\Chrome\\Application\\chrome.exe"
          ],
          darwin: [
            "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
          ],
          linux: [
            "/usr/bin/microsoft-edge",
            "/usr/bin/google-chrome-stable",
            "/usr/bin/google-chrome",
            "/usr/bin/chromium-browser"
          ]
        };
        const platformPaths = paths[platform] || [];
        for (const path2 of platformPaths) {
          if (path2 && fs2.existsSync(path2)) {
            return path2;
          }
        }
        return void 0;
      }
      /**
       * 检测浏览器类型
       */
      detectBrowserType() {
        if (!this.executablePath) return "Chromium (\u5185\u7F6E)";
        if (this.executablePath.includes("msedge")) return "Edge";
        if (this.executablePath.includes("chrome")) return "Chrome";
        return "Unknown";
      }
      /**
       * 获取固定的用户数据目录
       * 避免每次启动都在 /tmp/ 创建新的临时目录（puppeteer_dev_profile-*）
       * 每个临时目录约81MB，异常退出时会残留导致磁盘堆积
       */
      getUserDataDir() {
        const path2 = require("path");
        const os = require("os");
        if (this.config.userDataDir) {
          return this.config.userDataDir;
        }
        const clientType = process.env.CLIENT_TYPE || "default";
        const hostname = os.hostname().replace(/[^a-zA-Z0-9]/g, "_");
        let userDataDir;
        if (process.platform === "win32") {
          userDataDir = path2.join(os.homedir(), "AppData", "Local", "xiaohongshu-clients", clientType);
        } else {
          userDataDir = path2.join(os.tmpdir(), "xiaohongshu-clients", clientType);
        }
        return userDataDir;
      }
      /**
       * 清除浏览器缓存（包括Cookie，强制重新登录）
       * 删除 Cache、Code Cache、GPUCache、Cookies 等缓存目录
       * @param {boolean} forceClear - 强制清除（包括本机）
       */
      clearCache(userDataDir, forceClear = false) {
        const fs2 = require("fs");
        const os = require("os");
        if (!forceClear && os.hostname() === "DESKTOP-HDM9SKA") {
          console.log("   \u2139\uFE0F  [\u7F13\u5B58] \u672C\u673A\u6A21\u5F0F\uFF0C\u8DF3\u8FC7\u6E05\u9664\u7F13\u5B58");
          return;
        }
        const path2 = require("path");
        const profileDir = path2.join(userDataDir, "Default");
        const cacheDirs = [
          "Cache",
          // 主缓存目录
          "Code Cache",
          // 代码缓存
          "GPUCache",
          // GPU缓存
          "Service Worker",
          // Service Worker 缓存
          "Local Storage",
          // LocalStorage
          "Session Storage",
          // SessionStorage
          "IndexedDB",
          // IndexedDB
          "Application Cache",
          // 应用缓存
          "Storage"
          // 存储目录
        ];
        let clearedCount = 0;
        for (const cacheDir of cacheDirs) {
          const cachePath = path2.join(profileDir, cacheDir);
          try {
            if (fs2.existsSync(cachePath)) {
              fs2.rmSync(cachePath, { recursive: true, force: true });
              clearedCount++;
              console.log(`   \u{1F5D1}\uFE0F  [\u7F13\u5B58\u6E05\u7406] \u5DF2\u5220\u9664: ${cacheDir}`);
            }
          } catch (error) {
            console.log(`   \u26A0\uFE0F  [\u7F13\u5B58\u6E05\u7406] \u65E0\u6CD5\u5220\u9664 ${cacheDir}: ${error.message}`);
          }
        }
        const cacheFiles = [
          "Cookies",
          // Cookies 数据库
          "Cookies-journal",
          // Cookies WAL 文件
          "Network"
          // 网络缓存
        ];
        for (const cacheFile of cacheFiles) {
          const filePath = path2.join(profileDir, cacheFile);
          try {
            if (fs2.existsSync(filePath)) {
              fs2.unlinkSync(filePath);
              console.log(`   \u{1F5D1}\uFE0F  [\u7F13\u5B58\u6E05\u7406] \u5DF2\u5220\u9664: ${cacheFile}`);
            }
          } catch (error) {
            try {
              if (fs2.existsSync(filePath)) {
                fs2.rmSync(filePath, { recursive: true, force: true });
                console.log(`   \u{1F5D1}\uFE0F  [\u7F13\u5B58\u6E05\u7406] \u5DF2\u5220\u9664: ${cacheFile}`);
              }
            } catch (e) {
            }
          }
        }
        if (clearedCount > 0) {
          console.log(`   \u2705 [\u7F13\u5B58\u6E05\u7406] \u5DF2\u6E05\u9664 ${clearedCount} \u4E2A\u7F13\u5B58\u76EE\u5F55\uFF08\u5B8C\u5168\u6E05\u7A7A\uFF09`);
        } else {
          console.log(`   \u2139\uFE0F  [\u7F13\u5B58\u6E05\u7406] \u6CA1\u6709\u53D1\u73B0\u65E7\u7F13\u5B58`);
        }
      }
      /**
       * 启动浏览器（可见模式）
       */
      async launch() {
        console.log("\u{1F680} [\u6D4F\u89C8\u5668] \u542F\u52A8\u6D4F\u89C8\u5668...");
        const userDataDir = this.getUserDataDir();
        console.log(`\u{1F4C1} [\u6D4F\u89C8\u5668] \u7528\u6237\u6570\u636E\u76EE\u5F55: ${userDataDir}`);
        const fs2 = require("fs");
        const path2 = require("path");
        const cookiesPath = path2.join(userDataDir, "Default", "Cookies");
        if (fs2.existsSync(cookiesPath)) {
          const stats = fs2.statSync(cookiesPath);
          const ageHours = (Date.now() - stats.mtime.getTime()) / (1e3 * 60 * 60);
          const os = require("os");
          const isLocalMachine = os.hostname() === "DESKTOP-HDM9SKA";
          if (ageHours > 72) {
            console.log(`   \u26A0\uFE0F  [\u6D4F\u89C8\u5668] Cookie\u6587\u4EF6\u5DF2\u8FC7\u671F (${Math.floor(ageHours)}\u5C0F\u65F6\u672A\u66F4\u65B0)`);
            console.log(`   \u{1F5D1}\uFE0F  [\u6D4F\u89C8\u5668] ${isLocalMachine ? "\u672C\u673A\u4E5F" : ""}\u6E05\u9664\u65E7\u7F13\u5B58...`);
            this.clearCache(userDataDir, true);
          } else if (isLocalMachine) {
            console.log(`   \u2139\uFE0F  [\u6D4F\u89C8\u5668] \u672C\u673A\u6A21\u5F0F\uFF0CCookie\u5E74\u9F84: ${Math.floor(ageHours)}\u5C0F\u65F6 (\u6B63\u5E38)`);
          }
        }
        const launchOptions = {
          headless: this.headless,
          executablePath: this.executablePath,
          userDataDir,
          // 固定目录，避免每次创建新的临时目录
          defaultViewport: this.viewport,
          args: [
            "--disable-blink-features=AutomationControlled",
            "--no-sandbox",
            "--disable-setuid-sandbox",
            "--disable-dev-shm-usage",
            "--disable-web-security",
            "--disable-gpu",
            "--disable-accelerated-2d-canvas",
            "--disable-cache",
            // 禁用浏览器缓存
            "--disable-application-cache",
            // 禁用应用缓存
            "--disable-service-worker",
            // 禁用 Service Worker（防止离线缓存）
            "--disable-background-networking",
            // 禁用后台网络请求
            "--disable-background-timer-throttling",
            "--disable-backgrounding-occluded-windows",
            "--disable-renderer-backgrounding",
            "--disable-features=BuiltinModuleCacher,MediaRouter",
            // 禁用额外缓存特性
            `--window-size=${this.viewport.width},${this.viewport.height}`
          ]
        };
        try {
          this.browser = await puppeteer.launch(launchOptions);
          this.page = await this.browser.newPage();
          await this.page.setCacheEnabled(false);
          await this.page.setUserAgent(
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
          );
          await this.injectAntiDetection();
          await this.injectCommentJumper();
          console.log("\u2705 [\u6D4F\u89C8\u5668] \u6D4F\u89C8\u5668\u542F\u52A8\u6210\u529F");
          console.log(`\u{1F310} [\u6D4F\u89C8\u5668] \u4F7F\u7528\u6D4F\u89C8\u5668: ${this.browserType}`);
          console.log(`\u{1F4FA} [\u6D4F\u89C8\u5668] \u663E\u793A\u6A21\u5F0F: ${this.headless ? "\u65E0\u5934" : "\u53EF\u89C1"}`);
          return true;
        } catch (error) {
          console.error("\u274C [\u6D4F\u89C8\u5668] \u542F\u52A8\u5931\u8D25:", error.message);
          throw error;
        }
      }
      /**
       * 注入反检测脚本
       */
      async injectAntiDetection() {
        await this.page.evaluateOnNewDocument(() => {
          Object.defineProperty(navigator, "webdriver", {
            get: () => false
          });
          window.chrome = {
            runtime: {}
          };
          const originalQuery = window.navigator.permissions.query;
          window.navigator.permissions.query = (parameters) => parameters.name === "notifications" ? Promise.resolve({ state: Notification.permission }) : originalQuery(parameters);
          Object.defineProperty(navigator, "plugins", {
            get: () => [1, 2, 3, 4, 5]
          });
          Object.defineProperty(navigator, "languages", {
            get: () => ["zh-CN", "zh", "en"]
          });
        });
      }
      /**
       * 注入评论跳转脚本
       */
      async injectCommentJumper() {
        await this.page.evaluateOnNewDocument(() => {
          console.log("\u{1F4CC} [\u8BC4\u8BBA\u8DF3\u8F6C] \u811A\u672C\u5DF2\u52A0\u8F7D");
          function findScrollParent(element) {
            let parent = element.parentElement;
            while (parent) {
              const overflow = window.getComputedStyle(parent).overflow;
              const overflowY = window.getComputedStyle(parent).overflowY;
              if ((overflow === "auto" || overflow === "scroll" || overflowY === "auto" || overflowY === "scroll") && parent.scrollHeight > parent.clientHeight) {
                return parent;
              }
              parent = parent.parentElement;
            }
            return null;
          }
          function getRelativeOffsetTop(element, scrollParent) {
            let offsetTop = 0;
            let current = element;
            while (current && current !== scrollParent) {
              offsetTop += current.offsetTop;
              current = current.offsetParent;
            }
            return offsetTop;
          }
          function highlightComment(element) {
            const originalBg = element.style.backgroundColor;
            const originalBoxShadow = element.style.boxShadow;
            element.style.backgroundColor = "#fff3cd";
            element.style.boxShadow = "0 0 10px rgba(255, 193, 7, 0.5)";
            element.style.transition = "all 0.3s ease";
            setTimeout(() => {
              element.style.backgroundColor = originalBg;
              element.style.boxShadow = originalBoxShadow;
            }, 2e3);
          }
          function scrollToComment(commentId) {
            console.log(`\u{1F50D} [\u8BC4\u8BBA\u8DF3\u8F6C] \u67E5\u627E\u8BC4\u8BBA: ${commentId}`);
            const commentEl = document.getElementById("comment-" + commentId);
            if (!commentEl) {
              console.log("\u23F3 [\u8BC4\u8BBA\u8DF3\u8F6C] \u8BC4\u8BBA\u672A\u627E\u5230");
              return false;
            }
            console.log("\u2705 [\u8BC4\u8BBA\u8DF3\u8F6C] \u627E\u5230\u8BC4\u8BBA\uFF0C\u5F00\u59CB\u6EDA\u52A8");
            const scrollParent = findScrollParent(commentEl);
            if (!scrollParent) {
              console.warn("\u26A0\uFE0F [\u8BC4\u8BBA\u8DF3\u8F6C] \u672A\u627E\u5230\u6EDA\u52A8\u5BB9\u5668");
              commentEl.scrollIntoView({ behavior: "smooth", block: "center" });
              highlightComment(commentEl);
              return true;
            }
            const offsetTop = getRelativeOffsetTop(commentEl, scrollParent);
            const targetScroll = offsetTop - scrollParent.clientHeight / 2;
            scrollParent.scrollTop = targetScroll;
            highlightComment(commentEl);
            console.log("\u2705 [\u8BC4\u8BBA\u8DF3\u8F6C] \u6EDA\u52A8\u5B8C\u6210");
            return true;
          }
          function handleHashChange() {
            const hash = window.location.hash;
            if (hash && hash.startsWith("#comment-")) {
              const commentId = hash.replace("#comment-", "");
              if (commentId) {
                console.log("\u{1F4CD} [\u8BC4\u8BBA\u8DF3\u8F6C] \u68C0\u6D4B\u5230\u8BC4\u8BBA\u951A\u70B9: " + commentId);
                setTimeout(() => scrollToComment(commentId), 500);
              }
            }
          }
          window.addEventListener("hashchange", handleHashChange);
          if (document.readyState === "loading") {
            document.addEventListener("DOMContentLoaded", () => {
              setTimeout(handleHashChange, 1e3);
            });
          } else {
            setTimeout(handleHashChange, 1e3);
          }
          let lastUrl = location.href;
          new MutationObserver(() => {
            const currentUrl = location.href;
            if (currentUrl !== lastUrl) {
              lastUrl = currentUrl;
              setTimeout(handleHashChange, 1e3);
            }
          }).observe(document.body, { childList: true, subtree: true });
          console.log("\u2705 [\u8BC4\u8BBA\u8DF3\u8F6C] \u811A\u672C\u5DF2\u5C31\u7EEA");
        });
      }
      /**
       * 设置 Cookie（直接使用 Cookie 数组）
       */
      async setCookies(cookieStringOrArray) {
        if (!this.page) {
          console.error("\u274C [\u6D4F\u89C8\u5668] \u9875\u9762\u672A\u521D\u59CB\u5316");
          return false;
        }
        try {
          let cookies;
          if (typeof cookieStringOrArray === "string") {
            cookies = this.parseCookieString(cookieStringOrArray);
          } else if (Array.isArray(cookieStringOrArray)) {
            cookies = cookieStringOrArray;
          } else {
            console.error("\u274C [\u6D4F\u89C8\u5668] Cookie \u683C\u5F0F\u9519\u8BEF");
            return false;
          }
          if (!cookies || cookies.length === 0) {
            console.error("\u274C [\u6D4F\u89C8\u5668] \u6CA1\u6709 Cookie \u53EF\u8BBE\u7F6E");
            return false;
          }
          await this.page.goto("https://www.xiaohongshu.com", {
            waitUntil: "domcontentloaded",
            timeout: 15e3
          });
          await this.page.setCookie(...cookies);
          console.log(`\u{1F36A} [\u6D4F\u89C8\u5668] \u5DF2\u8BBE\u7F6E ${cookies.length} \u4E2A Cookie`);
          const keyCookies = ["a1", "web_session"];
          for (const name of keyCookies) {
            const cookie = cookies.find((c) => c.name === name);
            if (cookie) {
              const valuePreview = cookie.value ? cookie.value.substring(0, 20) + "..." : "empty";
              console.log(`   \u2713 ${name}: ${valuePreview} (${cookie.value?.length || 0} \u5B57\u7B26)`);
            } else {
              console.log(`   \u2717 ${name}: \u7F3A\u5931`);
            }
          }
          return true;
        } catch (error) {
          console.error("\u274C [\u6D4F\u89C8\u5668] \u8BBE\u7F6E Cookie \u5931\u8D25:", error.message);
          return false;
        }
      }
      /**
       * 解析 Cookie 字符串为 Puppeteer 格式
       */
      parseCookieString(cookieString) {
        return cookieString.split("; ").map((pair) => {
          const parts = pair.split("=");
          if (parts.length < 2) return null;
          const name = parts[0].trim();
          const value = parts.slice(1).join("=").trim();
          if (!name || !value) return null;
          return {
            name,
            value,
            domain: ".xiaohongshu.com",
            path: "/",
            httpOnly: name === "web_session" || name === "a1",
            secure: true
          };
        }).filter((cookie) => cookie !== null);
      }
      /**
       * 打开小红书登录页
       */
      async openLoginPage() {
        if (!this.page) {
          throw new Error("\u6D4F\u89C8\u5668\u672A\u542F\u52A8");
        }
        console.log("\u{1F310} [\u6D4F\u89C8\u5668] \u6253\u5F00\u5C0F\u7EA2\u4E66\u767B\u5F55\u9875...");
        await this.page.goto("https://www.xiaohongshu.com", {
          waitUntil: "domcontentloaded",
          // 改用 domcontentloaded，更快
          timeout: 15e3
        });
        console.log("\u2705 [\u6D4F\u89C8\u5668] \u767B\u5F55\u9875\u5DF2\u6253\u5F00\uFF0C\u7B49\u5F85\u7528\u6237\u626B\u7801\u767B\u5F55");
      }
      /**
       * 刷新当前页面（用于登录后确保 Cookie 设置完成）
       */
      async refreshPage() {
        if (!this.page) {
          throw new Error("\u6D4F\u89C8\u5668\u672A\u542F\u52A8");
        }
        console.log("\u{1F504} [\u6D4F\u89C8\u5668] \u5237\u65B0\u9875\u9762...");
        await this.page.reload({ waitUntil: "domcontentloaded", timeout: 15e3 });
        await this.sleep(500);
        console.log("\u2705 [\u6D4F\u89C8\u5668] \u9875\u9762\u5237\u65B0\u5B8C\u6210");
      }
      /**
       * 读取当前页面的 Cookie
       */
      async readCookies() {
        if (!this.page) {
          throw new Error("\u6D4F\u89C8\u5668\u672A\u542F\u52A8");
        }
        console.log("\u{1F36A} [\u6D4F\u89C8\u5668] \u8BFB\u53D6 Cookie...");
        const cookies = await this.page.cookies();
        const hasA1 = cookies.some((c) => c.name === "a1");
        const hasWebSession = cookies.some((c) => c.name === "web_session");
        const hasXHng = cookies.some((c) => c.name === "x-hng");
        console.log(`\u{1F4CA} [Cookie] \u539F\u59CB Cookie \u6570\u91CF: ${cookies.length}`);
        console.log(`   - a1: ${hasA1 ? "\u2705" : "\u274C"}`);
        console.log(`   - web_session: ${hasWebSession ? "\u2705" : "\u274C"}`);
        console.log(`   - x-hng: ${hasXHng ? "\u2705" : "\u274C"}`);
        const xhsCookies = cookies.filter(
          (c) => c.domain?.includes("xiaohongshu") || ["a1", "web_session", "x-hng", "gid", "webId", "loadts", "xsecappid"].includes(c.name)
        );
        console.log(`\u2705 [\u6D4F\u89C8\u5668] \u8BFB\u53D6\u5230 ${xhsCookies.length} \u4E2A\u5C0F\u7EA2\u4E66 Cookie`);
        return xhsCookies;
      }
      /**
       * 访问小红书笔记页面
       */
      async visitNotePage(noteUrl) {
        if (!this.page) {
          throw new Error("\u6D4F\u89C8\u5668\u672A\u542F\u52A8");
        }
        console.log(`\u{1F310} [\u6D4F\u89C8\u5668] \u8BBF\u95EE\u7B14\u8BB0: ${noteUrl}`);
        try {
          await this.page.goto(noteUrl, {
            waitUntil: "domcontentloaded",
            timeout: 3e4
          });
          await this.randomDelay(3e3, 6e3, "normal");
          let rateLimitCheck = null;
          try {
            rateLimitCheck = await this.checkIsRateLimited();
          } catch (e) {
            console.warn("\u26A0\uFE0F  [\u6D4F\u89C8\u5668] checkIsRateLimited \u5931\u8D25:", e.message);
          }
          if (rateLimitCheck && rateLimitCheck.isRateLimited) {
            console.error("\u{1F6AB} [\u6D4F\u89C8\u5668] \u68C0\u6D4B\u5230\u8BBF\u95EE\u9891\u7387\u9650\u5236\uFF08\u9519\u8BEF 300013\uFF09");
            return {
              success: false,
              isRateLimited: true,
              errorCode: rateLimitCheck.errorCode || "300013",
              error: rateLimitCheck.message || "\u8BBF\u95EE\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5"
            };
          }
          let isNoteNotFound = false;
          try {
            isNoteNotFound = await this.checkIsNoteNotFound();
          } catch (e) {
            console.warn("\u26A0\uFE0F  [\u6D4F\u89C8\u5668] checkIsNoteNotFound \u5931\u8D25:", e.message);
          }
          if (isNoteNotFound) {
            console.warn('\u{1F5D1}\uFE0F  [\u6D4F\u89C8\u5668] \u68C0\u6D4B\u5230"\u9875\u9762\u4E0D\u89C1\u4E86"\uFF0C\u7B14\u8BB0\u5DF2\u88AB\u5220\u9664');
            return { success: false, isNoteNotFound: true, isDeleted: true };
          }
          let isLoginPage = false;
          try {
            isLoginPage = await this.checkIsLoginPage();
          } catch (e) {
            console.warn("\u26A0\uFE0F  [\u6D4F\u89C8\u5668] checkIsLoginPage \u5931\u8D25\uFF0C\u91CD\u8BD5\u4E2D...", e.message);
            await this.randomDelay(1e3, 2e3, "normal");
            isLoginPage = await this.checkIsLoginPage();
          }
          if (isLoginPage) {
            console.warn("\u26A0\uFE0F  [\u6D4F\u89C8\u5668] \u68C0\u6D4B\u5230\u767B\u5F55\u9875\u9762\uFF0CCookie \u53EF\u80FD\u5DF2\u5931\u6548");
            return { success: false, isLoginPage: true };
          }
          console.log("\u2705 [\u6D4F\u89C8\u5668] \u9875\u9762\u52A0\u8F7D\u6210\u529F");
          if (Math.random() > 0.5) {
            await this.simulateMouseMovement();
          }
          await this.simulateReading({
            minTime: 2e3,
            // 最少停留 2 秒
            maxTime: 6e3,
            // 最多停留 6 秒
            scrollDuringRead: true
            // 阅读时随机滚动
          });
          return { success: true, isLoginPage: false, isNoteNotFound: false };
        } catch (error) {
          console.error("\u274C [\u6D4F\u89C8\u5668] \u8BBF\u95EE\u9875\u9762\u5931\u8D25:", error.message);
          return { success: false, error: error.message };
        }
      }
      /**
       * 检查是否为笔记不存在页面（404/已删除）
       * 使用与删除笔记客户端相同的检测逻辑
       *
       * 检测特征：
       * 1. URL包含 errorCode=-510001 或 /404
       * 2. 页面标题或内容包含删除关键词
       * 3. 页面内容过短（<1000字符）
       * 4. 缺少正常内容元素
       */
      async checkIsNoteNotFound() {
        try {
          const currentUrl = this.page.url();
          const deletedPatterns = [
            "404",
            "\u9875\u9762\u4E0D\u89C1\u4E86",
            "\u9875\u9762\u4E0D\u5B58\u5728",
            "\u7B14\u8BB0\u4E0D\u5B58\u5728",
            "\u5185\u5BB9\u5DF2\u5220\u9664",
            "\u5185\u5BB9\u8FDD\u89C4",
            "\u8BE5\u5185\u5BB9\u5DF2\u88AB\u4F5C\u8005\u5220\u9664",
            "\u8BE5\u5185\u5BB9\u6682\u4E0D\u53EF\u89C1",
            "\u8BE5\u5185\u5BB9\u6682\u65F6\u65E0\u6CD5\u67E5\u770B",
            "\u62B1\u6B49\uFF0C\u4F60\u8BBF\u95EE\u7684\u5185\u5BB9\u4E0D\u89C1\u4E86",
            "\u5F53\u524D\u7B14\u8BB0\u6682\u65F6\u65E0\u6CD5\u6D4F\u89C8"
          ];
          const pageInfo = await this.page.evaluate(() => {
            const title = document.title || "";
            const bodyText = document.body.innerText || "";
            const hasContent = !!(document.querySelector(".note-text") || document.querySelector(".content") || document.querySelector(".desc") || document.querySelector('[class*="note"]'));
            return {
              title,
              bodyText,
              bodyLength: bodyText.length,
              hasContent
            };
          });
          const urlHasErrorCode = currentUrl.includes("errorCode=-510001") || currentUrl.includes("/404");
          const lowerTitle = pageInfo.title.toLowerCase();
          const lowerBodyText = pageInfo.bodyText.toLowerCase();
          const hasDeletedPattern = deletedPatterns.some(
            (pattern) => lowerTitle.includes(pattern.toLowerCase()) || lowerBodyText.includes(pattern.toLowerCase())
          );
          const isTooShort = pageInfo.bodyText.length < 1e3;
          const isDeleted = urlHasErrorCode || hasDeletedPattern && !pageInfo.hasContent || hasDeletedPattern && isTooShort || isTooShort && hasDeletedPattern;
          if (isDeleted) {
            console.log(`\u{1F5D1}\uFE0F  [\u5220\u9664\u68C0\u6D4B] \u7B14\u8BB0\u5DF2\u88AB\u5220\u9664`);
            console.log(`   URL\u9519\u8BEF\u7801: ${urlHasErrorCode ? "\u662F" : "\u5426"}`);
            console.log(`   \u9875\u9762\u6807\u9898: ${pageInfo.title}`);
            console.log(`   \u5185\u5BB9\u957F\u5EA6: ${pageInfo.bodyLength} \u5B57\u7B26`);
          }
          return isDeleted;
        } catch (error) {
          console.error("\u274C [\u5220\u9664\u68C0\u6D4B] \u68C0\u67E5\u5931\u8D25:", error.message);
          return false;
        }
      }
      /**
       * 检查Cookie是否有效（基于Cookie的登录状态检测）
       * @returns {Promise<{valid: boolean, reason: string, cookieInfo: object}>}
       */
      async checkCookiesValid() {
        try {
          const cookies = await this.page.cookies();
          const currentUrl = this.page.url();
          const a1Cookie = cookies.find((c) => c.name === "a1");
          const webSessionCookie = cookies.find((c) => c.name === "web_session");
          const xHngCookie = cookies.find((c) => c.name === "x-hng");
          const cookieInfo = {
            hasA1: !!a1Cookie,
            a1Length: a1Cookie?.value?.length || 0,
            hasWebSession: !!webSessionCookie,
            webSessionLength: webSessionCookie?.value?.length || 0,
            hasXHng: !!xHngCookie,
            totalCookies: cookies.length
          };
          const minCookieCount = 12;
          if (cookies.length < minCookieCount) {
            return {
              valid: false,
              reason: `Cookie \u6570\u91CF\u4E0D\u8DB3 (${cookies.length}/${minCookieCount}\uFF0C\u767B\u5F55\u672A\u5B8C\u6210)`,
              cookieInfo
            };
          }
          if (!a1Cookie) {
            return {
              valid: false,
              reason: "\u7F3A\u5C11 a1 Cookie\uFF08\u4E3B\u8981\u8BA4\u8BC1token\uFF09",
              cookieInfo
            };
          }
          if (a1Cookie.value.length < 50) {
            return {
              valid: false,
              reason: `a1 Cookie \u8FC7\u77ED (${a1Cookie.value.length} \u5B57\u7B26\uFF0C\u53EF\u80FD\u5DF2\u5931\u6548\u6216\u672A\u767B\u5F55)`,
              cookieInfo
            };
          }
          if (!webSessionCookie) {
            return {
              valid: false,
              reason: "\u7F3A\u5C11 web_session Cookie\uFF08\u4F1A\u8BDDID\uFF09",
              cookieInfo
            };
          }
          const now = Math.floor(Date.now() / 1e3);
          const oneDay = 24 * 60 * 60;
          if (a1Cookie.expires && a1Cookie.expires < now + oneDay) {
            const expiryDate = new Date(a1Cookie.expires * 1e3);
            console.warn(`   \u26A0\uFE0F [Cookie] a1 \u5373\u5C06\u8FC7\u671F (${expiryDate.toLocaleString("zh-CN")})\uFF0C\u4F46\u4ECD\u53EF\u4F7F\u7528`);
          }
          return {
            valid: true,
            reason: "Cookie \u6709\u6548",
            cookieInfo
          };
        } catch (error) {
          return {
            valid: false,
            reason: `Cookie \u68C0\u6D4B\u51FA\u9519: ${error.message}`,
            cookieInfo: null
          };
        }
      }
      /**
       * 通过API接口验证登录状态
       * 使用用户信息接口验证Cookie是否有效（更稳定）
       * @returns {Promise<{valid: boolean, reason: string, apiResponse: object}>}
       */
      async verifyLoginByAPI() {
        try {
          const cookies = await this.page.cookies();
          const cookieString = cookies.map((c) => `${c.name}=${c.value}`).join("; ");
          const a1Cookie = cookies.find((c) => c.name === "a1");
          const webSessionCookie = cookies.find((c) => c.name === "web_session");
          const hasCookies = cookies.length >= 13;
          const response = await this.page.evaluate(async (cookieStr) => {
            try {
              const endpoints = [
                "https://edith.xiaohongshu.com/api/sns/web/v1/user/selfinfo",
                "https://edith.xiaohongshu.com/api/sns/web/v1/login/activate"
              ];
              for (const url of endpoints) {
                try {
                  const res = await fetch(url, {
                    method: "GET",
                    headers: {
                      "Cookie": cookieStr,
                      "Accept": "application/json, text/plain, */*",
                      "Accept-Language": "zh-CN,zh;q=0.9",
                      "Origin": "https://www.xiaohongshu.com",
                      "Referer": "https://www.xiaohongshu.com/",
                      "Sec-Fetch-Dest": "empty",
                      "Sec-Fetch-Mode": "cors",
                      "Sec-Fetch-Site": "same-site"
                    }
                  });
                  const data = await res.json();
                  if (res.ok) {
                    return { ok: true, status: res.status, data, endpoint: url };
                  }
                } catch (e) {
                  continue;
                }
              }
              return { ok: false, error: "\u6240\u6709\u7AEF\u70B9\u5747\u5931\u8D25" };
            } catch (e) {
              return { ok: false, error: e.message, stack: e.stack };
            }
          }, cookieString);
          if (!response.ok) {
            return {
              valid: false,
              reason: `API\u5931\u8D25: ${response.error || "\u672A\u77E5\u9519\u8BEF"}`,
              apiResponse: response
            };
          }
          const apiData = response.data;
          if (apiData && apiData.success === false) {
            return {
              valid: false,
              reason: `API: ${apiData.msg || apiData.message || "\u672A\u767B\u5F55"}`,
              apiResponse: apiData
            };
          }
          return {
            valid: true,
            reason: "API\u9A8C\u8BC1\u901A\u8FC7",
            apiResponse: apiData
          };
        } catch (error) {
          return {
            valid: false,
            reason: `API\u5F02\u5E38: ${error.message}`,
            apiResponse: null
          };
        }
      }
      /**
       * 检查是否触发访问频率限制（错误代码 300013）
       * 当小红书检测到访问频繁时，会显示"安全限制：访问频繁，请稍后再试"页面
       * @returns {Promise<{isRateLimited: boolean, errorCode?: string, message?: string}>}
       */
      async checkIsRateLimited() {
        try {
          const currentUrl = this.page.url();
          const urlHasRateLimitError = currentUrl.includes("error_code=300013") || currentUrl.includes("errorCode=300013") || currentUrl.includes("error-code=300013");
          if (urlHasRateLimitError) {
            console.log("");
            console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
            console.log("\u{1F6AB} [\u8BBF\u95EE\u9650\u5236] \u68C0\u6D4B\u5230\u9519\u8BEF\u4EE3\u7801 300013");
            console.log("   URL: " + currentUrl);
            console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
            console.log("");
            return { isRateLimited: true, errorCode: "300013", message: "URL\u5305\u542B\u9519\u8BEF\u4EE3\u7801300013" };
          }
          const pageInfo = await this.page.evaluate(() => {
            const bodyText = document.body.innerText || "";
            const title = document.title || "";
            const url = window.location.href;
            const rateLimitPatterns = [
              "\u5B89\u5168\u9650\u5236",
              "\u8BBF\u95EE\u9891\u7E41",
              "\u8BF7\u7A0D\u540E\u518D\u8BD5",
              "300013",
              "\u64CD\u4F5C\u8FC7\u4E8E\u9891\u7E41",
              "\u7CFB\u7EDF\u68C0\u6D4B\u5230\u5F02\u5E38"
            ];
            const matchedPatterns = rateLimitPatterns.filter(
              (pattern) => bodyText.includes(pattern) || title.includes(pattern)
            );
            return {
              title,
              bodyText: bodyText.substring(0, 500),
              // 只取前500字符用于调试
              url,
              matchedPatterns
            };
          });
          if (pageInfo.matchedPatterns.length > 0) {
            console.log("");
            console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
            console.log("\u{1F6AB} [\u8BBF\u95EE\u9650\u5236] \u68C0\u6D4B\u5230\u9650\u6D41\u9875\u9762");
            console.log("   \u5339\u914D\u5173\u952E\u8BCD: " + pageInfo.matchedPatterns.join(", "));
            console.log("   \u9875\u9762\u6807\u9898: " + pageInfo.title);
            console.log("   URL: " + pageInfo.url);
            console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
            console.log("");
            return {
              isRateLimited: true,
              errorCode: "300013",
              message: "\u9875\u9762\u663E\u793A\u9650\u6D41\u63D0\u793A: " + pageInfo.matchedPatterns.join(", ")
            };
          }
          return { isRateLimited: false };
        } catch (error) {
          console.warn("   \u26A0\uFE0F [\u9650\u6D41\u68C0\u6D4B] \u68C0\u6D4B\u5931\u8D25: " + error.message);
          return { isRateLimited: false };
        }
      }
      /**
       * 检查是否为登录页面
       * 优先使用Cookie检测，失败时回退到DOM检测
       */
      async checkIsLoginPage() {
        try {
          console.log(`   [\u767B\u5F55\u68C0\u6D4B] \u7B2C\u4E00\u6B65\uFF1ACookie\u68C0\u6D4B...`);
          const cookieCheck = await this.checkCookiesValid();
          if (!cookieCheck.valid) {
            console.log(`   \u274C [\u767B\u5F55\u68C0\u6D4B] Cookie\u68C0\u6D4B\u5931\u8D25: ${cookieCheck.reason}`);
          } else {
            console.log(`   \u2705 [\u767B\u5F55\u68C0\u6D4B] Cookie\u6709\u6548\uFF0C\u4E0D\u662F\u767B\u5F55\u9875`);
            return false;
          }
          console.log(`   [\u767B\u5F55\u68C0\u6D4B] \u7B2C\u4E8C\u6B65\uFF1ADOM\u68C0\u6D4B...`);
          const loginInfo = await this.page.evaluate(() => {
            const bodyText = document.body.innerText || "";
            const title = document.title || "";
            const loginTexts = [
              "\u767B\u5F55\u540E\u63A8\u8350\u66F4\u61C2\u4F60\u7684\u7B14\u8BB0",
              "\u53EF\u7528\u5C0F\u7EA2\u4E66\u6216\u5FAE\u4FE1\u626B\u7801",
              "\u624B\u673A\u53F7\u767B\u5F55",
              "\u6211\u5DF2\u9605\u8BFB\u5E76\u540C\u610F"
            ];
            const loginTextCount = loginTexts.filter((text) => bodyText.includes(text)).length;
            const passwordInput = document.querySelector('input[type="password"]');
            return {
              title,
              loginTextCount,
              hasPasswordInput: !!passwordInput,
              bodyLength: bodyText.length
            };
          });
          const isLoginPage = loginInfo.loginTextCount >= 3 && loginInfo.hasPasswordInput;
          if (isLoginPage) {
            console.log(`   \u274C [\u767B\u5F55\u68C0\u6D4B] DOM\u68C0\u6D4B\u786E\u8BA4\u662F\u767B\u5F55\u9875 (${loginInfo.loginTextCount}\u4E2A\u767B\u5F55\u7279\u5F81, \u6709\u5BC6\u7801\u6846)`);
          } else {
            console.log(`   \u2705 [\u767B\u5F55\u68C0\u6D4B] DOM\u68C0\u6D4B\uFF1A\u4E0D\u662F\u767B\u5F55\u9875`);
          }
          return isLoginPage;
        } catch (error) {
          console.warn(`   \u26A0\uFE0F [\u767B\u5F55\u68C0\u6D4B] \u68C0\u6D4B\u5931\u8D25: ${error.message}`);
          return false;
        }
      }
      /**
       * 检查是否在正常工作状态（简化版：仅Cookie检测）
       *
       * 注意：此方法应该在采集任务完成后返回搜索页面时调用
       * 不应在启动时或每次操作前调用
       *
       * @returns {Promise<boolean>} true=正常状态(可继续), false=异常页需干预(离线)
       */
      async checkIsLoggedIn() {
        try {
          let currentUrl = this.page ? this.page.url() : "";
          if (currentUrl) {
            try {
              const urlObj = new URL2(currentUrl);
              const hostname = urlObj.hostname.toLowerCase();
              if (hostname.includes("xhslink.com")) {
                console.log(`   \u{1F504} [\u72B6\u6001\u68C0\u6D4B] \u68C0\u6D4B\u5230\u77ED\u94FE\u63A5\u57DF\u540D (${hostname})\uFF0C\u5148\u8DF3\u8F6C\u5230\u5C0F\u7EA2\u4E66\u9996\u9875\u8FDB\u884CCookie\u68C0\u6D4B`);
                await this.page.goto("https://www.xiaohongshu.com", {
                  waitUntil: "domcontentloaded",
                  timeout: 15e3
                });
                await this.sleep(1e3);
                currentUrl = this.page.url();
              }
            } catch (e) {
            }
          }
          console.log(`   [\u72B6\u6001\u68C0\u6D4B] Cookie\u68C0\u6D4B...`);
          const cookieCheck = await this.checkCookiesValid();
          if (!cookieCheck.valid) {
            console.error(`   \u274C [\u72B6\u6001\u68C0\u6D4B] Cookie\u68C0\u6D4B\u5931\u8D25: ${cookieCheck.reason}`);
            const os = require("os");
            const isLocalMachine = os.hostname() === "DESKTOP-HDM9SKA";
            console.error(`   \u274C [\u72B6\u6001\u68C0\u6D4B] Cookie\u5DF2\u5931\u6548\uFF0C${isLocalMachine ? "\u672C\u673A\u4E5F" : ""}\u5C06\u6E05\u9664\u7F13\u5B58\u5E76\u91CD\u65B0\u767B\u5F55`);
            try {
              const cookies = await this.page.cookies();
              for (const cookie of cookies) {
                await this.page.deleteCookie(cookie);
              }
              console.log("   \u{1F5D1}\uFE0F  [\u72B6\u6001\u68C0\u6D4B] \u5DF2\u6E05\u9664\u9875\u9762\u6240\u6709Cookie");
            } catch (e) {
            }
            try {
              await this.page.evaluate(() => {
                localStorage.clear();
                sessionStorage.clear();
              });
              console.log("   \u{1F5D1}\uFE0F  [\u72B6\u6001\u68C0\u6D4B] \u5DF2\u6E05\u9664 LocalStorage \u548C SessionStorage");
            } catch (e) {
            }
            const userDataDir = this.getUserDataDir();
            this.clearCache(userDataDir, true);
            console.error(`   \u274C [\u72B6\u6001\u68C0\u6D4B] Cookie\u5DF2\u6E05\u9664\uFF0C\u9700\u8981\u5237\u65B0\u9875\u9762\u91CD\u65B0\u767B\u5F55`);
            return false;
          }
          console.log(`   \u2705 [\u72B6\u6001\u68C0\u6D4B] Cookie\u6709\u6548`);
          console.log(`   \u{1F4CA} [\u72B6\u6001\u68C0\u6D4B] a1\u957F\u5EA6: ${cookieCheck.cookieInfo.a1Length}, webSession: ${cookieCheck.cookieInfo.hasWebSession ? "\u2705" : "\u274C"}`);
          currentUrl = this.page.url();
          const pageTitle = this.page ? await this.page.title() : "";
          if (currentUrl.includes("/web/login") || currentUrl.includes("/login") || currentUrl.includes("signin")) {
            console.log(`   \u{1F504} [\u72B6\u6001\u68C0\u6D4B] Cookie\u6709\u6548\u4F46URL\u5728\u767B\u5F55\u9875 (${currentUrl})\uFF0C\u8DF3\u8F6C\u5230\u9996\u9875\u9A8C\u8BC1...`);
            try {
              await this.page.goto("https://www.xiaohongshu.com", {
                waitUntil: "domcontentloaded",
                timeout: 15e3
              });
              await this.randomDelay(1e3, 2e3, "normal");
              console.log(`   \u2705 [\u72B6\u6001\u68C0\u6D4B] \u5DF2\u8DF3\u8F6C\u5230\u9996\u9875`);
            } catch (e) {
              console.warn(`   \u26A0\uFE0F  [\u72B6\u6001\u68C0\u6D4B] \u8DF3\u8F6C\u9996\u9875\u5931\u8D25: ${e.message}`);
            }
          }
          console.log(`   \u23F3 [\u72B6\u6001\u68C0\u6D4B] \u7B49\u5F85\u9875\u9762\u5B8C\u5168\u52A0\u8F7D...`);
          try {
            await this.page.waitForNetworkIdle({ idleTime: 500, timeout: 5e3 }).catch(() => {
            });
            await this.randomDelay(1e3, 2e3, "normal");
            console.log(`   \u2705 [\u72B6\u6001\u68C0\u6D4B] \u9875\u9762\u52A0\u8F7D\u5B8C\u6210`);
          } catch (e) {
            await this.randomDelay(1500, 2500, "normal");
          }
          const currentUrlAfterJump = this.page.url();
          if (currentUrlAfterJump.includes("/web/login") || currentUrlAfterJump.includes("/login") || currentUrlAfterJump.includes("signin")) {
            console.error(`   \u274C [\u72B6\u6001\u68C0\u6D4B] \u8DF3\u8F6C\u540EURL\u4ECD\u5728\u767B\u5F55\u9875: ${currentUrlAfterJump}`);
            return false;
          }
          const hasProfileButton = await this.page.evaluate(() => {
            const profileLink = document.querySelector('a[href*="/user/profile/"]');
            if (profileLink) {
              const text = profileLink.textContent || "";
              return text.includes("\u6211");
            }
            return false;
          });
          if (hasProfileButton) {
            console.log(`   \u2705 [\u72B6\u6001\u68C0\u6D4B] DOM\u68C0\u6D4B\uFF1A\u627E\u5230"\u6211"\u6309\u94AE\uFF0C\u786E\u8BA4\u5DF2\u767B\u5F55`);
            return true;
          }
          const hasLoginElements = await this.page.evaluate(() => {
            const loginContainer = document.querySelector(".login-container");
            if (loginContainer) return true;
            const qrcodeImg = document.querySelector('.qrcode-img, img[class*="qrcode"], img[class*="qr-code"]');
            if (qrcodeImg) return true;
            return false;
          });
          if (hasLoginElements) {
            console.error(`   \u274C [\u72B6\u6001\u68C0\u6D4B] \u68C0\u6D4B\u5230\u767B\u5F55\u9875\u9762\u5143\u7D20\uFF08\u767B\u5F55\u5BB9\u5668/\u4E8C\u7EF4\u7801\uFF09`);
            return false;
          }
          const pageContent = await this.page.evaluate(() => {
            return {
              bodyText: document.body ? document.body.innerText : "",
              bodyLength: document.body ? document.body.innerText.length : 0
            };
          });
          if (pageContent.bodyText.includes("\u8BF7\u901A\u8FC7\u9A8C\u8BC1") || pageContent.bodyText.includes("\u6ED1\u52A8\u9A8C\u8BC1") || pageContent.bodyText.includes("\u8BF7\u5B8C\u6210\u9A8C\u8BC1")) {
            console.error(`   \u274C [\u72B6\u6001\u68C0\u6D4B] \u68C0\u6D4B\u5230\u9A8C\u8BC1\u7801\u9875\u9762`);
            return false;
          }
          if (pageContent.bodyLength < 2e3) {
            const loginGuidanceTexts = [
              "\u9A6C\u4E0A\u767B\u5F55\u5373\u53EF",
              "\u5237\u5230\u66F4\u61C2\u4F60\u7684\u4F18\u8D28\u5185\u5BB9",
              "\u641C\u7D22\u6700\u65B0\u79CD\u8349\u3001\u62D4\u8349\u4FE1\u606F",
              "\u67E5\u770B\u6536\u85CF\u3001\u70B9\u8D5E\u7684\u7B14\u8BB0",
              "\u4E0E\u4ED6\u4EBA\u66F4\u597D\u5730\u4E92\u52A8\u3001\u4EA4\u6D41",
              "\u626B\u7801\u767B\u5F55",
              "\u8BF7\u5148\u767B\u5F55",
              "\u767B\u5F55\u540E\u63A8\u8350"
            ];
            const lowerText = pageContent.bodyText.toLowerCase();
            const hasLoginText = loginGuidanceTexts.some(
              (text) => lowerText.includes(text.toLowerCase())
            );
            if (hasLoginText) {
              console.error(`   \u274C [\u72B6\u6001\u68C0\u6D4B] \u68C0\u6D4B\u5230\u767B\u5F55\u5F15\u5BFC\u6587\u6848`);
              return false;
            }
          }
          return true;
        } catch (error) {
          console.error(`   \u274C [\u72B6\u6001\u68C0\u6D4B] \u68C0\u67E5\u8FC7\u7A0B\u51FA\u9519: ${error.message}`);
          return false;
        }
      }
      /**
       * 通用方法：检测笔记是否已被小红书删除
       * @param {string} noteUrl - 笔记URL
       * @param {Object} options - 配置选项
       * @param {boolean} options.checkLogin - 是否检查登录状态（默认 true）
       * @param {string[]} options.deletedPatterns - 删除标记模式（可选，使用默认）
       * @returns {Promise<{isDeleted: boolean, isAccountOffline?: boolean, reason: string}>}
       */
      async checkNoteDeleted(noteUrl, options = {}) {
        const { checkLogin = true, deletedPatterns = null } = options;
        const defaultDeletedPatterns = [
          "\u9875\u9762\u4E0D\u5B58\u5728",
          "\u7B14\u8BB0\u4E0D\u5B58\u5728",
          "\u5185\u5BB9\u4E0D\u5B58\u5728",
          "\u5F53\u524D\u7B14\u8BB0\u6682\u65F6\u65E0\u6CD5\u6D4F\u89C8",
          "404",
          "\u7B14\u8BB0\u5DF2\u5220\u9664",
          "\u5DF2\u4E0B\u67B6",
          "\u62B1\u6B49",
          "\u65E0\u6CD5\u8BBF\u95EE"
        ];
        const patterns = deletedPatterns || defaultDeletedPatterns;
        try {
          await this.page.goto(noteUrl, { waitUntil: "networkidle2", timeout: 15e3 });
          await this.sleep(1500);
          if (checkLogin) {
            const isLoggedIn = await this.checkIsLoggedIn();
            if (!isLoggedIn) {
              return { isDeleted: false, isAccountOffline: true, reason: "\u5C0F\u7EA2\u4E66\u8D26\u53F7\u5DF2\u6389\u7EBF" };
            }
          }
          const currentUrl = this.page.url();
          if (currentUrl.includes("error_code=300013") || currentUrl.includes("errorCode=300013") || currentUrl.includes("error-code=300013")) {
            throw new Error("\u8BBF\u95EE\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
          }
          const pageTitle = await this.page.title();
          const pageText = await this.page.evaluate(() => document.body.innerText);
          const lowerText = pageText.toLowerCase() + pageTitle.toLowerCase();
          const hasDeletedPattern = patterns.some(
            (pattern) => lowerText.includes(pattern.toLowerCase())
          );
          if (hasDeletedPattern) {
            return { isDeleted: true, reason: "\u9875\u9762\u663E\u793A\u7B14\u8BB0\u4E0D\u5B58\u5728" };
          }
          const hasContent = await this.page.evaluate(() => {
            return !!(document.querySelector(".note-text") || document.querySelector(".content") || document.querySelector(".desc") || document.querySelector('[class*="note"]'));
          });
          if (!hasContent && pageText.length < 1e3) {
            return { isDeleted: true, reason: "\u9875\u9762\u5185\u5BB9\u8FC7\u77ED\uFF0C\u53EF\u80FD\u5DF2\u5220\u9664" };
          }
          return { isDeleted: false, reason: "\u7B14\u8BB0\u6B63\u5E38" };
        } catch (error) {
          console.log(`   ? \u5220\u9664\u68C0\u6D4B\u5931\u8D25: ${error.message}`);
          return { isDeleted: false, reason: `\u68C0\u6D4B\u5931\u8D25: ${error.message}` };
        }
      }
      /**
       * 检查登录弹窗是否存在（用于自动检测登录完成）
       * @returns {Promise<boolean>} true=弹窗存在(未登录), false=弹窗消失(已登录)
       */
      async checkLoginModalExists() {
        try {
          const result = await this.page.evaluate(() => {
            const overlay = document.querySelector('.modal-overlay, .dialog-overlay, [class*="mask"], [class*="overlay"]');
            const loginModal = document.querySelector('.login-modal, .auth-container, .sign-container, [class*="login-modal"], [id*="login-modal"]');
            const passwordInput = document.querySelector('input[type="password"]');
            const bodyText = document.body.innerText || "";
            const loginTexts = ["\u626B\u7801\u767B\u5F55", "\u5FAE\u4FE1\u626B\u7801", "\u624B\u673A\u53F7\u767B\u5F55", "\u9A8C\u8BC1\u7801"];
            const loginTextCount = loginTexts.filter((t) => bodyText.includes(t)).length;
            let hasOverlay = false;
            if (overlay) {
              const styles = window.getComputedStyle(overlay);
              hasOverlay = styles.display !== "none" && styles.visibility !== "hidden";
            }
            let hasModal = false;
            if (loginModal) {
              const styles = window.getComputedStyle(loginModal);
              hasModal = styles.display !== "none" && styles.visibility !== "hidden";
            }
            return {
              hasOverlay,
              hasModal,
              hasPasswordInput: !!passwordInput,
              loginTextCount
            };
          });
          const hasLoginModal = result.hasOverlay || result.hasModal || result.hasPasswordInput || result.loginTextCount >= 3;
          return hasLoginModal;
        } catch (error) {
          return false;
        }
      }
      /**
       * 检测页面上是否存在登录后的元素
       * 登录后应该有：用户头像、导航栏中的"我"等元素
       * @returns {Promise<{valid: boolean, reason: string, element?: string}>}
       */
      async checkLoginElements() {
        try {
          const result = await this.page.evaluate(() => {
            const loginSelectors = [
              ".login-container",
              ".qrcode-container",
              '[class*="login-modal"]',
              '[class*="login-dialog"]',
              ".signin-container",
              '[class*="qrcode"][class*="login"]'
            ];
            for (const selector of loginSelectors) {
              const element = document.querySelector(selector);
              if (element && element.offsetParent !== null) {
                const style = window.getComputedStyle(element);
                if (style.display !== "none" && style.visibility !== "hidden") {
                  return {
                    valid: false,
                    reason: "\u4ECD\u663E\u793A\u767B\u5F55\u5F39\u7A97"
                  };
                }
              }
            }
            const url = window.location.href;
            if (url.includes("/login") || url.includes("/signin")) {
              return {
                valid: false,
                reason: "\u4ECD\u5728\u767B\u5F55\u9875"
              };
            }
            const hasQRCode = document.querySelector('img[src*="qrcode"], img[alt*="\u4E8C\u7EF4\u7801"], canvas[aria-label*="\u4E8C\u7EF4\u7801"]');
            if (hasQRCode && hasQRCode.offsetParent !== null) {
              return {
                valid: false,
                reason: "\u4ECD\u663E\u793A\u4E8C\u7EF4\u7801"
              };
            }
            const loggedInSelectors = [
              'a[href*="/user/profile/"]',
              // 用户资料链接（带ID）
              '.avatar-wrapper[href*="user"]',
              // 带用户链接的头像
              '[class*="user"][class*="info"]',
              // 用户信息区域
              '.nav-item[href*="/user/"]'
              // 导航中的用户链接
            ];
            for (const selector of loggedInSelectors) {
              const element = document.querySelector(selector);
              if (element && element.offsetParent !== null) {
                return {
                  valid: true,
                  element: selector
                };
              }
            }
            return {
              valid: false,
              reason: "\u672A\u627E\u5230\u767B\u5F55\u540E\u9875\u9762\u5143\u7D20"
            };
          });
          return result;
        } catch (error) {
          return {
            valid: false,
            reason: `\u9875\u9762\u68C0\u6D4B\u5F02\u5E38: ${error.message}`
          };
        }
      }
      /**
       * 自动等待用户登录
       * Cookie 检测 + 页面元素检测（双重确认）
       * @param {Object} options - 配置选项
       * @param {number} options.maxWaitTime - 最大等待时间（毫秒），默认 300000（5分钟）
       * @param {number} options.checkInterval - 检查间隔（毫秒），默认 5000（5秒）
       * @returns {Promise<{valid: boolean, reason: string, cookieInfo?: object, element?: string}>}
       */
      async waitForLogin(options = {}) {
        const maxWaitTime = options.maxWaitTime || 3e5;
        const checkInterval = options.checkInterval || 5e3;
        const startTime = Date.now();
        console.log("");
        console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
        console.log("\u{1F4F1} \u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u767B\u5F55\uFF1A");
        console.log("   1. \u4F7F\u7528\u5FAE\u4FE1\u626B\u7801");
        console.log("   2. \u8F93\u5165\u624B\u673A\u9A8C\u8BC1\u7801\uFF08\u5982\u679C\u9700\u8981\uFF09");
        console.log("   3. \u5B8C\u6210\u6240\u6709\u9A8C\u8BC1\u6B65\u9AA4");
        console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
        console.log("");
        console.log("\u23F3 \u68C0\u6D4B\u767B\u5F55\u72B6\u6001\uFF08Cookie + \u9875\u9762\u5143\u7D20\uFF09...");
        console.log("");
        const os = require("os");
        if (os.hostname() !== "DESKTOP-HDM9SKA") {
          const existingCookies = await this.page.cookies();
          if (existingCookies.length > 0) {
            console.log(`\u{1F5D1}\uFE0F  [Cookie] \u6E05\u9664 ${existingCookies.length} \u4E2A\u6B8B\u7559 Cookie...`);
            for (const cookie of existingCookies) {
              await this.page.deleteCookie(cookie);
            }
            console.log("\u2705 [Cookie] \u6B8B\u7559 Cookie \u5DF2\u6E05\u9664");
          }
          try {
            await this.page.evaluate(() => {
              localStorage.clear();
              sessionStorage.clear();
            });
            console.log("\u2705 [\u5B58\u50A8] Local Storage \u548C Session Storage \u5DF2\u6E05\u9664");
          } catch (e) {
          }
        } else {
          console.log("   \u2139\uFE0F  [Cookie] \u672C\u673A\u6A21\u5F0F\uFF0C\u8DF3\u8FC7\u6E05\u9664\u6B8B\u7559 Cookie");
        }
        console.log("");
        while (Date.now() - startTime < maxWaitTime) {
          const elapsed = Math.floor((Date.now() - startTime) / 1e3);
          const cookieCheck = await this.checkCookiesValid();
          const info = cookieCheck.cookieInfo || {};
          const hasA1 = info.hasA1 ? "\u2705" : "\u274C";
          const hasWebSession = info.hasWebSession ? "\u2705" : "\u274C";
          const cookieCount = info.totalCookies || 0;
          if (!cookieCheck.valid) {
            process.stdout.write(`\r\u23F3 \u7B49\u5F85\u767B\u5F55... (${elapsed}\u79D2) Cookie:${cookieCount} a1:${hasA1} web_session:${hasWebSession} [${cookieCheck.reason}]   `);
            process.stdout.flush && process.stdout.flush();
            await this.sleep(checkInterval);
            continue;
          }
          process.stdout.write(`\r\u23F3 Cookie\u5DF2\u83B7\u53D6\uFF0C\u7B49\u5F85\u9875\u9762\u5B8C\u5168\u52A0\u8F7D... (${elapsed}\u79D2)   `);
          process.stdout.flush && process.stdout.flush();
          await this.sleep(3e3);
          const elementCheck = await this.checkLoginElements();
          if (!elementCheck.valid) {
            process.stdout.write(`\r\u23F3 Cookie\u6709\u6548\u4F46\u68C0\u6D4B\u9875\u9762\u5143\u7D20... (${elapsed}\u79D2) [${elementCheck.reason}]   `);
            process.stdout.flush && process.stdout.flush();
            await this.sleep(checkInterval);
            continue;
          }
          console.log("\n\u2705 \u767B\u5F55\u9A8C\u8BC1\u901A\u8FC7\uFF01");
          console.log(`   \u8017\u65F6: ${elapsed} \u79D2`);
          console.log(`   Cookie: ${cookieCount} \u4E2A | a1: ${info.a1Length}\u5B57\u7B26 | web_session: \u2705`);
          console.log(`   \u9875\u9762\u5143\u7D20: ${elementCheck.element || "\u7528\u6237\u5934\u50CF/\u5BFC\u822A"}`);
          return {
            valid: true,
            reason: "\u767B\u5F55\u9A8C\u8BC1\u901A\u8FC7",
            cookieInfo: info,
            element: elementCheck.element
          };
        }
        console.log("\r");
        console.log("\u274C \u767B\u5F55\u8D85\u65F6\uFF0C\u672A\u8FBE\u5230\u5B8C\u6574\u767B\u5F55\u72B6\u6001");
        return {
          valid: false,
          reason: "\u767B\u5F55\u8D85\u65F6"
        };
      }
      /**
       * 滚动页面加载评论（优化速度版）
       */
      async scrollToLoadComments() {
        console.log("\u{1F4DC} [\u6D4F\u89C8\u5668] \u5F00\u59CB\u6EDA\u52A8\u52A0\u8F7D\u8BC4\u8BBA...");
        try {
          await this.randomDelay(1500, 3e3, "normal");
          const isReady = await this.page.evaluate(() => {
            if (!document.body) return false;
            const bodyHeight = document.body.scrollHeight || document.body.offsetHeight || 0;
            const mainContainer = document.querySelector('#app, #main, [class*="app"], [class*="container"], [class*="wrapper"]');
            const containerHeight = mainContainer ? mainContainer.scrollHeight || mainContainer.offsetHeight || 0 : 0;
            return bodyHeight > 100 || containerHeight > 100;
          });
          if (!isReady) {
            console.warn("\u26A0\uFE0F [\u6D4F\u89C8\u5668] \u9875\u9762\u672A\u5C31\u7EEA\uFF0C\u7B49\u5F85\u66F4\u957F\u65F6\u95F4...");
            await this.randomDelay(4e3, 7e3, "normal");
            const debugInfo = await this.page.evaluate(() => {
              if (!document.body) {
                return { error: "no body" };
              }
              return {
                bodyHeight: document.body.scrollHeight,
                bodyOffset: document.body.offsetHeight,
                bodyChildren: document.body.children.length,
                html: document.body.innerHTML.substring(0, 500)
              };
            });
            console.log("\u{1F50D} \u8C03\u8BD5\u4FE1\u606F:", debugInfo);
          }
          console.log('\u{1F50D} \u67E5\u627E"\u5C55\u5F00\u66F4\u591A"\u6309\u94AE...');
          const expandButtonSelectors = [
            "span.more-text",
            ".expand-btn",
            ".more-btn",
            '[class*="expand"]',
            '[class*="more"]',
            'button[class*="more"]'
          ];
          for (const selector of expandButtonSelectors) {
            try {
              const elements = await this.page.$$(selector);
              for (const element of elements) {
                const text = await element.evaluate((el) => el.textContent?.trim() || "");
                if (text.includes("\u5C55\u5F00") || text.includes("\u66F4\u591A") || text.includes("\u5168\u90E8") || text.includes("\u67E5\u770B")) {
                  console.log(`\u2705 \u70B9\u51FB\u6309\u94AE: "${text}"`);
                  try {
                    const box = await element.boundingBox();
                    if (box) {
                      const targetX = box.x + box.width / 2 + (Math.random() - 0.5) * box.width * 0.5;
                      const targetY = box.y + box.height / 2 + (Math.random() - 0.5) * box.height * 0.5;
                      await this.moveMouse({ x: targetX, y: targetY });
                      await this.sleep(100 + Math.random() * 150);
                      await this.page.mouse.click(targetX, targetY);
                      console.log(`   \u{1F5B1}\uFE0F  \u4EBA\u7C7B\u5316\u70B9\u51FB @ (${Math.round(targetX)}, ${Math.round(targetY)})`);
                    } else {
                      await element.click();
                    }
                  } catch (e) {
                    await element.evaluate((el) => el.click());
                  }
                  await this.randomDelay(1e3, 2e3, "normal");
                }
              }
            } catch (e) {
            }
          }
          console.log("\u{1F4DC} \u5F00\u59CB\u6EDA\u52A8\u52A0\u8F7D\u8BC4\u8BBA...");
          let previousHeight = 0;
          let scrollCount = 0;
          let noChangeCount = 0;
          let zeroHeightCount = 0;
          const maxNoChange = 2;
          const maxScrolls = 15;
          const maxZeroHeight = 5;
          while (scrollCount < maxScrolls && noChangeCount < maxNoChange && zeroHeightCount < maxZeroHeight) {
            let currentHeight = 0;
            try {
              currentHeight = await this.page.evaluate(() => {
                if (!document.body) return 0;
                let height = document.body.scrollHeight || 0;
                if (height === 0) {
                  height = document.body.offsetHeight || 0;
                }
                if (height === 0) {
                  height = document.documentElement.scrollHeight || 0;
                }
                if (height === 0) {
                  const containers = document.querySelectorAll('#app, #main, [class*="app"], [class*="container"], [class*="wrapper"]');
                  for (const container of containers) {
                    const h = container.scrollHeight || container.offsetHeight || 0;
                    if (h > height) height = h;
                  }
                }
                return height;
              });
            } catch (e) {
              console.warn("\u26A0\uFE0F \u83B7\u53D6\u9875\u9762\u9AD8\u5EA6\u5931\u8D25\uFF0C\u5C1D\u8BD5\u91CD\u8BD5...");
              await this.sleep(500);
              zeroHeightCount++;
              continue;
            }
            if (currentHeight === 0) {
              zeroHeightCount++;
              console.warn(`\u26A0\uFE0F \u9875\u9762\u9AD8\u5EA6\u4E3A0 (${zeroHeightCount}/${maxZeroHeight})\uFF0C\u53EF\u80FD\u9875\u9762\u672A\u52A0\u8F7D\u5B8C\u6210`);
              if (zeroHeightCount >= maxZeroHeight) {
                console.error("\u274C \u9875\u9762\u9AD8\u5EA6\u6301\u7EED\u4E3A0\uFF0C\u8DF3\u8FC7\u6B64\u7B14\u8BB0\u7684\u6EDA\u52A8");
                break;
              }
              await this.randomDelay(1500, 3e3, "normal");
              continue;
            }
            zeroHeightCount = 0;
            try {
              await this.page.evaluate(() => {
                if (document.body) {
                  const scrollHeight = document.body.scrollHeight || document.documentElement.scrollHeight || 0;
                  const viewportHeight = window.innerHeight || 0;
                  const randomOffset = Math.floor(Math.random() * 500) + 300;
                  const targetPosition = Math.max(0, scrollHeight - viewportHeight - randomOffset);
                  window.scrollTo({
                    top: targetPosition,
                    behavior: "smooth"
                  });
                } else {
                  window.scrollTo(0, document.documentElement.scrollHeight);
                }
              });
            } catch (e) {
              console.warn("\u26A0\uFE0F \u6EDA\u52A8\u6267\u884C\u5931\u8D25\uFF0C\u8DF3\u8FC7\u672C\u6B21:", e.message);
              await this.randomDelay(300, 600, "normal");
              continue;
            }
            scrollCount++;
            await this.randomDelay(1e3, 2e3, "normal");
            let newHeight = 0;
            try {
              newHeight = await this.page.evaluate(() => {
                if (!document.body) return 0;
                return document.body.scrollHeight || document.body.offsetHeight || 0;
              });
            } catch (e) {
              newHeight = currentHeight;
            }
            if (newHeight === currentHeight) {
              noChangeCount++;
              console.log(`\u23F8\uFE0F \u9AD8\u5EA6\u672A\u53D8\u5316 (${noChangeCount}/${maxNoChange})`);
              if (noChangeCount < maxNoChange) {
                try {
                  await this.page.evaluate(() => window.scrollBy(0, -200));
                  await this.randomDelay(300, 600, "normal");
                  await this.page.evaluate(() => window.scrollBy(0, 300));
                  await this.randomDelay(800, 1500, "normal");
                  const checkHeight = await this.page.evaluate(() => {
                    if (!document.body) return 0;
                    return document.body.scrollHeight || 0;
                  });
                  if (checkHeight > newHeight) {
                    noChangeCount = 0;
                  }
                } catch (e) {
                }
              }
            } else {
              noChangeCount = 0;
              console.log(`\u{1F4DC} \u6EDA\u52A8 ${scrollCount}: ${currentHeight}px \u2192 ${newHeight}px`);
            }
            previousHeight = newHeight;
          }
          if (zeroHeightCount >= maxZeroHeight) {
            console.warn("\u26A0\uFE0F \u9875\u9762\u9AD8\u5EA6\u68C0\u6D4B\u8D85\u65F6\uFF0C\u8DF3\u8FC7\u6EDA\u52A8\u6B65\u9AA4");
          } else {
            console.log(`\u2705 \u6EDA\u52A8\u5B8C\u6210: \u5171\u6EDA\u52A8 ${scrollCount} \u6B21`);
          }
          console.log(`\u23F3 \u7B49\u5F85\u8BC4\u8BBA\u6E32\u67D3\u5B8C\u6210...`);
          await this.randomDelay(2e3, 4e3, "normal");
          try {
            const finalStats = await this.page.evaluate(() => {
              if (!document.body) {
                return { bodyHeight: 0, commentElements: 0 };
              }
              const commentElements = document.querySelectorAll('[class*="comment"], .comment-list, .list-container');
              return {
                bodyHeight: document.body.scrollHeight,
                commentElements: commentElements.length
              };
            });
            console.log(`\u{1F4CA} \u9875\u9762\u9AD8\u5EA6 ${finalStats.bodyHeight}px, \u8BC4\u8BBA\u5143\u7D20 ${finalStats.commentElements} \u4E2A`);
          } catch (e) {
            console.warn("\u26A0\uFE0F \u83B7\u53D6\u6700\u7EC8\u7EDF\u8BA1\u5931\u8D25:", e.message);
          }
          return true;
        } catch (error) {
          console.error("\u274C [\u6D4F\u89C8\u5668] \u6EDA\u52A8\u5931\u8D25:", error.message);
          return false;
        }
      }
      /**
       * 提取页面评论（增强版：多方法提取）
       */
      async extractComments() {
        console.log("\u{1F4DD} [\u6D4F\u89C8\u5668] \u63D0\u53D6\u8BC4\u8BBA...");
        try {
          const comments = await this.page.evaluate(() => {
            const results = [];
            const commentContainers = document.querySelectorAll(".list-container .right, .comments-container .right, .right");
            commentContainers.forEach((container) => {
              const contentSelectors = [".content", '[class*="content"]', ".note-text", '[class*="text"]'];
              let contentText = null;
              for (const selector of contentSelectors) {
                const contentElement = container.querySelector(selector);
                if (contentElement) {
                  contentText = contentElement.textContent?.trim();
                  if (contentText) break;
                }
              }
              const authorSelectors = [
                ".author-wrapper",
                ".author-name",
                ".nickname",
                ".user-name",
                '[class*="author"] [class*="name"]',
                '[class*="author"]',
                '[class*="user"]',
                '[class*="name"]',
                ".name"
              ];
              let authorText = null;
              for (const selector of authorSelectors) {
                const authorElement = container.querySelector(selector);
                if (authorElement) {
                  authorText = authorElement.textContent?.trim();
                  if (authorText) break;
                }
              }
              if (contentText && contentText.length > 0) {
                results.push({
                  text: contentText,
                  author: authorText,
                  method: "container"
                });
              }
            });
            if (results.length === 0) {
              const contentElements = document.querySelectorAll('.note-text, [class*="comment"] [class*="text"], [class*="comment"] [class*="content"], [class*="content"]');
              contentElements.forEach((contentEl) => {
                const contentText = contentEl.textContent?.trim();
                if (contentText && contentText.length > 0) {
                  let authorText = null;
                  let parent = contentEl.parentElement;
                  let searchDepth = 0;
                  while (parent && searchDepth < 8) {
                    const authorSelectors = [
                      ".author-wrapper",
                      ".author-name",
                      ".nickname",
                      ".user-name",
                      '[class*="author"] [class*="name"]',
                      '[class*="author"]',
                      '[class*="user"]',
                      '[class*="name"]',
                      ".name"
                    ];
                    for (const selector of authorSelectors) {
                      const authorEl = parent.querySelector(selector);
                      if (authorEl) {
                        authorText = authorEl.textContent?.trim();
                        if (authorText) break;
                      }
                    }
                    if (authorText) break;
                    const siblings = parent.children;
                    for (let sibling of siblings) {
                      if (sibling !== contentEl) {
                        for (const selector of authorSelectors) {
                          const authorEl = sibling.querySelector ? sibling.querySelector(selector) : null;
                          if (authorEl) {
                            authorText = authorEl.textContent?.trim();
                            if (authorText) break;
                          }
                        }
                        if (authorText) break;
                      }
                    }
                    if (authorText) break;
                    parent = parent.parentElement;
                    searchDepth++;
                  }
                  results.push({
                    text: contentText,
                    author: authorText,
                    method: "upward"
                  });
                }
              });
            }
            if (results.length === 0) {
              console.log("\u4F7F\u7528\u515C\u5E95\u65B9\u6CD5\u67E5\u627E\u8BC4\u8BBA\u548C\u4F5C\u8005\u914D\u5BF9");
              const allContents = [];
              const contentSelectors = [".content", '[class*="content"]', ".note-text", '[class*="text"]'];
              contentSelectors.forEach((selector) => {
                document.querySelectorAll(selector).forEach((el) => {
                  const text = el.textContent?.trim();
                  if (text && text.length > 5 && text.length < 500) {
                    allContents.push({
                      element: el,
                      text,
                      rect: el.getBoundingClientRect()
                    });
                  }
                });
              });
              const allAuthors = [];
              const authorSelectors = [
                ".author-wrapper",
                ".author-name",
                ".nickname",
                ".user-name",
                '[class*="author"] [class*="name"]',
                '[class*="author"]',
                '[class*="user"]',
                '[class*="name"]',
                ".name"
              ];
              authorSelectors.forEach((selector) => {
                document.querySelectorAll(selector).forEach((el) => {
                  const text = el.textContent?.trim();
                  if (text && text.length > 0 && text.length < 50) {
                    allAuthors.push({
                      element: el,
                      text,
                      rect: el.getBoundingClientRect()
                    });
                  }
                });
              });
              allContents.forEach((content) => {
                let closestAuthor = null;
                let minDistance = Infinity;
                allAuthors.forEach((author) => {
                  const verticalDistance = Math.abs(content.rect.top - author.rect.top);
                  const horizontalDistance = Math.abs(content.rect.left - author.rect.left);
                  if (verticalDistance < 100 && horizontalDistance < 200 && verticalDistance < minDistance) {
                    minDistance = verticalDistance;
                    closestAuthor = author;
                  }
                });
                if (closestAuthor) {
                  results.push({
                    text: content.text,
                    author: closestAuthor.text,
                    method: "position"
                  });
                }
              });
            }
            return results;
          });
          console.log(`\u2705 [\u6D4F\u89C8\u5668] \u63D0\u53D6\u5230 ${comments.length} \u6761\u8BC4\u8BBA`);
          if (comments.length > 0) {
            console.log("   \u524D5\u6761\u8BC4\u8BBA:");
            for (let i = 0; i < Math.min(5, comments.length); i++) {
              const preview = comments[i].text?.substring(0, 40);
              const author = comments[i].author || "\u672A\u77E5";
              const method = comments[i].method || "unknown";
              console.log(`   ${i + 1}. "${preview}..." (\u4F5C\u8005: ${author}, \u65B9\u6CD5: ${method})`);
            }
          }
          return comments;
        } catch (error) {
          console.error("\u274C [\u6D4F\u89C8\u5668] \u63D0\u53D6\u8BC4\u8BBA\u5931\u8D25:", error.message);
          return [];
        }
      }
      /**
       * 移除小红书表情标签（如[doge]、[smile]等）
       */
      removeEmojiTags(text) {
        if (!text) return "";
        return text.replace(/\[[^\]]+\]/g, "").trim();
      }
      /**
       * 计算两个字符串的相似度（编辑距离算法）
       */
      calculateSimilarity(str1, str2) {
        if (!str1 || !str2) return 0;
        const longer = str1.length > str2.length ? str1 : str2;
        const shorter = str1.length > str2.length ? str2 : str1;
        if (longer.length === 0) return 1;
        const editDistance = this.levenshteinDistance(longer, shorter);
        return (longer.length - editDistance) / longer.length;
      }
      /**
       * 计算编辑距离
       */
      levenshteinDistance(str1, str2) {
        const matrix = [];
        for (let i = 0; i <= str2.length; i++) {
          matrix[i] = [i];
        }
        for (let j = 0; j <= str1.length; j++) {
          matrix[0][j] = j;
        }
        for (let i = 1; i <= str2.length; i++) {
          for (let j = 1; j <= str1.length; j++) {
            if (str2.charAt(i - 1) === str1.charAt(j - 1)) {
              matrix[i][j] = matrix[i - 1][j - 1];
            } else {
              matrix[i][j] = Math.min(
                matrix[i - 1][j - 1] + 1,
                matrix[i][j - 1] + 1,
                matrix[i - 1][j] + 1
              );
            }
          }
        }
        return matrix[str2.length][str1.length];
      }
      /**
       * 检查两个字符串是否有共同的词汇
       */
      hasCommonWords(str1, str2) {
        if (!str1 || !str2) return false;
        const words1 = str1.split(/[\s\u3000\uff0c\uff1f\uff01\uff0e\u3001\u3002]+/).filter((w) => w.length > 1);
        const words2 = str2.split(/[\s\u3000\uff0c\uff1f\uff01\uff0e\u3001\u3002]+/).filter((w) => w.length > 1);
        const commonWords = words1.filter((word) => words2.some((w2) => w2.includes(word) || word.includes(w2)));
        return commonWords.length >= 2;
      }
      /**
       * 验证目标评论是否存在（增强版：使用服务器端匹配逻辑）
       */
      async verifyComment(targetComment, targetAuthor) {
        console.log(`\u{1F50D} [\u6D4F\u89C8\u5668] \u9A8C\u8BC1\u8BC4\u8BBA...`);
        console.log(`   \u76EE\u6807\u5185\u5BB9: ${targetComment?.substring(0, 30)}...`);
        console.log(`   \u76EE\u6807\u4F5C\u8005: ${targetAuthor}`);
        const comments = await this.extractComments();
        if (!targetComment) {
          console.warn("\u26A0\uFE0F  \u76EE\u6807\u8BC4\u8BBA\u4E3A\u7A7A\uFF0C\u8DF3\u8FC7\u9A8C\u8BC1");
          return {
            found: false,
            confidence: 0,
            targetComment: "",
            targetAuthor: "",
            matchedComment: null,
            allComments: comments,
            commentCount: comments.length
          };
        }
        const searchContent = targetComment.trim();
        const searchWithoutEmojis = this.removeEmojiTags(searchContent);
        let authorList = [];
        if (Array.isArray(targetAuthor)) {
          authorList = targetAuthor.filter((author) => author && typeof author === "string").map((author) => author.trim());
        } else if (targetAuthor && typeof targetAuthor === "string") {
          authorList = targetAuthor.split(",").map((a) => a.trim()).filter((a) => a);
        }
        console.log(`\u{1F50D} \u641C\u7D22\u6761\u4EF6: \u5185\u5BB9="${searchContent}", \u4F5C\u8005\u5217\u8868=${JSON.stringify(authorList)}`);
        console.log(`\u{1F50D} \u53BB\u8868\u60C5\u540E: "${searchWithoutEmojis}"`);
        let found = false;
        let matchedComment = null;
        let matchedAuthor = null;
        let bestMatchScore = 0;
        for (let i = 0; i < comments.length; i++) {
          const comment = comments[i];
          const commentWithoutEmojis = this.removeEmojiTags(comment.text);
          if (commentWithoutEmojis === searchWithoutEmojis) {
            console.log(`\u2705 \u627E\u5230\u5B8C\u5168\u5339\u914D\u7684\u8BC4\u8BBA\u5185\u5BB9\uFF08\u5DF2\u6392\u9664\u8868\u60C5\u6807\u7B7E\uFF09: "${searchWithoutEmojis}"`);
            console.log(`\u{1F464} \u5BF9\u5E94\u7684\u4F5C\u8005: "${comment.author || "\u672A\u627E\u5230"}"`);
            bestMatchScore = 1;
            matchedComment = comment;
            matchedAuthor = comment.author;
            found = true;
            break;
          }
          const normalizedComment = commentWithoutEmojis.replace(/\s+/g, " ").trim();
          const normalizedSearch = searchWithoutEmojis.replace(/\s+/g, " ").trim();
          if (normalizedComment === normalizedSearch) {
            console.log(`\u2705 \u627E\u5230\u89C4\u8303\u5316\u5339\u914D\u7684\u8BC4\u8BBA\u5185\u5BB9: "${normalizedComment}"`);
            console.log(`\u{1F464} \u5BF9\u5E94\u7684\u4F5C\u8005: "${comment.author || "\u672A\u627E\u5230"}"`);
            bestMatchScore = 1;
            matchedComment = comment;
            matchedAuthor = comment.author;
            found = true;
            break;
          }
          const similarity = this.calculateSimilarity(normalizedComment, normalizedSearch);
          if (similarity >= 0.95) {
            console.log(`\u2705 \u627E\u5230\u9AD8\u76F8\u4F3C\u5EA6\u5339\u914D\u7684\u8BC4\u8BBA\u5185\u5BB9 (${(similarity * 100).toFixed(1)}%)`);
            console.log(`   \u641C\u7D22: "${normalizedSearch}"`);
            console.log(`   \u627E\u5230: "${normalizedComment}"`);
            console.log(`\u{1F464} \u5BF9\u5E94\u7684\u4F5C\u8005: "${comment.author || "\u672A\u627E\u5230"}"`);
            bestMatchScore = similarity;
            matchedComment = comment;
            matchedAuthor = comment.author;
            found = true;
            break;
          }
          if (similarity >= 0.85 && this.hasCommonWords(normalizedComment, normalizedSearch)) {
            console.log(`\u2705 \u627E\u5230\u5173\u952E\u8BCD\u5339\u914D\u7684\u8BC4\u8BBA\u5185\u5BB9 (${(similarity * 100).toFixed(1)}% + \u5173\u952E\u8BCD)`);
            console.log(`   \u641C\u7D22: "${normalizedSearch}"`);
            console.log(`   \u627E\u5230: "${normalizedComment}"`);
            console.log(`\u{1F464} \u5BF9\u5E94\u7684\u4F5C\u8005: "${comment.author || "\u672A\u627E\u5230"}"`);
            bestMatchScore = similarity;
            matchedComment = comment;
            matchedAuthor = comment.author;
            found = true;
            break;
          }
          if (similarity >= 0.6) {
            console.log(`   \u5019\u9009 ${i + 1}: "${comment.text?.substring(0, 30)}..." (\u76F8\u4F3C\u5EA6: ${(similarity * 100).toFixed(1)}%, \u4F5C\u8005: ${comment.author || "\u672A\u77E5"})`);
          }
        }
        if (found && authorList.length > 0 && matchedAuthor) {
          console.log(`\u{1F50D} \u5F00\u59CB\u4F5C\u8005\u9A8C\u8BC1: matchedAuthor="${matchedAuthor}", authorList=${JSON.stringify(authorList)}`);
          let authorMatched = false;
          for (const expectedAuthor of authorList) {
            const cleanMatchedAuthor = matchedAuthor.replace(/\s*(关注|作者|等)$/, "").trim();
            const cleanExpectedAuthor = expectedAuthor.trim();
            if (cleanMatchedAuthor === cleanExpectedAuthor) {
              authorMatched = true;
              console.log(`\u2705 \u4F5C\u8005\u5B8C\u5168\u5339\u914D: "${cleanMatchedAuthor}"`);
              break;
            }
            if (cleanMatchedAuthor.includes(cleanExpectedAuthor) || cleanExpectedAuthor.includes(cleanMatchedAuthor)) {
              authorMatched = true;
              console.log(`\u2705 \u4F5C\u8005\u90E8\u5206\u5339\u914D: "${cleanMatchedAuthor}" \u5305\u542B "${cleanExpectedAuthor}"`);
              break;
            }
          }
          if (!authorMatched) {
            console.log(`\u274C \u4F5C\u8005\u4E0D\u5339\u914D - \u627E\u5230\u7684: "${matchedAuthor}", \u671F\u671B: ${JSON.stringify(authorList)}`);
            found = false;
          }
        }
        const result = {
          found,
          confidence: found ? bestMatchScore : 0,
          targetComment,
          targetAuthor,
          matchedComment: matchedComment ? {
            text: matchedComment.text,
            author: matchedComment.author
          } : null,
          allComments: comments,
          commentCount: comments.length
        };
        console.log(`\u{1F4CA} [\u6D4F\u89C8\u5668] \u9A8C\u8BC1\u7ED3\u679C: ${found ? "\u2705 \u627E\u5230" : "\u274C \u672A\u627E\u5230"} (${comments.length} \u6761\u8BC4\u8BBA)`);
        return result;
      }
      /**
       * 提取笔记内容（标题、正文、作者）
       */
      async extractNoteContent() {
        console.log("\u{1F4DD} [\u6D4F\u89C8\u5668] \u63D0\u53D6\u7B14\u8BB0\u5185\u5BB9...");
        try {
          const noteData = await this.page.evaluate(() => {
            const titleSelectors = [
              ".title",
              '[class*="title"]',
              "h1",
              ".note-title",
              '[class*="note"][class*="title"]'
            ];
            let title = "";
            for (const selector of titleSelectors) {
              const el = document.querySelector(selector);
              if (el && el.textContent && el.textContent.trim().length > 0) {
                title = el.textContent.trim();
                break;
              }
            }
            const authorSelectors = [
              ".author-wrapper",
              ".author-name",
              ".nickname",
              ".user-name",
              '[class*="author"] [class*="name"]',
              '[class*="user"] [class*="name"]'
            ];
            let author = "";
            for (const selector of authorSelectors) {
              const el = document.querySelector(selector);
              if (el && el.textContent && el.textContent.trim().length > 0) {
                author = el.textContent.trim();
                break;
              }
            }
            const contentSelectors = [
              ".note-text",
              '[class*="content"]',
              '[class*="desc"]',
              '[class*="text"]',
              ".content",
              "article",
              ".post-content"
            ];
            let content = "";
            for (const selector of contentSelectors) {
              const el = document.querySelector(selector);
              if (el && el.textContent && el.textContent.trim().length > 20) {
                content = el.textContent.trim();
                break;
              }
            }
            if (content.length < 50) {
              const bodyText = document.body.innerText || "";
              const lines = bodyText.split("\n").filter((line) => {
                const trimmed = line.trim();
                return trimmed.length > 10 && !trimmed.includes("\u767B\u5F55") && !trimmed.includes("\u626B\u7801") && !trimmed.includes("\u63A8\u8350") && !trimmed.includes("\u5173\u6CE8");
              });
              content = lines.join("\n").substring(0, 5e3);
            }
            const invalidTitles = [
              "\u6E29\u99A8\u63D0\u793A",
              "\u63D0\u793A",
              "\u767B\u5F55",
              "\u626B\u7801",
              "\u767B\u5F55\u540E\u63A8\u8350",
              "\u8BF7\u767B\u5F55",
              "\u767B\u5F55\u540E\u67E5\u770B",
              "\u6CE8\u610F",
              "\u6CE8\u610F\uFF01",
              "\u53CB\u60C5\u63D0\u793A"
            ];
            if (title && invalidTitles.some((invalid) => title.includes(invalid))) {
              title = "";
            }
            return {
              title: title || "",
              author: author || "",
              content: content || ""
            };
          });
          console.log(`\u2705 [\u6D4F\u89C8\u5668] \u7B14\u8BB0\u5185\u5BB9\u63D0\u53D6\u6210\u529F`);
          console.log(`   \u6807\u9898: ${noteData.title.substring(0, 50)}...`);
          console.log(`   \u4F5C\u8005: ${noteData.author}`);
          console.log(`   \u6B63\u6587\u957F\u5EA6: ${noteData.content.length} \u5B57\u7B26`);
          return {
            success: true,
            data: noteData
          };
        } catch (error) {
          console.error("\u274C [\u6D4F\u89C8\u5668] \u63D0\u53D6\u7B14\u8BB0\u5185\u5BB9\u5931\u8D25:", error.message);
          return {
            success: false,
            error: error.message,
            data: { title: "", author: "", content: "" }
          };
        }
      }
      /**
       * 从笔记标题和内容中提取关键词
       * 用于手动导入的笔记补充关键词信息
       *
       * @param {Object} noteData - { title, content }
       * @returns {string} 提取的关键词
       */
      extractKeywordFromContent(noteData) {
        const { title, content } = noteData;
        if (!title && !content) {
          return "";
        }
        const victimKeywords = [
          "\u88AB\u9A97",
          "\u6295\u8BC9",
          "\u7EF4\u6743",
          "\u8BC8\u9A97",
          "\u6B3A\u8BC8",
          "\u5751\u4EBA",
          "\u9677\u9631",
          "\u5957\u8DEF",
          "\u9000\u6B3E",
          "\u9000\u8D27",
          "\u8D54\u507F",
          "\u635F\u5931",
          "\u635F\u5931\u8D39",
          "\u7EF4\u6743",
          "\u4E3E\u62A5",
          "\u66DD\u5149",
          "\u9ED1\u5FC3",
          "\u65E0\u826F",
          "\u9A97\u5B50",
          "\u5047\u8D27",
          "\u6C34\u8D27",
          "\u6B21\u54C1",
          "\u4F53\u9A8C",
          "\u7F8E\u5BB9",
          "\u533B\u7F8E",
          "\u6574\u5F62",
          "\u51CF\u80A5",
          "\u4E30\u80F8",
          "\u7F8E\u767D",
          "\u795B\u6591",
          "\u795B\u75D8",
          "\u62A4\u80A4",
          "\u5316\u5986\u54C1",
          "\u7F8E\u5BB9\u9662",
          "\u673A\u6784",
          "\u533B\u9662",
          "\u690D\u53D1",
          "\u7259\u9F7F",
          "\u6B63\u7578",
          "\u77EB\u6B63",
          "\u773C\u955C",
          "\u8FD1\u89C6",
          "\u4F53\u68C0"
        ];
        const stopWords = /* @__PURE__ */ new Set([
          "\u7684",
          "\u4E86",
          "\u662F",
          "\u5728",
          "\u6211",
          "\u6709",
          "\u548C",
          "\u5C31",
          "\u4E0D",
          "\u4EBA",
          "\u90FD",
          "\u4E00",
          "\u4E00\u4E2A",
          "\u4E0A",
          "\u4E5F",
          "\u5F88",
          "\u5230",
          "\u8BF4",
          "\u8981",
          "\u53BB",
          "\u4F60",
          "\u4F1A",
          "\u7740",
          "\u6CA1\u6709",
          "\u770B",
          "\u597D",
          "\u81EA\u5DF1",
          "\u8FD9",
          "\u90A3",
          "\u4EC0\u4E48",
          "\u554A",
          "\u5417",
          "\u5462",
          "\u5427",
          "\u54E6",
          "\u5440",
          "\u5566",
          "\u55EF",
          "\u54FC",
          "\u5582",
          "\u5DF2\u7ECF",
          "\u8FD8\u662F",
          "\u4F46\u662F",
          "\u56E0\u4E3A",
          "\u6240\u4EE5",
          "\u5982\u679C",
          "\u867D\u7136",
          "\u7136\u540E",
          "\u53EF\u4EE5",
          "\u8FD9\u4E2A",
          "\u90A3\u4E2A",
          "\u600E\u4E48",
          "\u600E\u4E48",
          "\u4E3A\u4EC0\u4E48",
          "\u591A\u5C11",
          "\u51E0\u4E2A",
          "\u4ECA\u5929",
          "\u6628\u5929",
          "\u660E\u5929",
          "\u73B0\u5728",
          "\u540E\u6765",
          "\u4E4B\u524D",
          "\u4E4B\u540E",
          "\u7A81\u7136",
          "\u771F\u7684",
          "\u5047\u7684",
          "\u7279\u522B",
          "\u975E\u5E38",
          "\u8D85\u7EA7",
          "\u7279\u522B",
          "\u7B80\u76F4",
          "\u5B8C\u5168",
          "\u5206\u4EAB",
          "\u8BB0\u5F55",
          "\u5E0C\u671B",
          "\u89C9\u5F97",
          "\u611F\u89C9",
          "\u53D1\u73B0",
          "\u7EC8\u4E8E",
          "\u5C45\u7136"
        ]);
        const fullText = (title + " " + content).trim();
        for (const keyword of victimKeywords) {
          if (fullText.includes(keyword)) {
            const regex = new RegExp(`(.{0,3})${keyword}(.{0,3})`, "g");
            const matches = fullText.match(regex);
            if (matches) {
              const bestMatch = matches.sort((a, b) => b.length - a.length)[0];
              const cleaned = bestMatch.split("").filter((c) => !stopWords.has(c)).join("");
              if (cleaned.length >= 2) {
                console.log(`\u{1F511} [\u5173\u952E\u8BCD\u63D0\u53D6] \u4ECE\u5185\u5BB9\u4E2D\u63D0\u53D6: "${cleaned}"`);
                return cleaned;
              }
            }
            console.log(`\u{1F511} [\u5173\u952E\u8BCD\u63D0\u53D6] \u4ECE\u5185\u5BB9\u4E2D\u63D0\u53D6: "${keyword}"`);
            return keyword;
          }
        }
        if (title) {
          const titleWords = title.replace(/[，。！？、；：""''（）【】《》,\.!\?;:"'()\[\]<>]/g, " ").split(/\s+/).filter((word) => word.length >= 2 && !stopWords.has(word));
          if (titleWords.length > 0) {
            const extracted = titleWords[0];
            console.log(`\u{1F511} [\u5173\u952E\u8BCD\u63D0\u53D6] \u4ECE\u6807\u9898\u63D0\u53D6: "${extracted}"`);
            return extracted;
          }
        }
        if (content) {
          const contentPreview = content.substring(0, 100);
          const contentWords = contentPreview.replace(/[，。！？、；：""''（）【】《》,\.!\?;:"'()\[\]<>]/g, " ").split(/\s+/).filter((word) => word.length >= 2 && !stopWords.has(word));
          if (contentWords.length > 0) {
            const extracted = contentWords[0];
            console.log(`\u{1F511} [\u5173\u952E\u8BCD\u63D0\u53D6] \u4ECE\u5185\u5BB9\u63D0\u53D6: "${extracted}"`);
            return extracted;
          }
        }
        console.log("\u26A0\uFE0F  [\u5173\u952E\u8BCD\u63D0\u53D6] \u672A\u80FD\u63D0\u53D6\u5230\u6709\u6548\u5173\u952E\u8BCD");
        return "";
      }
      /**
       * 截图（用于调试）
       */
      async screenshot(filepath) {
        if (!this.page) return false;
        try {
          await this.page.screenshot({ path: filepath, fullPage: true });
          console.log(`\u{1F4F8} [\u6D4F\u89C8\u5668] \u622A\u56FE\u4FDD\u5B58: ${filepath}`);
          return true;
        } catch (error) {
          console.error("\u274C [\u6D4F\u89C8\u5668] \u622A\u56FE\u5931\u8D25:", error.message);
          return false;
        }
      }
      /**
       * 关闭浏览器
       */
      async close() {
        this.cleanupFunctions.forEach((fn) => {
          try {
            fn();
          } catch (e) {
          }
        });
        this.cleanupFunctions = [];
        if (this.browser) {
          try {
            if (this.page && !this.page.isClosed()) {
              await this.page.close();
            }
            await this.browser.close();
            console.log("\u{1F512} [\u6D4F\u89C8\u5668] \u6D4F\u89C8\u5668\u5DF2\u5173\u95ED");
          } catch (error) {
            console.error("\u274C [\u6D4F\u89C8\u5668] \u5173\u95ED\u5931\u8D25:", error.message);
          }
          this.browser = null;
          this.page = null;
        }
      }
      /**
       * 延迟函数（固定时间）
       */
      async sleep(ms) {
        return new Promise((resolve5) => setTimeout(resolve5, ms));
      }
      /**
       * 安全的页面操作包装器
       * 检查页面是否可用，防止在页面已关闭时操作
       * @param {Function} operation - 要执行的页面操作
       * @returns {Promise<any>} 操作结果
       */
      async safePageOperation(operation) {
        if (!this.page) {
          throw new Error("\u9875\u9762\u4E0D\u5B58\u5728");
        }
        if (this.page.isClosed()) {
          throw new Error("\u9875\u9762\u5DF2\u5173\u95ED");
        }
        try {
          return await operation();
        } catch (error) {
          if (error.message.includes("closed") || error.message.includes("Session closed") || error.message.includes("Target closed") || error.message.includes("page been closed")) {
            throw new Error("\u9875\u9762\u5DF2\u88AB\u5173\u95ED: " + error.message);
          }
          throw error;
        }
      }
      /**
       * 模拟随机鼠标移动（简单的版本，用于页面加载后）
       * 在视口范围内随机移动鼠标几次
       */
      async simulateMouseMovement() {
        try {
          if (!this.page) return;
          const viewport = this.viewport;
          const moves = Math.floor(Math.random() * 3) + 1;
          for (let i = 0; i < moves; i++) {
            const targetX = Math.floor(Math.random() * viewport.width);
            const targetY = Math.floor(Math.random() * viewport.height);
            await this.page.mouse.move(targetX, targetY);
            await this.sleep(Math.floor(Math.random() * 200) + 100);
          }
        } catch (error) {
        }
      }
      // ==================== 拟人化功能 ====================
      /**
       * 随机延迟（模拟人类操作间隔）
       * 使用正态分布，更接近真实人类行为
       *
       * @param {number} min - 最小延迟（毫秒）
       * @param {number} max - 最大延迟（毫秒）
       * @param {string} type - 延迟类型：'uniform'(均匀) | 'normal'(正态) | 'biased'(偏向最大值)
       * @returns {Promise<number>} 实际延迟时间
       */
      async randomDelay(min, max, type = "normal") {
        let delay;
        switch (type) {
          case "uniform":
            delay = min + Math.random() * (max - min);
            break;
          case "normal":
            const mean = (min + max) / 2;
            const stdDev = (max - min) / 6;
            let u1 = Math.random();
            let u2 = Math.random();
            u1 = u1 === 0 ? 1e-4 : u1;
            const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
            delay = mean + z * stdDev;
            delay = Math.max(min, Math.min(max, delay));
            break;
          case "biased":
            const rand = Math.random();
            delay = min + (max - min) * Math.pow(rand, 0.5);
            break;
          default:
            delay = min + Math.random() * (max - min);
        }
        delay = Math.round(delay);
        console.log(`   \u23F1\uFE0F  \u968F\u673A\u5EF6\u8FDF: ${delay}ms`);
        await this.sleep(delay);
        return delay;
      }
      /**
       * 模拟人类阅读停留
       * 根据页面内容长度动态调整停留时间
       *
       * @param {Object} options - 配置选项
       * @param {number} options.minTime - 最小停留时间（毫秒），默认 2000
       * @param {number} options.maxTime - 最大停留时间（毫秒），默认 8000
       * @param {boolean} options.scrollDuringRead - 是否在阅读时滚动，默认 true
       * @returns {Promise<{stayTime: number, scrollCount: number}>}
       */
      async simulateReading(options = {}) {
        const { minTime = 2e3, maxTime = 8e3, scrollDuringRead = true } = options;
        console.log(`\u{1F4D6} [\u9605\u8BFB\u6A21\u62DF] \u5F00\u59CB\u6A21\u62DF\u9605\u8BFB\u884C\u4E3A...`);
        let contentLength = 0;
        try {
          contentLength = await this.page.evaluate(() => {
            const body = document.body?.innerText || "";
            return body.length;
          });
        } catch (e) {
          contentLength = 1e3;
        }
        const baseTime = minTime;
        const extraTime = Math.min(contentLength * 2, maxTime - minTime);
        const calculatedTime = baseTime + extraTime;
        const randomFactor = 0.8 + Math.random() * 0.4;
        const stayTime = Math.round(calculatedTime * randomFactor);
        console.log(`   \u{1F4C4} \u5185\u5BB9\u957F\u5EA6: ${contentLength} \u5B57\u7B26`);
        console.log(`   \u23F1\uFE0F  \u8BA1\u5212\u505C\u7559: ${stayTime}ms`);
        let scrollCount = 0;
        if (scrollDuringRead && stayTime > 3e3) {
          scrollCount = Math.floor(1 + Math.random() * 2);
          for (let i = 0; i < scrollCount; i++) {
            const waitBeforeScroll = Math.round(stayTime / (scrollCount + 1) * (i + 0.5));
            await this.sleep(waitBeforeScroll);
            const scrollAmount = Math.round(50 + Math.random() * 150);
            const direction = Math.random() > 0.3 ? 1 : -1;
            try {
              await this.page.evaluate((amount, dir) => {
                window.scrollBy({ top: amount * dir, behavior: "smooth" });
              }, scrollAmount, direction);
              console.log(`   \u{1F4DC} \u9605\u8BFB\u6EDA\u52A8: ${direction > 0 ? "\u2193" : "\u2191"}${scrollAmount}px`);
            } catch (e) {
            }
            await this.sleep(300 + Math.random() * 500);
          }
        } else {
          await this.sleep(stayTime);
        }
        console.log(`   \u2705 \u9605\u8BFB\u6A21\u62DF\u5B8C\u6210 (\u505C\u7559 ${stayTime}ms, \u6EDA\u52A8 ${scrollCount} \u6B21)`);
        return { stayTime, scrollCount };
      }
      /**
       * 模拟鼠标移动轨迹
       * 使用贝塞尔曲线生成自然的鼠标移动路径
       *
       * @param {Object} target - 目标位置 { x, y }
       * @param {Object} options - 配置选项
       * @param {number} options.steps - 移动步数，默认 20-40 随机
       * @param {number} options.duration - 总移动时间（毫秒），默认 500-1500 随机
       * @returns {Promise<{success: boolean, steps: number, duration: number}>}
       */
      async moveMouse(target, options = {}) {
        if (!this.page) {
          return { success: false, steps: 0, duration: 0 };
        }
        const steps = options.steps || Math.floor(20 + Math.random() * 20);
        const duration = options.duration || Math.floor(500 + Math.random() * 1e3);
        try {
          const viewport = this.viewport;
          let startX = options.startX || viewport.width / 2 + (Math.random() - 0.5) * 200;
          let startY = options.startY || viewport.height / 2 + (Math.random() - 0.5) * 200;
          const controlPoints = this._generateBezierControlPoints(
            { x: startX, y: startY },
            { x: target.x, y: target.y },
            3
            // 三次贝塞尔曲线
          );
          console.log(`\u{1F5B1}\uFE0F  [\u9F20\u6807\u79FB\u52A8] \u8D77\u70B9(${Math.round(startX)}, ${Math.round(startY)}) \u2192 \u7EC8\u70B9(${target.x}, ${target.y})`);
          console.log(`   \u8F68\u8FF9: ${steps} \u6B65, \u8017\u65F6 ${duration}ms`);
          const stepDelay = duration / steps;
          for (let i = 0; i <= steps; i++) {
            const t = i / steps;
            const point = this._getBezierPoint(controlPoints, t);
            try {
              await this.page.mouse.move(point.x, point.y);
            } catch (e) {
            }
            await this.sleep(stepDelay + (Math.random() - 0.5) * 10);
          }
          return { success: true, steps, duration };
        } catch (error) {
          console.warn(`   \u26A0\uFE0F \u9F20\u6807\u79FB\u52A8\u5931\u8D25: ${error.message}`);
          return { success: false, steps: 0, duration: 0 };
        }
      }
      /**
       * 生成贝塞尔曲线控制点
       * @private
       */
      _generateBezierControlPoints(start, end, order = 3) {
        const points = [start];
        const dx = end.x - start.x;
        const dy = end.y - start.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        for (let i = 1; i < order; i++) {
          const t = i / order;
          const baseX = start.x + dx * t;
          const baseY = start.y + dy * t;
          const perpX = -dy / distance;
          const perpY = dx / distance;
          const offset = (Math.random() - 0.5) * distance * 0.3;
          points.push({
            x: baseX + perpX * offset,
            y: baseY + perpY * offset
          });
        }
        points.push(end);
        return points;
      }
      /**
       * 获取贝塞尔曲线上的点
       * @private
       */
      _getBezierPoint(points, t) {
        if (points.length === 1) {
          return points[0];
        }
        const newPoints = [];
        for (let i = 0; i < points.length - 1; i++) {
          newPoints.push({
            x: points[i].x + (points[i + 1].x - points[i].x) * t,
            y: points[i].y + (points[i + 1].y - points[i].y) * t
          });
        }
        return this._getBezierPoint(newPoints, t);
      }
      /**
       * 模拟人类点击（带鼠标移动）
       *
       * @param {string} selector - 元素选择器
       * @param {Object} options - 配置选项
       * @param {number} options.moveBeforeClick - 点击前是否移动鼠标，默认 true
       * @param {number} options.hoverDelay - 悬停延迟（毫秒），默认 100-300 随机
       * @returns {Promise<boolean>}
       */
      async humanClick(selector, options = {}) {
        const { moveBeforeClick = true, hoverDelay = null } = options;
        try {
          const element = await this.page.$(selector);
          if (!element) {
            console.warn(`   \u26A0\uFE0F \u672A\u627E\u5230\u5143\u7D20: ${selector}`);
            return false;
          }
          const box = await element.boundingBox();
          if (!box) {
            console.warn(`   \u26A0\uFE0F \u5143\u7D20\u4E0D\u53EF\u89C1: ${selector}`);
            return false;
          }
          const targetX = box.x + box.width / 2 + (Math.random() - 0.5) * box.width * 0.6;
          const targetY = box.y + box.height / 2 + (Math.random() - 0.5) * box.height * 0.6;
          if (moveBeforeClick) {
            await this.moveMouse({ x: targetX, y: targetY });
            const delay = hoverDelay || Math.floor(100 + Math.random() * 200);
            await this.sleep(delay);
          } else {
            await this.page.mouse.move(targetX, targetY);
          }
          await this.page.mouse.click(targetX, targetY);
          console.log(`   \u2705 \u4EBA\u7C7B\u5316\u70B9\u51FB: ${selector} @ (${Math.round(targetX)}, ${Math.round(targetY)})`);
          return true;
        } catch (error) {
          console.warn(`   \u26A0\uFE0F \u70B9\u51FB\u5931\u8D25: ${error.message}`);
          return false;
        }
      }
      /**
       * 模拟人类输入（带随机间隔）
       *
       * @param {string} selector - 输入框选择器
       * @param {string} text - 要输入的文本
       * @param {Object} options - 配置选项
       * @param {number} options.minInterval - 最小输入间隔（毫秒），默认 50
       * @param {number} options.maxInterval - 最大输入间隔（毫秒），默认 150
       * @returns {Promise<boolean>}
       */
      async humanType(selector, text, options = {}) {
        const { minInterval = 50, maxInterval = 150 } = options;
        try {
          await this.humanClick(selector);
          for (const char of text) {
            await this.page.keyboard.type(char);
            await this.randomDelay(minInterval, maxInterval, "biased");
          }
          console.log(`   \u2705 \u4EBA\u7C7B\u5316\u8F93\u5165: "${text.substring(0, 20)}..." (${text.length} \u5B57\u7B26)`);
          return true;
        } catch (error) {
          console.warn(`   \u26A0\uFE0F \u8F93\u5165\u5931\u8D25: ${error.message}`);
          return false;
        }
      }
      /**
       * 模拟自然滚动（带随机速度和停顿）
       *
       * @param {Object} options - 配置选项
       * @param {number} options.distance - 滚动距离（像素），默认到页面底部
       * @param {number} options.direction - 滚动方向：1=向下，-1=向上，默认 1
       * @returns {Promise<{scrolled: number, pauses: number}>}
       */
      async naturalScroll(options = {}) {
        const direction = options.direction || 1;
        let targetDistance = options.distance;
        if (!targetDistance) {
          try {
            targetDistance = await this.page.evaluate(() => {
              return document.body.scrollHeight - window.innerHeight;
            });
          } catch (e) {
            targetDistance = 1e3;
          }
        }
        console.log(`\u{1F4DC} [\u81EA\u7136\u6EDA\u52A8] \u65B9\u5411: ${direction > 0 ? "\u2193" : "\u2191"}, \u76EE\u6807\u8DDD\u79BB: ${targetDistance}px`);
        let scrolled = 0;
        let pauses = 0;
        while (scrolled < targetDistance) {
          const scrollAmount = Math.round(50 + Math.random() * 150);
          const actualScroll = Math.min(scrollAmount, targetDistance - scrolled);
          try {
            await this.page.evaluate((amount, dir) => {
              window.scrollBy({ top: amount * dir, behavior: "smooth" });
            }, actualScroll, direction);
            scrolled += actualScroll;
          } catch (e) {
            break;
          }
          const waitTime = await this.randomDelay(200, 800, "biased");
          if (Math.random() < 0.2) {
            await this.randomDelay(1e3, 3e3, "normal");
            pauses++;
            console.log(`   \u{1F4D6} \u9605\u8BFB\u505C\u987F...`);
          }
        }
        console.log(`   \u2705 \u81EA\u7136\u6EDA\u52A8\u5B8C\u6210: \u6EDA\u52A8 ${scrolled}px, \u505C\u987F ${pauses} \u6B21`);
        return { scrolled, pauses };
      }
      /**
       * 智能延迟（根据操作类型自动选择合适的延迟范围）
       *
       * @param {string} operationType - 操作类型
       * @returns {Promise<number>}
       */
      async smartDelay(operationType) {
        const delayRanges = {
          "page_load": { min: 2e3, max: 5e3 },
          // 页面加载后
          "click": { min: 300, max: 1e3 },
          // 点击前/后
          "scroll": { min: 500, max: 1500 },
          // 滚动间隔
          "input": { min: 50, max: 150 },
          // 输入字符间隔
          "navigation": { min: 1500, max: 4e3 },
          // 页面跳转
          "api_call": { min: 1e3, max: 3e3 },
          // API 调用后
          "reading": { min: 3e3, max: 1e4 },
          // 阅读停留
          "interaction": { min: 200, max: 600 }
          // 交互操作
        };
        const range = delayRanges[operationType] || { min: 500, max: 1500 };
        return await this.randomDelay(range.min, range.max, "normal");
      }
      /**
       * 获取状态
       */
      getStatus() {
        return {
          isLaunched: !!this.browser,
          isPageReady: !!this.page,
          headless: this.headless,
          viewport: this.viewport,
          executablePath: this.executablePath
        };
      }
    };
    module2.exports = BrowserAutomation2;
  }
});

// node_modules/delayed-stream/lib/delayed_stream.js
var require_delayed_stream = __commonJS({
  "node_modules/delayed-stream/lib/delayed_stream.js"(exports2, module2) {
    init_prefix();
    var Stream = require("stream").Stream;
    var util = require("util");
    module2.exports = DelayedStream;
    function DelayedStream() {
      this.source = null;
      this.dataSize = 0;
      this.maxDataSize = 1024 * 1024;
      this.pauseStream = true;
      this._maxDataSizeExceeded = false;
      this._released = false;
      this._bufferedEvents = [];
    }
    util.inherits(DelayedStream, Stream);
    DelayedStream.create = function(source, options) {
      var delayedStream = new this();
      options = options || {};
      for (var option in options) {
        delayedStream[option] = options[option];
      }
      delayedStream.source = source;
      var realEmit = source.emit;
      source.emit = function() {
        delayedStream._handleEmit(arguments);
        return realEmit.apply(source, arguments);
      };
      source.on("error", function() {
      });
      if (delayedStream.pauseStream) {
        source.pause();
      }
      return delayedStream;
    };
    Object.defineProperty(DelayedStream.prototype, "readable", {
      configurable: true,
      enumerable: true,
      get: function() {
        return this.source.readable;
      }
    });
    DelayedStream.prototype.setEncoding = function() {
      return this.source.setEncoding.apply(this.source, arguments);
    };
    DelayedStream.prototype.resume = function() {
      if (!this._released) {
        this.release();
      }
      this.source.resume();
    };
    DelayedStream.prototype.pause = function() {
      this.source.pause();
    };
    DelayedStream.prototype.release = function() {
      this._released = true;
      this._bufferedEvents.forEach(function(args2) {
        this.emit.apply(this, args2);
      }.bind(this));
      this._bufferedEvents = [];
    };
    DelayedStream.prototype.pipe = function() {
      var r = Stream.prototype.pipe.apply(this, arguments);
      this.resume();
      return r;
    };
    DelayedStream.prototype._handleEmit = function(args2) {
      if (this._released) {
        this.emit.apply(this, args2);
        return;
      }
      if (args2[0] === "data") {
        this.dataSize += args2[1].length;
        this._checkIfMaxDataSizeExceeded();
      }
      this._bufferedEvents.push(args2);
    };
    DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
      if (this._maxDataSizeExceeded) {
        return;
      }
      if (this.dataSize <= this.maxDataSize) {
        return;
      }
      this._maxDataSizeExceeded = true;
      var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded.";
      this.emit("error", new Error(message));
    };
  }
});

// node_modules/combined-stream/lib/combined_stream.js
var require_combined_stream = __commonJS({
  "node_modules/combined-stream/lib/combined_stream.js"(exports2, module2) {
    init_prefix();
    var util = require("util");
    var Stream = require("stream").Stream;
    var DelayedStream = require_delayed_stream();
    module2.exports = CombinedStream;
    function CombinedStream() {
      this.writable = false;
      this.readable = true;
      this.dataSize = 0;
      this.maxDataSize = 2 * 1024 * 1024;
      this.pauseStreams = true;
      this._released = false;
      this._streams = [];
      this._currentStream = null;
      this._insideLoop = false;
      this._pendingNext = false;
    }
    util.inherits(CombinedStream, Stream);
    CombinedStream.create = function(options) {
      var combinedStream = new this();
      options = options || {};
      for (var option in options) {
        combinedStream[option] = options[option];
      }
      return combinedStream;
    };
    CombinedStream.isStreamLike = function(stream) {
      return typeof stream !== "function" && typeof stream !== "string" && typeof stream !== "boolean" && typeof stream !== "number" && !Buffer.isBuffer(stream);
    };
    CombinedStream.prototype.append = function(stream) {
      var isStreamLike = CombinedStream.isStreamLike(stream);
      if (isStreamLike) {
        if (!(stream instanceof DelayedStream)) {
          var newStream = DelayedStream.create(stream, {
            maxDataSize: Infinity,
            pauseStream: this.pauseStreams
          });
          stream.on("data", this._checkDataSize.bind(this));
          stream = newStream;
        }
        this._handleErrors(stream);
        if (this.pauseStreams) {
          stream.pause();
        }
      }
      this._streams.push(stream);
      return this;
    };
    CombinedStream.prototype.pipe = function(dest, options) {
      Stream.prototype.pipe.call(this, dest, options);
      this.resume();
      return dest;
    };
    CombinedStream.prototype._getNext = function() {
      this._currentStream = null;
      if (this._insideLoop) {
        this._pendingNext = true;
        return;
      }
      this._insideLoop = true;
      try {
        do {
          this._pendingNext = false;
          this._realGetNext();
        } while (this._pendingNext);
      } finally {
        this._insideLoop = false;
      }
    };
    CombinedStream.prototype._realGetNext = function() {
      var stream = this._streams.shift();
      if (typeof stream == "undefined") {
        this.end();
        return;
      }
      if (typeof stream !== "function") {
        this._pipeNext(stream);
        return;
      }
      var getStream = stream;
      getStream(function(stream2) {
        var isStreamLike = CombinedStream.isStreamLike(stream2);
        if (isStreamLike) {
          stream2.on("data", this._checkDataSize.bind(this));
          this._handleErrors(stream2);
        }
        this._pipeNext(stream2);
      }.bind(this));
    };
    CombinedStream.prototype._pipeNext = function(stream) {
      this._currentStream = stream;
      var isStreamLike = CombinedStream.isStreamLike(stream);
      if (isStreamLike) {
        stream.on("end", this._getNext.bind(this));
        stream.pipe(this, { end: false });
        return;
      }
      var value = stream;
      this.write(value);
      this._getNext();
    };
    CombinedStream.prototype._handleErrors = function(stream) {
      var self2 = this;
      stream.on("error", function(err) {
        self2._emitError(err);
      });
    };
    CombinedStream.prototype.write = function(data) {
      this.emit("data", data);
    };
    CombinedStream.prototype.pause = function() {
      if (!this.pauseStreams) {
        return;
      }
      if (this.pauseStreams && this._currentStream && typeof this._currentStream.pause == "function") this._currentStream.pause();
      this.emit("pause");
    };
    CombinedStream.prototype.resume = function() {
      if (!this._released) {
        this._released = true;
        this.writable = true;
        this._getNext();
      }
      if (this.pauseStreams && this._currentStream && typeof this._currentStream.resume == "function") this._currentStream.resume();
      this.emit("resume");
    };
    CombinedStream.prototype.end = function() {
      this._reset();
      this.emit("end");
    };
    CombinedStream.prototype.destroy = function() {
      this._reset();
      this.emit("close");
    };
    CombinedStream.prototype._reset = function() {
      this.writable = false;
      this._streams = [];
      this._currentStream = null;
    };
    CombinedStream.prototype._checkDataSize = function() {
      this._updateDataSize();
      if (this.dataSize <= this.maxDataSize) {
        return;
      }
      var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded.";
      this._emitError(new Error(message));
    };
    CombinedStream.prototype._updateDataSize = function() {
      this.dataSize = 0;
      var self2 = this;
      this._streams.forEach(function(stream) {
        if (!stream.dataSize) {
          return;
        }
        self2.dataSize += stream.dataSize;
      });
      if (this._currentStream && this._currentStream.dataSize) {
        this.dataSize += this._currentStream.dataSize;
      }
    };
    CombinedStream.prototype._emitError = function(err) {
      this._reset();
      this.emit("error", err);
    };
  }
});

// node_modules/mime-db/db.json
var require_db = __commonJS({
  "node_modules/mime-db/db.json"(exports2, module2) {
    module2.exports = {
      "application/1d-interleaved-parityfec": {
        source: "iana"
      },
      "application/3gpdash-qoe-report+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/3gpp-ims+xml": {
        source: "iana",
        compressible: true
      },
      "application/3gpphal+json": {
        source: "iana",
        compressible: true
      },
      "application/3gpphalforms+json": {
        source: "iana",
        compressible: true
      },
      "application/a2l": {
        source: "iana"
      },
      "application/ace+cbor": {
        source: "iana"
      },
      "application/activemessage": {
        source: "iana"
      },
      "application/activity+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-costmap+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-costmapfilter+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-directory+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-endpointcost+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-endpointcostparams+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-endpointprop+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-endpointpropparams+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-error+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-networkmap+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-networkmapfilter+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-updatestreamcontrol+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-updatestreamparams+json": {
        source: "iana",
        compressible: true
      },
      "application/aml": {
        source: "iana"
      },
      "application/andrew-inset": {
        source: "iana",
        extensions: ["ez"]
      },
      "application/applefile": {
        source: "iana"
      },
      "application/applixware": {
        source: "apache",
        extensions: ["aw"]
      },
      "application/at+jwt": {
        source: "iana"
      },
      "application/atf": {
        source: "iana"
      },
      "application/atfx": {
        source: "iana"
      },
      "application/atom+xml": {
        source: "iana",
        compressible: true,
        extensions: ["atom"]
      },
      "application/atomcat+xml": {
        source: "iana",
        compressible: true,
        extensions: ["atomcat"]
      },
      "application/atomdeleted+xml": {
        source: "iana",
        compressible: true,
        extensions: ["atomdeleted"]
      },
      "application/atomicmail": {
        source: "iana"
      },
      "application/atomsvc+xml": {
        source: "iana",
        compressible: true,
        extensions: ["atomsvc"]
      },
      "application/atsc-dwd+xml": {
        source: "iana",
        compressible: true,
        extensions: ["dwd"]
      },
      "application/atsc-dynamic-event-message": {
        source: "iana"
      },
      "application/atsc-held+xml": {
        source: "iana",
        compressible: true,
        extensions: ["held"]
      },
      "application/atsc-rdt+json": {
        source: "iana",
        compressible: true
      },
      "application/atsc-rsat+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rsat"]
      },
      "application/atxml": {
        source: "iana"
      },
      "application/auth-policy+xml": {
        source: "iana",
        compressible: true
      },
      "application/bacnet-xdd+zip": {
        source: "iana",
        compressible: false
      },
      "application/batch-smtp": {
        source: "iana"
      },
      "application/bdoc": {
        compressible: false,
        extensions: ["bdoc"]
      },
      "application/beep+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/calendar+json": {
        source: "iana",
        compressible: true
      },
      "application/calendar+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xcs"]
      },
      "application/call-completion": {
        source: "iana"
      },
      "application/cals-1840": {
        source: "iana"
      },
      "application/captive+json": {
        source: "iana",
        compressible: true
      },
      "application/cbor": {
        source: "iana"
      },
      "application/cbor-seq": {
        source: "iana"
      },
      "application/cccex": {
        source: "iana"
      },
      "application/ccmp+xml": {
        source: "iana",
        compressible: true
      },
      "application/ccxml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["ccxml"]
      },
      "application/cdfx+xml": {
        source: "iana",
        compressible: true,
        extensions: ["cdfx"]
      },
      "application/cdmi-capability": {
        source: "iana",
        extensions: ["cdmia"]
      },
      "application/cdmi-container": {
        source: "iana",
        extensions: ["cdmic"]
      },
      "application/cdmi-domain": {
        source: "iana",
        extensions: ["cdmid"]
      },
      "application/cdmi-object": {
        source: "iana",
        extensions: ["cdmio"]
      },
      "application/cdmi-queue": {
        source: "iana",
        extensions: ["cdmiq"]
      },
      "application/cdni": {
        source: "iana"
      },
      "application/cea": {
        source: "iana"
      },
      "application/cea-2018+xml": {
        source: "iana",
        compressible: true
      },
      "application/cellml+xml": {
        source: "iana",
        compressible: true
      },
      "application/cfw": {
        source: "iana"
      },
      "application/city+json": {
        source: "iana",
        compressible: true
      },
      "application/clr": {
        source: "iana"
      },
      "application/clue+xml": {
        source: "iana",
        compressible: true
      },
      "application/clue_info+xml": {
        source: "iana",
        compressible: true
      },
      "application/cms": {
        source: "iana"
      },
      "application/cnrp+xml": {
        source: "iana",
        compressible: true
      },
      "application/coap-group+json": {
        source: "iana",
        compressible: true
      },
      "application/coap-payload": {
        source: "iana"
      },
      "application/commonground": {
        source: "iana"
      },
      "application/conference-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/cose": {
        source: "iana"
      },
      "application/cose-key": {
        source: "iana"
      },
      "application/cose-key-set": {
        source: "iana"
      },
      "application/cpl+xml": {
        source: "iana",
        compressible: true,
        extensions: ["cpl"]
      },
      "application/csrattrs": {
        source: "iana"
      },
      "application/csta+xml": {
        source: "iana",
        compressible: true
      },
      "application/cstadata+xml": {
        source: "iana",
        compressible: true
      },
      "application/csvm+json": {
        source: "iana",
        compressible: true
      },
      "application/cu-seeme": {
        source: "apache",
        extensions: ["cu"]
      },
      "application/cwt": {
        source: "iana"
      },
      "application/cybercash": {
        source: "iana"
      },
      "application/dart": {
        compressible: true
      },
      "application/dash+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mpd"]
      },
      "application/dash-patch+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mpp"]
      },
      "application/dashdelta": {
        source: "iana"
      },
      "application/davmount+xml": {
        source: "iana",
        compressible: true,
        extensions: ["davmount"]
      },
      "application/dca-rft": {
        source: "iana"
      },
      "application/dcd": {
        source: "iana"
      },
      "application/dec-dx": {
        source: "iana"
      },
      "application/dialog-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/dicom": {
        source: "iana"
      },
      "application/dicom+json": {
        source: "iana",
        compressible: true
      },
      "application/dicom+xml": {
        source: "iana",
        compressible: true
      },
      "application/dii": {
        source: "iana"
      },
      "application/dit": {
        source: "iana"
      },
      "application/dns": {
        source: "iana"
      },
      "application/dns+json": {
        source: "iana",
        compressible: true
      },
      "application/dns-message": {
        source: "iana"
      },
      "application/docbook+xml": {
        source: "apache",
        compressible: true,
        extensions: ["dbk"]
      },
      "application/dots+cbor": {
        source: "iana"
      },
      "application/dskpp+xml": {
        source: "iana",
        compressible: true
      },
      "application/dssc+der": {
        source: "iana",
        extensions: ["dssc"]
      },
      "application/dssc+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xdssc"]
      },
      "application/dvcs": {
        source: "iana"
      },
      "application/ecmascript": {
        source: "iana",
        compressible: true,
        extensions: ["es", "ecma"]
      },
      "application/edi-consent": {
        source: "iana"
      },
      "application/edi-x12": {
        source: "iana",
        compressible: false
      },
      "application/edifact": {
        source: "iana",
        compressible: false
      },
      "application/efi": {
        source: "iana"
      },
      "application/elm+json": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/elm+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.cap+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/emergencycalldata.comment+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.control+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.deviceinfo+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.ecall.msd": {
        source: "iana"
      },
      "application/emergencycalldata.providerinfo+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.serviceinfo+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.subscriberinfo+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.veds+xml": {
        source: "iana",
        compressible: true
      },
      "application/emma+xml": {
        source: "iana",
        compressible: true,
        extensions: ["emma"]
      },
      "application/emotionml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["emotionml"]
      },
      "application/encaprtp": {
        source: "iana"
      },
      "application/epp+xml": {
        source: "iana",
        compressible: true
      },
      "application/epub+zip": {
        source: "iana",
        compressible: false,
        extensions: ["epub"]
      },
      "application/eshop": {
        source: "iana"
      },
      "application/exi": {
        source: "iana",
        extensions: ["exi"]
      },
      "application/expect-ct-report+json": {
        source: "iana",
        compressible: true
      },
      "application/express": {
        source: "iana",
        extensions: ["exp"]
      },
      "application/fastinfoset": {
        source: "iana"
      },
      "application/fastsoap": {
        source: "iana"
      },
      "application/fdt+xml": {
        source: "iana",
        compressible: true,
        extensions: ["fdt"]
      },
      "application/fhir+json": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/fhir+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/fido.trusted-apps+json": {
        compressible: true
      },
      "application/fits": {
        source: "iana"
      },
      "application/flexfec": {
        source: "iana"
      },
      "application/font-sfnt": {
        source: "iana"
      },
      "application/font-tdpfr": {
        source: "iana",
        extensions: ["pfr"]
      },
      "application/font-woff": {
        source: "iana",
        compressible: false
      },
      "application/framework-attributes+xml": {
        source: "iana",
        compressible: true
      },
      "application/geo+json": {
        source: "iana",
        compressible: true,
        extensions: ["geojson"]
      },
      "application/geo+json-seq": {
        source: "iana"
      },
      "application/geopackage+sqlite3": {
        source: "iana"
      },
      "application/geoxacml+xml": {
        source: "iana",
        compressible: true
      },
      "application/gltf-buffer": {
        source: "iana"
      },
      "application/gml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["gml"]
      },
      "application/gpx+xml": {
        source: "apache",
        compressible: true,
        extensions: ["gpx"]
      },
      "application/gxf": {
        source: "apache",
        extensions: ["gxf"]
      },
      "application/gzip": {
        source: "iana",
        compressible: false,
        extensions: ["gz"]
      },
      "application/h224": {
        source: "iana"
      },
      "application/held+xml": {
        source: "iana",
        compressible: true
      },
      "application/hjson": {
        extensions: ["hjson"]
      },
      "application/http": {
        source: "iana"
      },
      "application/hyperstudio": {
        source: "iana",
        extensions: ["stk"]
      },
      "application/ibe-key-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/ibe-pkg-reply+xml": {
        source: "iana",
        compressible: true
      },
      "application/ibe-pp-data": {
        source: "iana"
      },
      "application/iges": {
        source: "iana"
      },
      "application/im-iscomposing+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/index": {
        source: "iana"
      },
      "application/index.cmd": {
        source: "iana"
      },
      "application/index.obj": {
        source: "iana"
      },
      "application/index.response": {
        source: "iana"
      },
      "application/index.vnd": {
        source: "iana"
      },
      "application/inkml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["ink", "inkml"]
      },
      "application/iotp": {
        source: "iana"
      },
      "application/ipfix": {
        source: "iana",
        extensions: ["ipfix"]
      },
      "application/ipp": {
        source: "iana"
      },
      "application/isup": {
        source: "iana"
      },
      "application/its+xml": {
        source: "iana",
        compressible: true,
        extensions: ["its"]
      },
      "application/java-archive": {
        source: "apache",
        compressible: false,
        extensions: ["jar", "war", "ear"]
      },
      "application/java-serialized-object": {
        source: "apache",
        compressible: false,
        extensions: ["ser"]
      },
      "application/java-vm": {
        source: "apache",
        compressible: false,
        extensions: ["class"]
      },
      "application/javascript": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["js", "mjs"]
      },
      "application/jf2feed+json": {
        source: "iana",
        compressible: true
      },
      "application/jose": {
        source: "iana"
      },
      "application/jose+json": {
        source: "iana",
        compressible: true
      },
      "application/jrd+json": {
        source: "iana",
        compressible: true
      },
      "application/jscalendar+json": {
        source: "iana",
        compressible: true
      },
      "application/json": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["json", "map"]
      },
      "application/json-patch+json": {
        source: "iana",
        compressible: true
      },
      "application/json-seq": {
        source: "iana"
      },
      "application/json5": {
        extensions: ["json5"]
      },
      "application/jsonml+json": {
        source: "apache",
        compressible: true,
        extensions: ["jsonml"]
      },
      "application/jwk+json": {
        source: "iana",
        compressible: true
      },
      "application/jwk-set+json": {
        source: "iana",
        compressible: true
      },
      "application/jwt": {
        source: "iana"
      },
      "application/kpml-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/kpml-response+xml": {
        source: "iana",
        compressible: true
      },
      "application/ld+json": {
        source: "iana",
        compressible: true,
        extensions: ["jsonld"]
      },
      "application/lgr+xml": {
        source: "iana",
        compressible: true,
        extensions: ["lgr"]
      },
      "application/link-format": {
        source: "iana"
      },
      "application/load-control+xml": {
        source: "iana",
        compressible: true
      },
      "application/lost+xml": {
        source: "iana",
        compressible: true,
        extensions: ["lostxml"]
      },
      "application/lostsync+xml": {
        source: "iana",
        compressible: true
      },
      "application/lpf+zip": {
        source: "iana",
        compressible: false
      },
      "application/lxf": {
        source: "iana"
      },
      "application/mac-binhex40": {
        source: "iana",
        extensions: ["hqx"]
      },
      "application/mac-compactpro": {
        source: "apache",
        extensions: ["cpt"]
      },
      "application/macwriteii": {
        source: "iana"
      },
      "application/mads+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mads"]
      },
      "application/manifest+json": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["webmanifest"]
      },
      "application/marc": {
        source: "iana",
        extensions: ["mrc"]
      },
      "application/marcxml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mrcx"]
      },
      "application/mathematica": {
        source: "iana",
        extensions: ["ma", "nb", "mb"]
      },
      "application/mathml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mathml"]
      },
      "application/mathml-content+xml": {
        source: "iana",
        compressible: true
      },
      "application/mathml-presentation+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-associated-procedure-description+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-deregister+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-envelope+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-msk+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-msk-response+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-protection-description+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-reception-report+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-register+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-register-response+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-schedule+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-user-service-description+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbox": {
        source: "iana",
        extensions: ["mbox"]
      },
      "application/media-policy-dataset+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mpf"]
      },
      "application/media_control+xml": {
        source: "iana",
        compressible: true
      },
      "application/mediaservercontrol+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mscml"]
      },
      "application/merge-patch+json": {
        source: "iana",
        compressible: true
      },
      "application/metalink+xml": {
        source: "apache",
        compressible: true,
        extensions: ["metalink"]
      },
      "application/metalink4+xml": {
        source: "iana",
        compressible: true,
        extensions: ["meta4"]
      },
      "application/mets+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mets"]
      },
      "application/mf4": {
        source: "iana"
      },
      "application/mikey": {
        source: "iana"
      },
      "application/mipc": {
        source: "iana"
      },
      "application/missing-blocks+cbor-seq": {
        source: "iana"
      },
      "application/mmt-aei+xml": {
        source: "iana",
        compressible: true,
        extensions: ["maei"]
      },
      "application/mmt-usd+xml": {
        source: "iana",
        compressible: true,
        extensions: ["musd"]
      },
      "application/mods+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mods"]
      },
      "application/moss-keys": {
        source: "iana"
      },
      "application/moss-signature": {
        source: "iana"
      },
      "application/mosskey-data": {
        source: "iana"
      },
      "application/mosskey-request": {
        source: "iana"
      },
      "application/mp21": {
        source: "iana",
        extensions: ["m21", "mp21"]
      },
      "application/mp4": {
        source: "iana",
        extensions: ["mp4s", "m4p"]
      },
      "application/mpeg4-generic": {
        source: "iana"
      },
      "application/mpeg4-iod": {
        source: "iana"
      },
      "application/mpeg4-iod-xmt": {
        source: "iana"
      },
      "application/mrb-consumer+xml": {
        source: "iana",
        compressible: true
      },
      "application/mrb-publish+xml": {
        source: "iana",
        compressible: true
      },
      "application/msc-ivr+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/msc-mixer+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/msword": {
        source: "iana",
        compressible: false,
        extensions: ["doc", "dot"]
      },
      "application/mud+json": {
        source: "iana",
        compressible: true
      },
      "application/multipart-core": {
        source: "iana"
      },
      "application/mxf": {
        source: "iana",
        extensions: ["mxf"]
      },
      "application/n-quads": {
        source: "iana",
        extensions: ["nq"]
      },
      "application/n-triples": {
        source: "iana",
        extensions: ["nt"]
      },
      "application/nasdata": {
        source: "iana"
      },
      "application/news-checkgroups": {
        source: "iana",
        charset: "US-ASCII"
      },
      "application/news-groupinfo": {
        source: "iana",
        charset: "US-ASCII"
      },
      "application/news-transmission": {
        source: "iana"
      },
      "application/nlsml+xml": {
        source: "iana",
        compressible: true
      },
      "application/node": {
        source: "iana",
        extensions: ["cjs"]
      },
      "application/nss": {
        source: "iana"
      },
      "application/oauth-authz-req+jwt": {
        source: "iana"
      },
      "application/oblivious-dns-message": {
        source: "iana"
      },
      "application/ocsp-request": {
        source: "iana"
      },
      "application/ocsp-response": {
        source: "iana"
      },
      "application/octet-stream": {
        source: "iana",
        compressible: false,
        extensions: ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"]
      },
      "application/oda": {
        source: "iana",
        extensions: ["oda"]
      },
      "application/odm+xml": {
        source: "iana",
        compressible: true
      },
      "application/odx": {
        source: "iana"
      },
      "application/oebps-package+xml": {
        source: "iana",
        compressible: true,
        extensions: ["opf"]
      },
      "application/ogg": {
        source: "iana",
        compressible: false,
        extensions: ["ogx"]
      },
      "application/omdoc+xml": {
        source: "apache",
        compressible: true,
        extensions: ["omdoc"]
      },
      "application/onenote": {
        source: "apache",
        extensions: ["onetoc", "onetoc2", "onetmp", "onepkg"]
      },
      "application/opc-nodeset+xml": {
        source: "iana",
        compressible: true
      },
      "application/oscore": {
        source: "iana"
      },
      "application/oxps": {
        source: "iana",
        extensions: ["oxps"]
      },
      "application/p21": {
        source: "iana"
      },
      "application/p21+zip": {
        source: "iana",
        compressible: false
      },
      "application/p2p-overlay+xml": {
        source: "iana",
        compressible: true,
        extensions: ["relo"]
      },
      "application/parityfec": {
        source: "iana"
      },
      "application/passport": {
        source: "iana"
      },
      "application/patch-ops-error+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xer"]
      },
      "application/pdf": {
        source: "iana",
        compressible: false,
        extensions: ["pdf"]
      },
      "application/pdx": {
        source: "iana"
      },
      "application/pem-certificate-chain": {
        source: "iana"
      },
      "application/pgp-encrypted": {
        source: "iana",
        compressible: false,
        extensions: ["pgp"]
      },
      "application/pgp-keys": {
        source: "iana",
        extensions: ["asc"]
      },
      "application/pgp-signature": {
        source: "iana",
        extensions: ["asc", "sig"]
      },
      "application/pics-rules": {
        source: "apache",
        extensions: ["prf"]
      },
      "application/pidf+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/pidf-diff+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/pkcs10": {
        source: "iana",
        extensions: ["p10"]
      },
      "application/pkcs12": {
        source: "iana"
      },
      "application/pkcs7-mime": {
        source: "iana",
        extensions: ["p7m", "p7c"]
      },
      "application/pkcs7-signature": {
        source: "iana",
        extensions: ["p7s"]
      },
      "application/pkcs8": {
        source: "iana",
        extensions: ["p8"]
      },
      "application/pkcs8-encrypted": {
        source: "iana"
      },
      "application/pkix-attr-cert": {
        source: "iana",
        extensions: ["ac"]
      },
      "application/pkix-cert": {
        source: "iana",
        extensions: ["cer"]
      },
      "application/pkix-crl": {
        source: "iana",
        extensions: ["crl"]
      },
      "application/pkix-pkipath": {
        source: "iana",
        extensions: ["pkipath"]
      },
      "application/pkixcmp": {
        source: "iana",
        extensions: ["pki"]
      },
      "application/pls+xml": {
        source: "iana",
        compressible: true,
        extensions: ["pls"]
      },
      "application/poc-settings+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/postscript": {
        source: "iana",
        compressible: true,
        extensions: ["ai", "eps", "ps"]
      },
      "application/ppsp-tracker+json": {
        source: "iana",
        compressible: true
      },
      "application/problem+json": {
        source: "iana",
        compressible: true
      },
      "application/problem+xml": {
        source: "iana",
        compressible: true
      },
      "application/provenance+xml": {
        source: "iana",
        compressible: true,
        extensions: ["provx"]
      },
      "application/prs.alvestrand.titrax-sheet": {
        source: "iana"
      },
      "application/prs.cww": {
        source: "iana",
        extensions: ["cww"]
      },
      "application/prs.cyn": {
        source: "iana",
        charset: "7-BIT"
      },
      "application/prs.hpub+zip": {
        source: "iana",
        compressible: false
      },
      "application/prs.nprend": {
        source: "iana"
      },
      "application/prs.plucker": {
        source: "iana"
      },
      "application/prs.rdf-xml-crypt": {
        source: "iana"
      },
      "application/prs.xsf+xml": {
        source: "iana",
        compressible: true
      },
      "application/pskc+xml": {
        source: "iana",
        compressible: true,
        extensions: ["pskcxml"]
      },
      "application/pvd+json": {
        source: "iana",
        compressible: true
      },
      "application/qsig": {
        source: "iana"
      },
      "application/raml+yaml": {
        compressible: true,
        extensions: ["raml"]
      },
      "application/raptorfec": {
        source: "iana"
      },
      "application/rdap+json": {
        source: "iana",
        compressible: true
      },
      "application/rdf+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rdf", "owl"]
      },
      "application/reginfo+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rif"]
      },
      "application/relax-ng-compact-syntax": {
        source: "iana",
        extensions: ["rnc"]
      },
      "application/remote-printing": {
        source: "iana"
      },
      "application/reputon+json": {
        source: "iana",
        compressible: true
      },
      "application/resource-lists+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rl"]
      },
      "application/resource-lists-diff+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rld"]
      },
      "application/rfc+xml": {
        source: "iana",
        compressible: true
      },
      "application/riscos": {
        source: "iana"
      },
      "application/rlmi+xml": {
        source: "iana",
        compressible: true
      },
      "application/rls-services+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rs"]
      },
      "application/route-apd+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rapd"]
      },
      "application/route-s-tsid+xml": {
        source: "iana",
        compressible: true,
        extensions: ["sls"]
      },
      "application/route-usd+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rusd"]
      },
      "application/rpki-ghostbusters": {
        source: "iana",
        extensions: ["gbr"]
      },
      "application/rpki-manifest": {
        source: "iana",
        extensions: ["mft"]
      },
      "application/rpki-publication": {
        source: "iana"
      },
      "application/rpki-roa": {
        source: "iana",
        extensions: ["roa"]
      },
      "application/rpki-updown": {
        source: "iana"
      },
      "application/rsd+xml": {
        source: "apache",
        compressible: true,
        extensions: ["rsd"]
      },
      "application/rss+xml": {
        source: "apache",
        compressible: true,
        extensions: ["rss"]
      },
      "application/rtf": {
        source: "iana",
        compressible: true,
        extensions: ["rtf"]
      },
      "application/rtploopback": {
        source: "iana"
      },
      "application/rtx": {
        source: "iana"
      },
      "application/samlassertion+xml": {
        source: "iana",
        compressible: true
      },
      "application/samlmetadata+xml": {
        source: "iana",
        compressible: true
      },
      "application/sarif+json": {
        source: "iana",
        compressible: true
      },
      "application/sarif-external-properties+json": {
        source: "iana",
        compressible: true
      },
      "application/sbe": {
        source: "iana"
      },
      "application/sbml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["sbml"]
      },
      "application/scaip+xml": {
        source: "iana",
        compressible: true
      },
      "application/scim+json": {
        source: "iana",
        compressible: true
      },
      "application/scvp-cv-request": {
        source: "iana",
        extensions: ["scq"]
      },
      "application/scvp-cv-response": {
        source: "iana",
        extensions: ["scs"]
      },
      "application/scvp-vp-request": {
        source: "iana",
        extensions: ["spq"]
      },
      "application/scvp-vp-response": {
        source: "iana",
        extensions: ["spp"]
      },
      "application/sdp": {
        source: "iana",
        extensions: ["sdp"]
      },
      "application/secevent+jwt": {
        source: "iana"
      },
      "application/senml+cbor": {
        source: "iana"
      },
      "application/senml+json": {
        source: "iana",
        compressible: true
      },
      "application/senml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["senmlx"]
      },
      "application/senml-etch+cbor": {
        source: "iana"
      },
      "application/senml-etch+json": {
        source: "iana",
        compressible: true
      },
      "application/senml-exi": {
        source: "iana"
      },
      "application/sensml+cbor": {
        source: "iana"
      },
      "application/sensml+json": {
        source: "iana",
        compressible: true
      },
      "application/sensml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["sensmlx"]
      },
      "application/sensml-exi": {
        source: "iana"
      },
      "application/sep+xml": {
        source: "iana",
        compressible: true
      },
      "application/sep-exi": {
        source: "iana"
      },
      "application/session-info": {
        source: "iana"
      },
      "application/set-payment": {
        source: "iana"
      },
      "application/set-payment-initiation": {
        source: "iana",
        extensions: ["setpay"]
      },
      "application/set-registration": {
        source: "iana"
      },
      "application/set-registration-initiation": {
        source: "iana",
        extensions: ["setreg"]
      },
      "application/sgml": {
        source: "iana"
      },
      "application/sgml-open-catalog": {
        source: "iana"
      },
      "application/shf+xml": {
        source: "iana",
        compressible: true,
        extensions: ["shf"]
      },
      "application/sieve": {
        source: "iana",
        extensions: ["siv", "sieve"]
      },
      "application/simple-filter+xml": {
        source: "iana",
        compressible: true
      },
      "application/simple-message-summary": {
        source: "iana"
      },
      "application/simplesymbolcontainer": {
        source: "iana"
      },
      "application/sipc": {
        source: "iana"
      },
      "application/slate": {
        source: "iana"
      },
      "application/smil": {
        source: "iana"
      },
      "application/smil+xml": {
        source: "iana",
        compressible: true,
        extensions: ["smi", "smil"]
      },
      "application/smpte336m": {
        source: "iana"
      },
      "application/soap+fastinfoset": {
        source: "iana"
      },
      "application/soap+xml": {
        source: "iana",
        compressible: true
      },
      "application/sparql-query": {
        source: "iana",
        extensions: ["rq"]
      },
      "application/sparql-results+xml": {
        source: "iana",
        compressible: true,
        extensions: ["srx"]
      },
      "application/spdx+json": {
        source: "iana",
        compressible: true
      },
      "application/spirits-event+xml": {
        source: "iana",
        compressible: true
      },
      "application/sql": {
        source: "iana"
      },
      "application/srgs": {
        source: "iana",
        extensions: ["gram"]
      },
      "application/srgs+xml": {
        source: "iana",
        compressible: true,
        extensions: ["grxml"]
      },
      "application/sru+xml": {
        source: "iana",
        compressible: true,
        extensions: ["sru"]
      },
      "application/ssdl+xml": {
        source: "apache",
        compressible: true,
        extensions: ["ssdl"]
      },
      "application/ssml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["ssml"]
      },
      "application/stix+json": {
        source: "iana",
        compressible: true
      },
      "application/swid+xml": {
        source: "iana",
        compressible: true,
        extensions: ["swidtag"]
      },
      "application/tamp-apex-update": {
        source: "iana"
      },
      "application/tamp-apex-update-confirm": {
        source: "iana"
      },
      "application/tamp-community-update": {
        source: "iana"
      },
      "application/tamp-community-update-confirm": {
        source: "iana"
      },
      "application/tamp-error": {
        source: "iana"
      },
      "application/tamp-sequence-adjust": {
        source: "iana"
      },
      "application/tamp-sequence-adjust-confirm": {
        source: "iana"
      },
      "application/tamp-status-query": {
        source: "iana"
      },
      "application/tamp-status-response": {
        source: "iana"
      },
      "application/tamp-update": {
        source: "iana"
      },
      "application/tamp-update-confirm": {
        source: "iana"
      },
      "application/tar": {
        compressible: true
      },
      "application/taxii+json": {
        source: "iana",
        compressible: true
      },
      "application/td+json": {
        source: "iana",
        compressible: true
      },
      "application/tei+xml": {
        source: "iana",
        compressible: true,
        extensions: ["tei", "teicorpus"]
      },
      "application/tetra_isi": {
        source: "iana"
      },
      "application/thraud+xml": {
        source: "iana",
        compressible: true,
        extensions: ["tfi"]
      },
      "application/timestamp-query": {
        source: "iana"
      },
      "application/timestamp-reply": {
        source: "iana"
      },
      "application/timestamped-data": {
        source: "iana",
        extensions: ["tsd"]
      },
      "application/tlsrpt+gzip": {
        source: "iana"
      },
      "application/tlsrpt+json": {
        source: "iana",
        compressible: true
      },
      "application/tnauthlist": {
        source: "iana"
      },
      "application/token-introspection+jwt": {
        source: "iana"
      },
      "application/toml": {
        compressible: true,
        extensions: ["toml"]
      },
      "application/trickle-ice-sdpfrag": {
        source: "iana"
      },
      "application/trig": {
        source: "iana",
        extensions: ["trig"]
      },
      "application/ttml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["ttml"]
      },
      "application/tve-trigger": {
        source: "iana"
      },
      "application/tzif": {
        source: "iana"
      },
      "application/tzif-leap": {
        source: "iana"
      },
      "application/ubjson": {
        compressible: false,
        extensions: ["ubj"]
      },
      "application/ulpfec": {
        source: "iana"
      },
      "application/urc-grpsheet+xml": {
        source: "iana",
        compressible: true
      },
      "application/urc-ressheet+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rsheet"]
      },
      "application/urc-targetdesc+xml": {
        source: "iana",
        compressible: true,
        extensions: ["td"]
      },
      "application/urc-uisocketdesc+xml": {
        source: "iana",
        compressible: true
      },
      "application/vcard+json": {
        source: "iana",
        compressible: true
      },
      "application/vcard+xml": {
        source: "iana",
        compressible: true
      },
      "application/vemmi": {
        source: "iana"
      },
      "application/vividence.scriptfile": {
        source: "apache"
      },
      "application/vnd.1000minds.decision-model+xml": {
        source: "iana",
        compressible: true,
        extensions: ["1km"]
      },
      "application/vnd.3gpp-prose+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp-prose-pc3ch+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp-v2x-local-service-information": {
        source: "iana"
      },
      "application/vnd.3gpp.5gnas": {
        source: "iana"
      },
      "application/vnd.3gpp.access-transfer-events+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.bsf+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.gmop+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.gtpc": {
        source: "iana"
      },
      "application/vnd.3gpp.interworking-data": {
        source: "iana"
      },
      "application/vnd.3gpp.lpp": {
        source: "iana"
      },
      "application/vnd.3gpp.mc-signalling-ear": {
        source: "iana"
      },
      "application/vnd.3gpp.mcdata-affiliation-command+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcdata-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcdata-payload": {
        source: "iana"
      },
      "application/vnd.3gpp.mcdata-service-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcdata-signalling": {
        source: "iana"
      },
      "application/vnd.3gpp.mcdata-ue-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcdata-user-profile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-affiliation-command+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-floor-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-location-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-mbms-usage-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-service-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-signed+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-ue-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-ue-init-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-user-profile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-affiliation-command+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-affiliation-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-location-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-service-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-transmission-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-ue-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-user-profile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mid-call+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.ngap": {
        source: "iana"
      },
      "application/vnd.3gpp.pfcp": {
        source: "iana"
      },
      "application/vnd.3gpp.pic-bw-large": {
        source: "iana",
        extensions: ["plb"]
      },
      "application/vnd.3gpp.pic-bw-small": {
        source: "iana",
        extensions: ["psb"]
      },
      "application/vnd.3gpp.pic-bw-var": {
        source: "iana",
        extensions: ["pvb"]
      },
      "application/vnd.3gpp.s1ap": {
        source: "iana"
      },
      "application/vnd.3gpp.sms": {
        source: "iana"
      },
      "application/vnd.3gpp.sms+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.srvcc-ext+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.srvcc-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.state-and-event-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.ussd+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp2.bcmcsinfo+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp2.sms": {
        source: "iana"
      },
      "application/vnd.3gpp2.tcap": {
        source: "iana",
        extensions: ["tcap"]
      },
      "application/vnd.3lightssoftware.imagescal": {
        source: "iana"
      },
      "application/vnd.3m.post-it-notes": {
        source: "iana",
        extensions: ["pwn"]
      },
      "application/vnd.accpac.simply.aso": {
        source: "iana",
        extensions: ["aso"]
      },
      "application/vnd.accpac.simply.imp": {
        source: "iana",
        extensions: ["imp"]
      },
      "application/vnd.acucobol": {
        source: "iana",
        extensions: ["acu"]
      },
      "application/vnd.acucorp": {
        source: "iana",
        extensions: ["atc", "acutc"]
      },
      "application/vnd.adobe.air-application-installer-package+zip": {
        source: "apache",
        compressible: false,
        extensions: ["air"]
      },
      "application/vnd.adobe.flash.movie": {
        source: "iana"
      },
      "application/vnd.adobe.formscentral.fcdt": {
        source: "iana",
        extensions: ["fcdt"]
      },
      "application/vnd.adobe.fxp": {
        source: "iana",
        extensions: ["fxp", "fxpl"]
      },
      "application/vnd.adobe.partial-upload": {
        source: "iana"
      },
      "application/vnd.adobe.xdp+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xdp"]
      },
      "application/vnd.adobe.xfdf": {
        source: "iana",
        extensions: ["xfdf"]
      },
      "application/vnd.aether.imp": {
        source: "iana"
      },
      "application/vnd.afpc.afplinedata": {
        source: "iana"
      },
      "application/vnd.afpc.afplinedata-pagedef": {
        source: "iana"
      },
      "application/vnd.afpc.cmoca-cmresource": {
        source: "iana"
      },
      "application/vnd.afpc.foca-charset": {
        source: "iana"
      },
      "application/vnd.afpc.foca-codedfont": {
        source: "iana"
      },
      "application/vnd.afpc.foca-codepage": {
        source: "iana"
      },
      "application/vnd.afpc.modca": {
        source: "iana"
      },
      "application/vnd.afpc.modca-cmtable": {
        source: "iana"
      },
      "application/vnd.afpc.modca-formdef": {
        source: "iana"
      },
      "application/vnd.afpc.modca-mediummap": {
        source: "iana"
      },
      "application/vnd.afpc.modca-objectcontainer": {
        source: "iana"
      },
      "application/vnd.afpc.modca-overlay": {
        source: "iana"
      },
      "application/vnd.afpc.modca-pagesegment": {
        source: "iana"
      },
      "application/vnd.age": {
        source: "iana",
        extensions: ["age"]
      },
      "application/vnd.ah-barcode": {
        source: "iana"
      },
      "application/vnd.ahead.space": {
        source: "iana",
        extensions: ["ahead"]
      },
      "application/vnd.airzip.filesecure.azf": {
        source: "iana",
        extensions: ["azf"]
      },
      "application/vnd.airzip.filesecure.azs": {
        source: "iana",
        extensions: ["azs"]
      },
      "application/vnd.amadeus+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.amazon.ebook": {
        source: "apache",
        extensions: ["azw"]
      },
      "application/vnd.amazon.mobi8-ebook": {
        source: "iana"
      },
      "application/vnd.americandynamics.acc": {
        source: "iana",
        extensions: ["acc"]
      },
      "application/vnd.amiga.ami": {
        source: "iana",
        extensions: ["ami"]
      },
      "application/vnd.amundsen.maze+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.android.ota": {
        source: "iana"
      },
      "application/vnd.android.package-archive": {
        source: "apache",
        compressible: false,
        extensions: ["apk"]
      },
      "application/vnd.anki": {
        source: "iana"
      },
      "application/vnd.anser-web-certificate-issue-initiation": {
        source: "iana",
        extensions: ["cii"]
      },
      "application/vnd.anser-web-funds-transfer-initiation": {
        source: "apache",
        extensions: ["fti"]
      },
      "application/vnd.antix.game-component": {
        source: "iana",
        extensions: ["atx"]
      },
      "application/vnd.apache.arrow.file": {
        source: "iana"
      },
      "application/vnd.apache.arrow.stream": {
        source: "iana"
      },
      "application/vnd.apache.thrift.binary": {
        source: "iana"
      },
      "application/vnd.apache.thrift.compact": {
        source: "iana"
      },
      "application/vnd.apache.thrift.json": {
        source: "iana"
      },
      "application/vnd.api+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.aplextor.warrp+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.apothekende.reservation+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.apple.installer+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mpkg"]
      },
      "application/vnd.apple.keynote": {
        source: "iana",
        extensions: ["key"]
      },
      "application/vnd.apple.mpegurl": {
        source: "iana",
        extensions: ["m3u8"]
      },
      "application/vnd.apple.numbers": {
        source: "iana",
        extensions: ["numbers"]
      },
      "application/vnd.apple.pages": {
        source: "iana",
        extensions: ["pages"]
      },
      "application/vnd.apple.pkpass": {
        compressible: false,
        extensions: ["pkpass"]
      },
      "application/vnd.arastra.swi": {
        source: "iana"
      },
      "application/vnd.aristanetworks.swi": {
        source: "iana",
        extensions: ["swi"]
      },
      "application/vnd.artisan+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.artsquare": {
        source: "iana"
      },
      "application/vnd.astraea-software.iota": {
        source: "iana",
        extensions: ["iota"]
      },
      "application/vnd.audiograph": {
        source: "iana",
        extensions: ["aep"]
      },
      "application/vnd.autopackage": {
        source: "iana"
      },
      "application/vnd.avalon+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.avistar+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.balsamiq.bmml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["bmml"]
      },
      "application/vnd.balsamiq.bmpr": {
        source: "iana"
      },
      "application/vnd.banana-accounting": {
        source: "iana"
      },
      "application/vnd.bbf.usp.error": {
        source: "iana"
      },
      "application/vnd.bbf.usp.msg": {
        source: "iana"
      },
      "application/vnd.bbf.usp.msg+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.bekitzur-stech+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.bint.med-content": {
        source: "iana"
      },
      "application/vnd.biopax.rdf+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.blink-idb-value-wrapper": {
        source: "iana"
      },
      "application/vnd.blueice.multipass": {
        source: "iana",
        extensions: ["mpm"]
      },
      "application/vnd.bluetooth.ep.oob": {
        source: "iana"
      },
      "application/vnd.bluetooth.le.oob": {
        source: "iana"
      },
      "application/vnd.bmi": {
        source: "iana",
        extensions: ["bmi"]
      },
      "application/vnd.bpf": {
        source: "iana"
      },
      "application/vnd.bpf3": {
        source: "iana"
      },
      "application/vnd.businessobjects": {
        source: "iana",
        extensions: ["rep"]
      },
      "application/vnd.byu.uapi+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.cab-jscript": {
        source: "iana"
      },
      "application/vnd.canon-cpdl": {
        source: "iana"
      },
      "application/vnd.canon-lips": {
        source: "iana"
      },
      "application/vnd.capasystems-pg+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.cendio.thinlinc.clientconf": {
        source: "iana"
      },
      "application/vnd.century-systems.tcp_stream": {
        source: "iana"
      },
      "application/vnd.chemdraw+xml": {
        source: "iana",
        compressible: true,
        extensions: ["cdxml"]
      },
      "application/vnd.chess-pgn": {
        source: "iana"
      },
      "application/vnd.chipnuts.karaoke-mmd": {
        source: "iana",
        extensions: ["mmd"]
      },
      "application/vnd.ciedi": {
        source: "iana"
      },
      "application/vnd.cinderella": {
        source: "iana",
        extensions: ["cdy"]
      },
      "application/vnd.cirpack.isdn-ext": {
        source: "iana"
      },
      "application/vnd.citationstyles.style+xml": {
        source: "iana",
        compressible: true,
        extensions: ["csl"]
      },
      "application/vnd.claymore": {
        source: "iana",
        extensions: ["cla"]
      },
      "application/vnd.cloanto.rp9": {
        source: "iana",
        extensions: ["rp9"]
      },
      "application/vnd.clonk.c4group": {
        source: "iana",
        extensions: ["c4g", "c4d", "c4f", "c4p", "c4u"]
      },
      "application/vnd.cluetrust.cartomobile-config": {
        source: "iana",
        extensions: ["c11amc"]
      },
      "application/vnd.cluetrust.cartomobile-config-pkg": {
        source: "iana",
        extensions: ["c11amz"]
      },
      "application/vnd.coffeescript": {
        source: "iana"
      },
      "application/vnd.collabio.xodocuments.document": {
        source: "iana"
      },
      "application/vnd.collabio.xodocuments.document-template": {
        source: "iana"
      },
      "application/vnd.collabio.xodocuments.presentation": {
        source: "iana"
      },
      "application/vnd.collabio.xodocuments.presentation-template": {
        source: "iana"
      },
      "application/vnd.collabio.xodocuments.spreadsheet": {
        source: "iana"
      },
      "application/vnd.collabio.xodocuments.spreadsheet-template": {
        source: "iana"
      },
      "application/vnd.collection+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.collection.doc+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.collection.next+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.comicbook+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.comicbook-rar": {
        source: "iana"
      },
      "application/vnd.commerce-battelle": {
        source: "iana"
      },
      "application/vnd.commonspace": {
        source: "iana",
        extensions: ["csp"]
      },
      "application/vnd.contact.cmsg": {
        source: "iana",
        extensions: ["cdbcmsg"]
      },
      "application/vnd.coreos.ignition+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.cosmocaller": {
        source: "iana",
        extensions: ["cmc"]
      },
      "application/vnd.crick.clicker": {
        source: "iana",
        extensions: ["clkx"]
      },
      "application/vnd.crick.clicker.keyboard": {
        source: "iana",
        extensions: ["clkk"]
      },
      "application/vnd.crick.clicker.palette": {
        source: "iana",
        extensions: ["clkp"]
      },
      "application/vnd.crick.clicker.template": {
        source: "iana",
        extensions: ["clkt"]
      },
      "application/vnd.crick.clicker.wordbank": {
        source: "iana",
        extensions: ["clkw"]
      },
      "application/vnd.criticaltools.wbs+xml": {
        source: "iana",
        compressible: true,
        extensions: ["wbs"]
      },
      "application/vnd.cryptii.pipe+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.crypto-shade-file": {
        source: "iana"
      },
      "application/vnd.cryptomator.encrypted": {
        source: "iana"
      },
      "application/vnd.cryptomator.vault": {
        source: "iana"
      },
      "application/vnd.ctc-posml": {
        source: "iana",
        extensions: ["pml"]
      },
      "application/vnd.ctct.ws+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.cups-pdf": {
        source: "iana"
      },
      "application/vnd.cups-postscript": {
        source: "iana"
      },
      "application/vnd.cups-ppd": {
        source: "iana",
        extensions: ["ppd"]
      },
      "application/vnd.cups-raster": {
        source: "iana"
      },
      "application/vnd.cups-raw": {
        source: "iana"
      },
      "application/vnd.curl": {
        source: "iana"
      },
      "application/vnd.curl.car": {
        source: "apache",
        extensions: ["car"]
      },
      "application/vnd.curl.pcurl": {
        source: "apache",
        extensions: ["pcurl"]
      },
      "application/vnd.cyan.dean.root+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.cybank": {
        source: "iana"
      },
      "application/vnd.cyclonedx+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.cyclonedx+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.d2l.coursepackage1p0+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.d3m-dataset": {
        source: "iana"
      },
      "application/vnd.d3m-problem": {
        source: "iana"
      },
      "application/vnd.dart": {
        source: "iana",
        compressible: true,
        extensions: ["dart"]
      },
      "application/vnd.data-vision.rdz": {
        source: "iana",
        extensions: ["rdz"]
      },
      "application/vnd.datapackage+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dataresource+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dbf": {
        source: "iana",
        extensions: ["dbf"]
      },
      "application/vnd.debian.binary-package": {
        source: "iana"
      },
      "application/vnd.dece.data": {
        source: "iana",
        extensions: ["uvf", "uvvf", "uvd", "uvvd"]
      },
      "application/vnd.dece.ttml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["uvt", "uvvt"]
      },
      "application/vnd.dece.unspecified": {
        source: "iana",
        extensions: ["uvx", "uvvx"]
      },
      "application/vnd.dece.zip": {
        source: "iana",
        extensions: ["uvz", "uvvz"]
      },
      "application/vnd.denovo.fcselayout-link": {
        source: "iana",
        extensions: ["fe_launch"]
      },
      "application/vnd.desmume.movie": {
        source: "iana"
      },
      "application/vnd.dir-bi.plate-dl-nosuffix": {
        source: "iana"
      },
      "application/vnd.dm.delegation+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dna": {
        source: "iana",
        extensions: ["dna"]
      },
      "application/vnd.document+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dolby.mlp": {
        source: "apache",
        extensions: ["mlp"]
      },
      "application/vnd.dolby.mobile.1": {
        source: "iana"
      },
      "application/vnd.dolby.mobile.2": {
        source: "iana"
      },
      "application/vnd.doremir.scorecloud-binary-document": {
        source: "iana"
      },
      "application/vnd.dpgraph": {
        source: "iana",
        extensions: ["dpg"]
      },
      "application/vnd.dreamfactory": {
        source: "iana",
        extensions: ["dfac"]
      },
      "application/vnd.drive+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ds-keypoint": {
        source: "apache",
        extensions: ["kpxx"]
      },
      "application/vnd.dtg.local": {
        source: "iana"
      },
      "application/vnd.dtg.local.flash": {
        source: "iana"
      },
      "application/vnd.dtg.local.html": {
        source: "iana"
      },
      "application/vnd.dvb.ait": {
        source: "iana",
        extensions: ["ait"]
      },
      "application/vnd.dvb.dvbisl+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.dvbj": {
        source: "iana"
      },
      "application/vnd.dvb.esgcontainer": {
        source: "iana"
      },
      "application/vnd.dvb.ipdcdftnotifaccess": {
        source: "iana"
      },
      "application/vnd.dvb.ipdcesgaccess": {
        source: "iana"
      },
      "application/vnd.dvb.ipdcesgaccess2": {
        source: "iana"
      },
      "application/vnd.dvb.ipdcesgpdd": {
        source: "iana"
      },
      "application/vnd.dvb.ipdcroaming": {
        source: "iana"
      },
      "application/vnd.dvb.iptv.alfec-base": {
        source: "iana"
      },
      "application/vnd.dvb.iptv.alfec-enhancement": {
        source: "iana"
      },
      "application/vnd.dvb.notif-aggregate-root+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.notif-container+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.notif-generic+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.notif-ia-msglist+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.notif-ia-registration-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.notif-ia-registration-response+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.notif-init+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.pfr": {
        source: "iana"
      },
      "application/vnd.dvb.service": {
        source: "iana",
        extensions: ["svc"]
      },
      "application/vnd.dxr": {
        source: "iana"
      },
      "application/vnd.dynageo": {
        source: "iana",
        extensions: ["geo"]
      },
      "application/vnd.dzr": {
        source: "iana"
      },
      "application/vnd.easykaraoke.cdgdownload": {
        source: "iana"
      },
      "application/vnd.ecdis-update": {
        source: "iana"
      },
      "application/vnd.ecip.rlp": {
        source: "iana"
      },
      "application/vnd.eclipse.ditto+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ecowin.chart": {
        source: "iana",
        extensions: ["mag"]
      },
      "application/vnd.ecowin.filerequest": {
        source: "iana"
      },
      "application/vnd.ecowin.fileupdate": {
        source: "iana"
      },
      "application/vnd.ecowin.series": {
        source: "iana"
      },
      "application/vnd.ecowin.seriesrequest": {
        source: "iana"
      },
      "application/vnd.ecowin.seriesupdate": {
        source: "iana"
      },
      "application/vnd.efi.img": {
        source: "iana"
      },
      "application/vnd.efi.iso": {
        source: "iana"
      },
      "application/vnd.emclient.accessrequest+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.enliven": {
        source: "iana",
        extensions: ["nml"]
      },
      "application/vnd.enphase.envoy": {
        source: "iana"
      },
      "application/vnd.eprints.data+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.epson.esf": {
        source: "iana",
        extensions: ["esf"]
      },
      "application/vnd.epson.msf": {
        source: "iana",
        extensions: ["msf"]
      },
      "application/vnd.epson.quickanime": {
        source: "iana",
        extensions: ["qam"]
      },
      "application/vnd.epson.salt": {
        source: "iana",
        extensions: ["slt"]
      },
      "application/vnd.epson.ssf": {
        source: "iana",
        extensions: ["ssf"]
      },
      "application/vnd.ericsson.quickcall": {
        source: "iana"
      },
      "application/vnd.espass-espass+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.eszigno3+xml": {
        source: "iana",
        compressible: true,
        extensions: ["es3", "et3"]
      },
      "application/vnd.etsi.aoc+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.asic-e+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.etsi.asic-s+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.etsi.cug+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvcommand+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvdiscovery+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvprofile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvsad-bc+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvsad-cod+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvsad-npvr+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvservice+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvsync+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvueprofile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.mcid+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.mheg5": {
        source: "iana"
      },
      "application/vnd.etsi.overload-control-policy-dataset+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.pstn+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.sci+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.simservs+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.timestamp-token": {
        source: "iana"
      },
      "application/vnd.etsi.tsl+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.tsl.der": {
        source: "iana"
      },
      "application/vnd.eu.kasparian.car+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.eudora.data": {
        source: "iana"
      },
      "application/vnd.evolv.ecig.profile": {
        source: "iana"
      },
      "application/vnd.evolv.ecig.settings": {
        source: "iana"
      },
      "application/vnd.evolv.ecig.theme": {
        source: "iana"
      },
      "application/vnd.exstream-empower+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.exstream-package": {
        source: "iana"
      },
      "application/vnd.ezpix-album": {
        source: "iana",
        extensions: ["ez2"]
      },
      "application/vnd.ezpix-package": {
        source: "iana",
        extensions: ["ez3"]
      },
      "application/vnd.f-secure.mobile": {
        source: "iana"
      },
      "application/vnd.familysearch.gedcom+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.fastcopy-disk-image": {
        source: "iana"
      },
      "application/vnd.fdf": {
        source: "iana",
        extensions: ["fdf"]
      },
      "application/vnd.fdsn.mseed": {
        source: "iana",
        extensions: ["mseed"]
      },
      "application/vnd.fdsn.seed": {
        source: "iana",
        extensions: ["seed", "dataless"]
      },
      "application/vnd.ffsns": {
        source: "iana"
      },
      "application/vnd.ficlab.flb+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.filmit.zfc": {
        source: "iana"
      },
      "application/vnd.fints": {
        source: "iana"
      },
      "application/vnd.firemonkeys.cloudcell": {
        source: "iana"
      },
      "application/vnd.flographit": {
        source: "iana",
        extensions: ["gph"]
      },
      "application/vnd.fluxtime.clip": {
        source: "iana",
        extensions: ["ftc"]
      },
      "application/vnd.font-fontforge-sfd": {
        source: "iana"
      },
      "application/vnd.framemaker": {
        source: "iana",
        extensions: ["fm", "frame", "maker", "book"]
      },
      "application/vnd.frogans.fnc": {
        source: "iana",
        extensions: ["fnc"]
      },
      "application/vnd.frogans.ltf": {
        source: "iana",
        extensions: ["ltf"]
      },
      "application/vnd.fsc.weblaunch": {
        source: "iana",
        extensions: ["fsc"]
      },
      "application/vnd.fujifilm.fb.docuworks": {
        source: "iana"
      },
      "application/vnd.fujifilm.fb.docuworks.binder": {
        source: "iana"
      },
      "application/vnd.fujifilm.fb.docuworks.container": {
        source: "iana"
      },
      "application/vnd.fujifilm.fb.jfi+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.fujitsu.oasys": {
        source: "iana",
        extensions: ["oas"]
      },
      "application/vnd.fujitsu.oasys2": {
        source: "iana",
        extensions: ["oa2"]
      },
      "application/vnd.fujitsu.oasys3": {
        source: "iana",
        extensions: ["oa3"]
      },
      "application/vnd.fujitsu.oasysgp": {
        source: "iana",
        extensions: ["fg5"]
      },
      "application/vnd.fujitsu.oasysprs": {
        source: "iana",
        extensions: ["bh2"]
      },
      "application/vnd.fujixerox.art-ex": {
        source: "iana"
      },
      "application/vnd.fujixerox.art4": {
        source: "iana"
      },
      "application/vnd.fujixerox.ddd": {
        source: "iana",
        extensions: ["ddd"]
      },
      "application/vnd.fujixerox.docuworks": {
        source: "iana",
        extensions: ["xdw"]
      },
      "application/vnd.fujixerox.docuworks.binder": {
        source: "iana",
        extensions: ["xbd"]
      },
      "application/vnd.fujixerox.docuworks.container": {
        source: "iana"
      },
      "application/vnd.fujixerox.hbpl": {
        source: "iana"
      },
      "application/vnd.fut-misnet": {
        source: "iana"
      },
      "application/vnd.futoin+cbor": {
        source: "iana"
      },
      "application/vnd.futoin+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.fuzzysheet": {
        source: "iana",
        extensions: ["fzs"]
      },
      "application/vnd.genomatix.tuxedo": {
        source: "iana",
        extensions: ["txd"]
      },
      "application/vnd.gentics.grd+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.geo+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.geocube+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.geogebra.file": {
        source: "iana",
        extensions: ["ggb"]
      },
      "application/vnd.geogebra.slides": {
        source: "iana"
      },
      "application/vnd.geogebra.tool": {
        source: "iana",
        extensions: ["ggt"]
      },
      "application/vnd.geometry-explorer": {
        source: "iana",
        extensions: ["gex", "gre"]
      },
      "application/vnd.geonext": {
        source: "iana",
        extensions: ["gxt"]
      },
      "application/vnd.geoplan": {
        source: "iana",
        extensions: ["g2w"]
      },
      "application/vnd.geospace": {
        source: "iana",
        extensions: ["g3w"]
      },
      "application/vnd.gerber": {
        source: "iana"
      },
      "application/vnd.globalplatform.card-content-mgt": {
        source: "iana"
      },
      "application/vnd.globalplatform.card-content-mgt-response": {
        source: "iana"
      },
      "application/vnd.gmx": {
        source: "iana",
        extensions: ["gmx"]
      },
      "application/vnd.google-apps.document": {
        compressible: false,
        extensions: ["gdoc"]
      },
      "application/vnd.google-apps.presentation": {
        compressible: false,
        extensions: ["gslides"]
      },
      "application/vnd.google-apps.spreadsheet": {
        compressible: false,
        extensions: ["gsheet"]
      },
      "application/vnd.google-earth.kml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["kml"]
      },
      "application/vnd.google-earth.kmz": {
        source: "iana",
        compressible: false,
        extensions: ["kmz"]
      },
      "application/vnd.gov.sk.e-form+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.gov.sk.e-form+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.gov.sk.xmldatacontainer+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.grafeq": {
        source: "iana",
        extensions: ["gqf", "gqs"]
      },
      "application/vnd.gridmp": {
        source: "iana"
      },
      "application/vnd.groove-account": {
        source: "iana",
        extensions: ["gac"]
      },
      "application/vnd.groove-help": {
        source: "iana",
        extensions: ["ghf"]
      },
      "application/vnd.groove-identity-message": {
        source: "iana",
        extensions: ["gim"]
      },
      "application/vnd.groove-injector": {
        source: "iana",
        extensions: ["grv"]
      },
      "application/vnd.groove-tool-message": {
        source: "iana",
        extensions: ["gtm"]
      },
      "application/vnd.groove-tool-template": {
        source: "iana",
        extensions: ["tpl"]
      },
      "application/vnd.groove-vcard": {
        source: "iana",
        extensions: ["vcg"]
      },
      "application/vnd.hal+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.hal+xml": {
        source: "iana",
        compressible: true,
        extensions: ["hal"]
      },
      "application/vnd.handheld-entertainment+xml": {
        source: "iana",
        compressible: true,
        extensions: ["zmm"]
      },
      "application/vnd.hbci": {
        source: "iana",
        extensions: ["hbci"]
      },
      "application/vnd.hc+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.hcl-bireports": {
        source: "iana"
      },
      "application/vnd.hdt": {
        source: "iana"
      },
      "application/vnd.heroku+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.hhe.lesson-player": {
        source: "iana",
        extensions: ["les"]
      },
      "application/vnd.hl7cda+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/vnd.hl7v2+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/vnd.hp-hpgl": {
        source: "iana",
        extensions: ["hpgl"]
      },
      "application/vnd.hp-hpid": {
        source: "iana",
        extensions: ["hpid"]
      },
      "application/vnd.hp-hps": {
        source: "iana",
        extensions: ["hps"]
      },
      "application/vnd.hp-jlyt": {
        source: "iana",
        extensions: ["jlt"]
      },
      "application/vnd.hp-pcl": {
        source: "iana",
        extensions: ["pcl"]
      },
      "application/vnd.hp-pclxl": {
        source: "iana",
        extensions: ["pclxl"]
      },
      "application/vnd.httphone": {
        source: "iana"
      },
      "application/vnd.hydrostatix.sof-data": {
        source: "iana",
        extensions: ["sfd-hdstx"]
      },
      "application/vnd.hyper+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.hyper-item+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.hyperdrive+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.hzn-3d-crossword": {
        source: "iana"
      },
      "application/vnd.ibm.afplinedata": {
        source: "iana"
      },
      "application/vnd.ibm.electronic-media": {
        source: "iana"
      },
      "application/vnd.ibm.minipay": {
        source: "iana",
        extensions: ["mpy"]
      },
      "application/vnd.ibm.modcap": {
        source: "iana",
        extensions: ["afp", "listafp", "list3820"]
      },
      "application/vnd.ibm.rights-management": {
        source: "iana",
        extensions: ["irm"]
      },
      "application/vnd.ibm.secure-container": {
        source: "iana",
        extensions: ["sc"]
      },
      "application/vnd.iccprofile": {
        source: "iana",
        extensions: ["icc", "icm"]
      },
      "application/vnd.ieee.1905": {
        source: "iana"
      },
      "application/vnd.igloader": {
        source: "iana",
        extensions: ["igl"]
      },
      "application/vnd.imagemeter.folder+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.imagemeter.image+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.immervision-ivp": {
        source: "iana",
        extensions: ["ivp"]
      },
      "application/vnd.immervision-ivu": {
        source: "iana",
        extensions: ["ivu"]
      },
      "application/vnd.ims.imsccv1p1": {
        source: "iana"
      },
      "application/vnd.ims.imsccv1p2": {
        source: "iana"
      },
      "application/vnd.ims.imsccv1p3": {
        source: "iana"
      },
      "application/vnd.ims.lis.v2.result+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ims.lti.v2.toolconsumerprofile+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ims.lti.v2.toolproxy+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ims.lti.v2.toolproxy.id+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ims.lti.v2.toolsettings+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ims.lti.v2.toolsettings.simple+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.informedcontrol.rms+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.informix-visionary": {
        source: "iana"
      },
      "application/vnd.infotech.project": {
        source: "iana"
      },
      "application/vnd.infotech.project+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.innopath.wamp.notification": {
        source: "iana"
      },
      "application/vnd.insors.igm": {
        source: "iana",
        extensions: ["igm"]
      },
      "application/vnd.intercon.formnet": {
        source: "iana",
        extensions: ["xpw", "xpx"]
      },
      "application/vnd.intergeo": {
        source: "iana",
        extensions: ["i2g"]
      },
      "application/vnd.intertrust.digibox": {
        source: "iana"
      },
      "application/vnd.intertrust.nncp": {
        source: "iana"
      },
      "application/vnd.intu.qbo": {
        source: "iana",
        extensions: ["qbo"]
      },
      "application/vnd.intu.qfx": {
        source: "iana",
        extensions: ["qfx"]
      },
      "application/vnd.iptc.g2.catalogitem+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.iptc.g2.conceptitem+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.iptc.g2.knowledgeitem+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.iptc.g2.newsitem+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.iptc.g2.newsmessage+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.iptc.g2.packageitem+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.iptc.g2.planningitem+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ipunplugged.rcprofile": {
        source: "iana",
        extensions: ["rcprofile"]
      },
      "application/vnd.irepository.package+xml": {
        source: "iana",
        compressible: true,
        extensions: ["irp"]
      },
      "application/vnd.is-xpr": {
        source: "iana",
        extensions: ["xpr"]
      },
      "application/vnd.isac.fcs": {
        source: "iana",
        extensions: ["fcs"]
      },
      "application/vnd.iso11783-10+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.jam": {
        source: "iana",
        extensions: ["jam"]
      },
      "application/vnd.japannet-directory-service": {
        source: "iana"
      },
      "application/vnd.japannet-jpnstore-wakeup": {
        source: "iana"
      },
      "application/vnd.japannet-payment-wakeup": {
        source: "iana"
      },
      "application/vnd.japannet-registration": {
        source: "iana"
      },
      "application/vnd.japannet-registration-wakeup": {
        source: "iana"
      },
      "application/vnd.japannet-setstore-wakeup": {
        source: "iana"
      },
      "application/vnd.japannet-verification": {
        source: "iana"
      },
      "application/vnd.japannet-verification-wakeup": {
        source: "iana"
      },
      "application/vnd.jcp.javame.midlet-rms": {
        source: "iana",
        extensions: ["rms"]
      },
      "application/vnd.jisp": {
        source: "iana",
        extensions: ["jisp"]
      },
      "application/vnd.joost.joda-archive": {
        source: "iana",
        extensions: ["joda"]
      },
      "application/vnd.jsk.isdn-ngn": {
        source: "iana"
      },
      "application/vnd.kahootz": {
        source: "iana",
        extensions: ["ktz", "ktr"]
      },
      "application/vnd.kde.karbon": {
        source: "iana",
        extensions: ["karbon"]
      },
      "application/vnd.kde.kchart": {
        source: "iana",
        extensions: ["chrt"]
      },
      "application/vnd.kde.kformula": {
        source: "iana",
        extensions: ["kfo"]
      },
      "application/vnd.kde.kivio": {
        source: "iana",
        extensions: ["flw"]
      },
      "application/vnd.kde.kontour": {
        source: "iana",
        extensions: ["kon"]
      },
      "application/vnd.kde.kpresenter": {
        source: "iana",
        extensions: ["kpr", "kpt"]
      },
      "application/vnd.kde.kspread": {
        source: "iana",
        extensions: ["ksp"]
      },
      "application/vnd.kde.kword": {
        source: "iana",
        extensions: ["kwd", "kwt"]
      },
      "application/vnd.kenameaapp": {
        source: "iana",
        extensions: ["htke"]
      },
      "application/vnd.kidspiration": {
        source: "iana",
        extensions: ["kia"]
      },
      "application/vnd.kinar": {
        source: "iana",
        extensions: ["kne", "knp"]
      },
      "application/vnd.koan": {
        source: "iana",
        extensions: ["skp", "skd", "skt", "skm"]
      },
      "application/vnd.kodak-descriptor": {
        source: "iana",
        extensions: ["sse"]
      },
      "application/vnd.las": {
        source: "iana"
      },
      "application/vnd.las.las+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.las.las+xml": {
        source: "iana",
        compressible: true,
        extensions: ["lasxml"]
      },
      "application/vnd.laszip": {
        source: "iana"
      },
      "application/vnd.leap+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.liberty-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.llamagraphics.life-balance.desktop": {
        source: "iana",
        extensions: ["lbd"]
      },
      "application/vnd.llamagraphics.life-balance.exchange+xml": {
        source: "iana",
        compressible: true,
        extensions: ["lbe"]
      },
      "application/vnd.logipipe.circuit+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.loom": {
        source: "iana"
      },
      "application/vnd.lotus-1-2-3": {
        source: "iana",
        extensions: ["123"]
      },
      "application/vnd.lotus-approach": {
        source: "iana",
        extensions: ["apr"]
      },
      "application/vnd.lotus-freelance": {
        source: "iana",
        extensions: ["pre"]
      },
      "application/vnd.lotus-notes": {
        source: "iana",
        extensions: ["nsf"]
      },
      "application/vnd.lotus-organizer": {
        source: "iana",
        extensions: ["org"]
      },
      "application/vnd.lotus-screencam": {
        source: "iana",
        extensions: ["scm"]
      },
      "application/vnd.lotus-wordpro": {
        source: "iana",
        extensions: ["lwp"]
      },
      "application/vnd.macports.portpkg": {
        source: "iana",
        extensions: ["portpkg"]
      },
      "application/vnd.mapbox-vector-tile": {
        source: "iana",
        extensions: ["mvt"]
      },
      "application/vnd.marlin.drm.actiontoken+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.marlin.drm.conftoken+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.marlin.drm.license+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.marlin.drm.mdcf": {
        source: "iana"
      },
      "application/vnd.mason+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.maxar.archive.3tz+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.maxmind.maxmind-db": {
        source: "iana"
      },
      "application/vnd.mcd": {
        source: "iana",
        extensions: ["mcd"]
      },
      "application/vnd.medcalcdata": {
        source: "iana",
        extensions: ["mc1"]
      },
      "application/vnd.mediastation.cdkey": {
        source: "iana",
        extensions: ["cdkey"]
      },
      "application/vnd.meridian-slingshot": {
        source: "iana"
      },
      "application/vnd.mfer": {
        source: "iana",
        extensions: ["mwf"]
      },
      "application/vnd.mfmp": {
        source: "iana",
        extensions: ["mfm"]
      },
      "application/vnd.micro+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.micrografx.flo": {
        source: "iana",
        extensions: ["flo"]
      },
      "application/vnd.micrografx.igx": {
        source: "iana",
        extensions: ["igx"]
      },
      "application/vnd.microsoft.portable-executable": {
        source: "iana"
      },
      "application/vnd.microsoft.windows.thumbnail-cache": {
        source: "iana"
      },
      "application/vnd.miele+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.mif": {
        source: "iana",
        extensions: ["mif"]
      },
      "application/vnd.minisoft-hp3000-save": {
        source: "iana"
      },
      "application/vnd.mitsubishi.misty-guard.trustweb": {
        source: "iana"
      },
      "application/vnd.mobius.daf": {
        source: "iana",
        extensions: ["daf"]
      },
      "application/vnd.mobius.dis": {
        source: "iana",
        extensions: ["dis"]
      },
      "application/vnd.mobius.mbk": {
        source: "iana",
        extensions: ["mbk"]
      },
      "application/vnd.mobius.mqy": {
        source: "iana",
        extensions: ["mqy"]
      },
      "application/vnd.mobius.msl": {
        source: "iana",
        extensions: ["msl"]
      },
      "application/vnd.mobius.plc": {
        source: "iana",
        extensions: ["plc"]
      },
      "application/vnd.mobius.txf": {
        source: "iana",
        extensions: ["txf"]
      },
      "application/vnd.mophun.application": {
        source: "iana",
        extensions: ["mpn"]
      },
      "application/vnd.mophun.certificate": {
        source: "iana",
        extensions: ["mpc"]
      },
      "application/vnd.motorola.flexsuite": {
        source: "iana"
      },
      "application/vnd.motorola.flexsuite.adsi": {
        source: "iana"
      },
      "application/vnd.motorola.flexsuite.fis": {
        source: "iana"
      },
      "application/vnd.motorola.flexsuite.gotap": {
        source: "iana"
      },
      "application/vnd.motorola.flexsuite.kmr": {
        source: "iana"
      },
      "application/vnd.motorola.flexsuite.ttc": {
        source: "iana"
      },
      "application/vnd.motorola.flexsuite.wem": {
        source: "iana"
      },
      "application/vnd.motorola.iprm": {
        source: "iana"
      },
      "application/vnd.mozilla.xul+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xul"]
      },
      "application/vnd.ms-3mfdocument": {
        source: "iana"
      },
      "application/vnd.ms-artgalry": {
        source: "iana",
        extensions: ["cil"]
      },
      "application/vnd.ms-asf": {
        source: "iana"
      },
      "application/vnd.ms-cab-compressed": {
        source: "iana",
        extensions: ["cab"]
      },
      "application/vnd.ms-color.iccprofile": {
        source: "apache"
      },
      "application/vnd.ms-excel": {
        source: "iana",
        compressible: false,
        extensions: ["xls", "xlm", "xla", "xlc", "xlt", "xlw"]
      },
      "application/vnd.ms-excel.addin.macroenabled.12": {
        source: "iana",
        extensions: ["xlam"]
      },
      "application/vnd.ms-excel.sheet.binary.macroenabled.12": {
        source: "iana",
        extensions: ["xlsb"]
      },
      "application/vnd.ms-excel.sheet.macroenabled.12": {
        source: "iana",
        extensions: ["xlsm"]
      },
      "application/vnd.ms-excel.template.macroenabled.12": {
        source: "iana",
        extensions: ["xltm"]
      },
      "application/vnd.ms-fontobject": {
        source: "iana",
        compressible: true,
        extensions: ["eot"]
      },
      "application/vnd.ms-htmlhelp": {
        source: "iana",
        extensions: ["chm"]
      },
      "application/vnd.ms-ims": {
        source: "iana",
        extensions: ["ims"]
      },
      "application/vnd.ms-lrm": {
        source: "iana",
        extensions: ["lrm"]
      },
      "application/vnd.ms-office.activex+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ms-officetheme": {
        source: "iana",
        extensions: ["thmx"]
      },
      "application/vnd.ms-opentype": {
        source: "apache",
        compressible: true
      },
      "application/vnd.ms-outlook": {
        compressible: false,
        extensions: ["msg"]
      },
      "application/vnd.ms-package.obfuscated-opentype": {
        source: "apache"
      },
      "application/vnd.ms-pki.seccat": {
        source: "apache",
        extensions: ["cat"]
      },
      "application/vnd.ms-pki.stl": {
        source: "apache",
        extensions: ["stl"]
      },
      "application/vnd.ms-playready.initiator+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ms-powerpoint": {
        source: "iana",
        compressible: false,
        extensions: ["ppt", "pps", "pot"]
      },
      "application/vnd.ms-powerpoint.addin.macroenabled.12": {
        source: "iana",
        extensions: ["ppam"]
      },
      "application/vnd.ms-powerpoint.presentation.macroenabled.12": {
        source: "iana",
        extensions: ["pptm"]
      },
      "application/vnd.ms-powerpoint.slide.macroenabled.12": {
        source: "iana",
        extensions: ["sldm"]
      },
      "application/vnd.ms-powerpoint.slideshow.macroenabled.12": {
        source: "iana",
        extensions: ["ppsm"]
      },
      "application/vnd.ms-powerpoint.template.macroenabled.12": {
        source: "iana",
        extensions: ["potm"]
      },
      "application/vnd.ms-printdevicecapabilities+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ms-printing.printticket+xml": {
        source: "apache",
        compressible: true
      },
      "application/vnd.ms-printschematicket+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ms-project": {
        source: "iana",
        extensions: ["mpp", "mpt"]
      },
      "application/vnd.ms-tnef": {
        source: "iana"
      },
      "application/vnd.ms-windows.devicepairing": {
        source: "iana"
      },
      "application/vnd.ms-windows.nwprinting.oob": {
        source: "iana"
      },
      "application/vnd.ms-windows.printerpairing": {
        source: "iana"
      },
      "application/vnd.ms-windows.wsd.oob": {
        source: "iana"
      },
      "application/vnd.ms-wmdrm.lic-chlg-req": {
        source: "iana"
      },
      "application/vnd.ms-wmdrm.lic-resp": {
        source: "iana"
      },
      "application/vnd.ms-wmdrm.meter-chlg-req": {
        source: "iana"
      },
      "application/vnd.ms-wmdrm.meter-resp": {
        source: "iana"
      },
      "application/vnd.ms-word.document.macroenabled.12": {
        source: "iana",
        extensions: ["docm"]
      },
      "application/vnd.ms-word.template.macroenabled.12": {
        source: "iana",
        extensions: ["dotm"]
      },
      "application/vnd.ms-works": {
        source: "iana",
        extensions: ["wps", "wks", "wcm", "wdb"]
      },
      "application/vnd.ms-wpl": {
        source: "iana",
        extensions: ["wpl"]
      },
      "application/vnd.ms-xpsdocument": {
        source: "iana",
        compressible: false,
        extensions: ["xps"]
      },
      "application/vnd.msa-disk-image": {
        source: "iana"
      },
      "application/vnd.mseq": {
        source: "iana",
        extensions: ["mseq"]
      },
      "application/vnd.msign": {
        source: "iana"
      },
      "application/vnd.multiad.creator": {
        source: "iana"
      },
      "application/vnd.multiad.creator.cif": {
        source: "iana"
      },
      "application/vnd.music-niff": {
        source: "iana"
      },
      "application/vnd.musician": {
        source: "iana",
        extensions: ["mus"]
      },
      "application/vnd.muvee.style": {
        source: "iana",
        extensions: ["msty"]
      },
      "application/vnd.mynfc": {
        source: "iana",
        extensions: ["taglet"]
      },
      "application/vnd.nacamar.ybrid+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ncd.control": {
        source: "iana"
      },
      "application/vnd.ncd.reference": {
        source: "iana"
      },
      "application/vnd.nearst.inv+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nebumind.line": {
        source: "iana"
      },
      "application/vnd.nervana": {
        source: "iana"
      },
      "application/vnd.netfpx": {
        source: "iana"
      },
      "application/vnd.neurolanguage.nlu": {
        source: "iana",
        extensions: ["nlu"]
      },
      "application/vnd.nimn": {
        source: "iana"
      },
      "application/vnd.nintendo.nitro.rom": {
        source: "iana"
      },
      "application/vnd.nintendo.snes.rom": {
        source: "iana"
      },
      "application/vnd.nitf": {
        source: "iana",
        extensions: ["ntf", "nitf"]
      },
      "application/vnd.noblenet-directory": {
        source: "iana",
        extensions: ["nnd"]
      },
      "application/vnd.noblenet-sealer": {
        source: "iana",
        extensions: ["nns"]
      },
      "application/vnd.noblenet-web": {
        source: "iana",
        extensions: ["nnw"]
      },
      "application/vnd.nokia.catalogs": {
        source: "iana"
      },
      "application/vnd.nokia.conml+wbxml": {
        source: "iana"
      },
      "application/vnd.nokia.conml+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nokia.iptv.config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nokia.isds-radio-presets": {
        source: "iana"
      },
      "application/vnd.nokia.landmark+wbxml": {
        source: "iana"
      },
      "application/vnd.nokia.landmark+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nokia.landmarkcollection+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nokia.n-gage.ac+xml": {
        source: "iana",
        compressible: true,
        extensions: ["ac"]
      },
      "application/vnd.nokia.n-gage.data": {
        source: "iana",
        extensions: ["ngdat"]
      },
      "application/vnd.nokia.n-gage.symbian.install": {
        source: "iana",
        extensions: ["n-gage"]
      },
      "application/vnd.nokia.ncd": {
        source: "iana"
      },
      "application/vnd.nokia.pcd+wbxml": {
        source: "iana"
      },
      "application/vnd.nokia.pcd+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nokia.radio-preset": {
        source: "iana",
        extensions: ["rpst"]
      },
      "application/vnd.nokia.radio-presets": {
        source: "iana",
        extensions: ["rpss"]
      },
      "application/vnd.novadigm.edm": {
        source: "iana",
        extensions: ["edm"]
      },
      "application/vnd.novadigm.edx": {
        source: "iana",
        extensions: ["edx"]
      },
      "application/vnd.novadigm.ext": {
        source: "iana",
        extensions: ["ext"]
      },
      "application/vnd.ntt-local.content-share": {
        source: "iana"
      },
      "application/vnd.ntt-local.file-transfer": {
        source: "iana"
      },
      "application/vnd.ntt-local.ogw_remote-access": {
        source: "iana"
      },
      "application/vnd.ntt-local.sip-ta_remote": {
        source: "iana"
      },
      "application/vnd.ntt-local.sip-ta_tcp_stream": {
        source: "iana"
      },
      "application/vnd.oasis.opendocument.chart": {
        source: "iana",
        extensions: ["odc"]
      },
      "application/vnd.oasis.opendocument.chart-template": {
        source: "iana",
        extensions: ["otc"]
      },
      "application/vnd.oasis.opendocument.database": {
        source: "iana",
        extensions: ["odb"]
      },
      "application/vnd.oasis.opendocument.formula": {
        source: "iana",
        extensions: ["odf"]
      },
      "application/vnd.oasis.opendocument.formula-template": {
        source: "iana",
        extensions: ["odft"]
      },
      "application/vnd.oasis.opendocument.graphics": {
        source: "iana",
        compressible: false,
        extensions: ["odg"]
      },
      "application/vnd.oasis.opendocument.graphics-template": {
        source: "iana",
        extensions: ["otg"]
      },
      "application/vnd.oasis.opendocument.image": {
        source: "iana",
        extensions: ["odi"]
      },
      "application/vnd.oasis.opendocument.image-template": {
        source: "iana",
        extensions: ["oti"]
      },
      "application/vnd.oasis.opendocument.presentation": {
        source: "iana",
        compressible: false,
        extensions: ["odp"]
      },
      "application/vnd.oasis.opendocument.presentation-template": {
        source: "iana",
        extensions: ["otp"]
      },
      "application/vnd.oasis.opendocument.spreadsheet": {
        source: "iana",
        compressible: false,
        extensions: ["ods"]
      },
      "application/vnd.oasis.opendocument.spreadsheet-template": {
        source: "iana",
        extensions: ["ots"]
      },
      "application/vnd.oasis.opendocument.text": {
        source: "iana",
        compressible: false,
        extensions: ["odt"]
      },
      "application/vnd.oasis.opendocument.text-master": {
        source: "iana",
        extensions: ["odm"]
      },
      "application/vnd.oasis.opendocument.text-template": {
        source: "iana",
        extensions: ["ott"]
      },
      "application/vnd.oasis.opendocument.text-web": {
        source: "iana",
        extensions: ["oth"]
      },
      "application/vnd.obn": {
        source: "iana"
      },
      "application/vnd.ocf+cbor": {
        source: "iana"
      },
      "application/vnd.oci.image.manifest.v1+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oftn.l10n+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.contentaccessdownload+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.contentaccessstreaming+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.cspg-hexbinary": {
        source: "iana"
      },
      "application/vnd.oipf.dae.svg+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.dae.xhtml+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.mippvcontrolmessage+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.pae.gem": {
        source: "iana"
      },
      "application/vnd.oipf.spdiscovery+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.spdlist+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.ueprofile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.userprofile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.olpc-sugar": {
        source: "iana",
        extensions: ["xo"]
      },
      "application/vnd.oma-scws-config": {
        source: "iana"
      },
      "application/vnd.oma-scws-http-request": {
        source: "iana"
      },
      "application/vnd.oma-scws-http-response": {
        source: "iana"
      },
      "application/vnd.oma.bcast.associated-procedure-parameter+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.drm-trigger+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.imd+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.ltkm": {
        source: "iana"
      },
      "application/vnd.oma.bcast.notification+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.provisioningtrigger": {
        source: "iana"
      },
      "application/vnd.oma.bcast.sgboot": {
        source: "iana"
      },
      "application/vnd.oma.bcast.sgdd+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.sgdu": {
        source: "iana"
      },
      "application/vnd.oma.bcast.simple-symbol-container": {
        source: "iana"
      },
      "application/vnd.oma.bcast.smartcard-trigger+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.sprov+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.stkm": {
        source: "iana"
      },
      "application/vnd.oma.cab-address-book+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.cab-feature-handler+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.cab-pcc+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.cab-subs-invite+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.cab-user-prefs+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.dcd": {
        source: "iana"
      },
      "application/vnd.oma.dcdc": {
        source: "iana"
      },
      "application/vnd.oma.dd2+xml": {
        source: "iana",
        compressible: true,
        extensions: ["dd2"]
      },
      "application/vnd.oma.drm.risd+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.group-usage-list+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.lwm2m+cbor": {
        source: "iana"
      },
      "application/vnd.oma.lwm2m+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.lwm2m+tlv": {
        source: "iana"
      },
      "application/vnd.oma.pal+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.poc.detailed-progress-report+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.poc.final-report+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.poc.groups+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.poc.invocation-descriptor+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.poc.optimized-progress-report+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.push": {
        source: "iana"
      },
      "application/vnd.oma.scidm.messages+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.xcap-directory+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.omads-email+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/vnd.omads-file+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/vnd.omads-folder+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/vnd.omaloc-supl-init": {
        source: "iana"
      },
      "application/vnd.onepager": {
        source: "iana"
      },
      "application/vnd.onepagertamp": {
        source: "iana"
      },
      "application/vnd.onepagertamx": {
        source: "iana"
      },
      "application/vnd.onepagertat": {
        source: "iana"
      },
      "application/vnd.onepagertatp": {
        source: "iana"
      },
      "application/vnd.onepagertatx": {
        source: "iana"
      },
      "application/vnd.openblox.game+xml": {
        source: "iana",
        compressible: true,
        extensions: ["obgx"]
      },
      "application/vnd.openblox.game-binary": {
        source: "iana"
      },
      "application/vnd.openeye.oeb": {
        source: "iana"
      },
      "application/vnd.openofficeorg.extension": {
        source: "apache",
        extensions: ["oxt"]
      },
      "application/vnd.openstreetmap.data+xml": {
        source: "iana",
        compressible: true,
        extensions: ["osm"]
      },
      "application/vnd.opentimestamps.ots": {
        source: "iana"
      },
      "application/vnd.openxmlformats-officedocument.custom-properties+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawing+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.extended-properties+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.presentation": {
        source: "iana",
        compressible: false,
        extensions: ["pptx"]
      },
      "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slide": {
        source: "iana",
        extensions: ["sldx"]
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slideshow": {
        source: "iana",
        extensions: ["ppsx"]
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.template": {
        source: "iana",
        extensions: ["potx"]
      },
      "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
        source: "iana",
        compressible: false,
        extensions: ["xlsx"]
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.template": {
        source: "iana",
        extensions: ["xltx"]
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.theme+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.themeoverride+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.vmldrawing": {
        source: "iana"
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document": {
        source: "iana",
        compressible: false,
        extensions: ["docx"]
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.template": {
        source: "iana",
        extensions: ["dotx"]
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-package.core-properties+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-package.relationships+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oracle.resource+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.orange.indata": {
        source: "iana"
      },
      "application/vnd.osa.netdeploy": {
        source: "iana"
      },
      "application/vnd.osgeo.mapguide.package": {
        source: "iana",
        extensions: ["mgp"]
      },
      "application/vnd.osgi.bundle": {
        source: "iana"
      },
      "application/vnd.osgi.dp": {
        source: "iana",
        extensions: ["dp"]
      },
      "application/vnd.osgi.subsystem": {
        source: "iana",
        extensions: ["esa"]
      },
      "application/vnd.otps.ct-kip+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oxli.countgraph": {
        source: "iana"
      },
      "application/vnd.pagerduty+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.palm": {
        source: "iana",
        extensions: ["pdb", "pqa", "oprc"]
      },
      "application/vnd.panoply": {
        source: "iana"
      },
      "application/vnd.paos.xml": {
        source: "iana"
      },
      "application/vnd.patentdive": {
        source: "iana"
      },
      "application/vnd.patientecommsdoc": {
        source: "iana"
      },
      "application/vnd.pawaafile": {
        source: "iana",
        extensions: ["paw"]
      },
      "application/vnd.pcos": {
        source: "iana"
      },
      "application/vnd.pg.format": {
        source: "iana",
        extensions: ["str"]
      },
      "application/vnd.pg.osasli": {
        source: "iana",
        extensions: ["ei6"]
      },
      "application/vnd.piaccess.application-licence": {
        source: "iana"
      },
      "application/vnd.picsel": {
        source: "iana",
        extensions: ["efif"]
      },
      "application/vnd.pmi.widget": {
        source: "iana",
        extensions: ["wg"]
      },
      "application/vnd.poc.group-advertisement+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.pocketlearn": {
        source: "iana",
        extensions: ["plf"]
      },
      "application/vnd.powerbuilder6": {
        source: "iana",
        extensions: ["pbd"]
      },
      "application/vnd.powerbuilder6-s": {
        source: "iana"
      },
      "application/vnd.powerbuilder7": {
        source: "iana"
      },
      "application/vnd.powerbuilder7-s": {
        source: "iana"
      },
      "application/vnd.powerbuilder75": {
        source: "iana"
      },
      "application/vnd.powerbuilder75-s": {
        source: "iana"
      },
      "application/vnd.preminet": {
        source: "iana"
      },
      "application/vnd.previewsystems.box": {
        source: "iana",
        extensions: ["box"]
      },
      "application/vnd.proteus.magazine": {
        source: "iana",
        extensions: ["mgz"]
      },
      "application/vnd.psfs": {
        source: "iana"
      },
      "application/vnd.publishare-delta-tree": {
        source: "iana",
        extensions: ["qps"]
      },
      "application/vnd.pvi.ptid1": {
        source: "iana",
        extensions: ["ptid"]
      },
      "application/vnd.pwg-multiplexed": {
        source: "iana"
      },
      "application/vnd.pwg-xhtml-print+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.qualcomm.brew-app-res": {
        source: "iana"
      },
      "application/vnd.quarantainenet": {
        source: "iana"
      },
      "application/vnd.quark.quarkxpress": {
        source: "iana",
        extensions: ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"]
      },
      "application/vnd.quobject-quoxdocument": {
        source: "iana"
      },
      "application/vnd.radisys.moml+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-audit+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-audit-conf+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-audit-conn+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-audit-dialog+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-audit-stream+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-conf+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog-base+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog-fax-detect+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog-group+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog-speech+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog-transform+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.rainstor.data": {
        source: "iana"
      },
      "application/vnd.rapid": {
        source: "iana"
      },
      "application/vnd.rar": {
        source: "iana",
        extensions: ["rar"]
      },
      "application/vnd.realvnc.bed": {
        source: "iana",
        extensions: ["bed"]
      },
      "application/vnd.recordare.musicxml": {
        source: "iana",
        extensions: ["mxl"]
      },
      "application/vnd.recordare.musicxml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["musicxml"]
      },
      "application/vnd.renlearn.rlprint": {
        source: "iana"
      },
      "application/vnd.resilient.logic": {
        source: "iana"
      },
      "application/vnd.restful+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.rig.cryptonote": {
        source: "iana",
        extensions: ["cryptonote"]
      },
      "application/vnd.rim.cod": {
        source: "apache",
        extensions: ["cod"]
      },
      "application/vnd.rn-realmedia": {
        source: "apache",
        extensions: ["rm"]
      },
      "application/vnd.rn-realmedia-vbr": {
        source: "apache",
        extensions: ["rmvb"]
      },
      "application/vnd.route66.link66+xml": {
        source: "iana",
        compressible: true,
        extensions: ["link66"]
      },
      "application/vnd.rs-274x": {
        source: "iana"
      },
      "application/vnd.ruckus.download": {
        source: "iana"
      },
      "application/vnd.s3sms": {
        source: "iana"
      },
      "application/vnd.sailingtracker.track": {
        source: "iana",
        extensions: ["st"]
      },
      "application/vnd.sar": {
        source: "iana"
      },
      "application/vnd.sbm.cid": {
        source: "iana"
      },
      "application/vnd.sbm.mid2": {
        source: "iana"
      },
      "application/vnd.scribus": {
        source: "iana"
      },
      "application/vnd.sealed.3df": {
        source: "iana"
      },
      "application/vnd.sealed.csf": {
        source: "iana"
      },
      "application/vnd.sealed.doc": {
        source: "iana"
      },
      "application/vnd.sealed.eml": {
        source: "iana"
      },
      "application/vnd.sealed.mht": {
        source: "iana"
      },
      "application/vnd.sealed.net": {
        source: "iana"
      },
      "application/vnd.sealed.ppt": {
        source: "iana"
      },
      "application/vnd.sealed.tiff": {
        source: "iana"
      },
      "application/vnd.sealed.xls": {
        source: "iana"
      },
      "application/vnd.sealedmedia.softseal.html": {
        source: "iana"
      },
      "application/vnd.sealedmedia.softseal.pdf": {
        source: "iana"
      },
      "application/vnd.seemail": {
        source: "iana",
        extensions: ["see"]
      },
      "application/vnd.seis+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.sema": {
        source: "iana",
        extensions: ["sema"]
      },
      "application/vnd.semd": {
        source: "iana",
        extensions: ["semd"]
      },
      "application/vnd.semf": {
        source: "iana",
        extensions: ["semf"]
      },
      "application/vnd.shade-save-file": {
        source: "iana"
      },
      "application/vnd.shana.informed.formdata": {
        source: "iana",
        extensions: ["ifm"]
      },
      "application/vnd.shana.informed.formtemplate": {
        source: "iana",
        extensions: ["itp"]
      },
      "application/vnd.shana.informed.interchange": {
        source: "iana",
        extensions: ["iif"]
      },
      "application/vnd.shana.informed.package": {
        source: "iana",
        extensions: ["ipk"]
      },
      "application/vnd.shootproof+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.shopkick+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.shp": {
        source: "iana"
      },
      "application/vnd.shx": {
        source: "iana"
      },
      "application/vnd.sigrok.session": {
        source: "iana"
      },
      "application/vnd.simtech-mindmapper": {
        source: "iana",
        extensions: ["twd", "twds"]
      },
      "application/vnd.siren+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.smaf": {
        source: "iana",
        extensions: ["mmf"]
      },
      "application/vnd.smart.notebook": {
        source: "iana"
      },
      "application/vnd.smart.teacher": {
        source: "iana",
        extensions: ["teacher"]
      },
      "application/vnd.snesdev-page-table": {
        source: "iana"
      },
      "application/vnd.software602.filler.form+xml": {
        source: "iana",
        compressible: true,
        extensions: ["fo"]
      },
      "application/vnd.software602.filler.form-xml-zip": {
        source: "iana"
      },
      "application/vnd.solent.sdkm+xml": {
        source: "iana",
        compressible: true,
        extensions: ["sdkm", "sdkd"]
      },
      "application/vnd.spotfire.dxp": {
        source: "iana",
        extensions: ["dxp"]
      },
      "application/vnd.spotfire.sfs": {
        source: "iana",
        extensions: ["sfs"]
      },
      "application/vnd.sqlite3": {
        source: "iana"
      },
      "application/vnd.sss-cod": {
        source: "iana"
      },
      "application/vnd.sss-dtf": {
        source: "iana"
      },
      "application/vnd.sss-ntf": {
        source: "iana"
      },
      "application/vnd.stardivision.calc": {
        source: "apache",
        extensions: ["sdc"]
      },
      "application/vnd.stardivision.draw": {
        source: "apache",
        extensions: ["sda"]
      },
      "application/vnd.stardivision.impress": {
        source: "apache",
        extensions: ["sdd"]
      },
      "application/vnd.stardivision.math": {
        source: "apache",
        extensions: ["smf"]
      },
      "application/vnd.stardivision.writer": {
        source: "apache",
        extensions: ["sdw", "vor"]
      },
      "application/vnd.stardivision.writer-global": {
        source: "apache",
        extensions: ["sgl"]
      },
      "application/vnd.stepmania.package": {
        source: "iana",
        extensions: ["smzip"]
      },
      "application/vnd.stepmania.stepchart": {
        source: "iana",
        extensions: ["sm"]
      },
      "application/vnd.street-stream": {
        source: "iana"
      },
      "application/vnd.sun.wadl+xml": {
        source: "iana",
        compressible: true,
        extensions: ["wadl"]
      },
      "application/vnd.sun.xml.calc": {
        source: "apache",
        extensions: ["sxc"]
      },
      "application/vnd.sun.xml.calc.template": {
        source: "apache",
        extensions: ["stc"]
      },
      "application/vnd.sun.xml.draw": {
        source: "apache",
        extensions: ["sxd"]
      },
      "application/vnd.sun.xml.draw.template": {
        source: "apache",
        extensions: ["std"]
      },
      "application/vnd.sun.xml.impress": {
        source: "apache",
        extensions: ["sxi"]
      },
      "application/vnd.sun.xml.impress.template": {
        source: "apache",
        extensions: ["sti"]
      },
      "application/vnd.sun.xml.math": {
        source: "apache",
        extensions: ["sxm"]
      },
      "application/vnd.sun.xml.writer": {
        source: "apache",
        extensions: ["sxw"]
      },
      "application/vnd.sun.xml.writer.global": {
        source: "apache",
        extensions: ["sxg"]
      },
      "application/vnd.sun.xml.writer.template": {
        source: "apache",
        extensions: ["stw"]
      },
      "application/vnd.sus-calendar": {
        source: "iana",
        extensions: ["sus", "susp"]
      },
      "application/vnd.svd": {
        source: "iana",
        extensions: ["svd"]
      },
      "application/vnd.swiftview-ics": {
        source: "iana"
      },
      "application/vnd.sycle+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.syft+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.symbian.install": {
        source: "apache",
        extensions: ["sis", "sisx"]
      },
      "application/vnd.syncml+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["xsm"]
      },
      "application/vnd.syncml.dm+wbxml": {
        source: "iana",
        charset: "UTF-8",
        extensions: ["bdm"]
      },
      "application/vnd.syncml.dm+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["xdm"]
      },
      "application/vnd.syncml.dm.notification": {
        source: "iana"
      },
      "application/vnd.syncml.dmddf+wbxml": {
        source: "iana"
      },
      "application/vnd.syncml.dmddf+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["ddf"]
      },
      "application/vnd.syncml.dmtnds+wbxml": {
        source: "iana"
      },
      "application/vnd.syncml.dmtnds+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/vnd.syncml.ds.notification": {
        source: "iana"
      },
      "application/vnd.tableschema+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.tao.intent-module-archive": {
        source: "iana",
        extensions: ["tao"]
      },
      "application/vnd.tcpdump.pcap": {
        source: "iana",
        extensions: ["pcap", "cap", "dmp"]
      },
      "application/vnd.think-cell.ppttc+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.tmd.mediaflex.api+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.tml": {
        source: "iana"
      },
      "application/vnd.tmobile-livetv": {
        source: "iana",
        extensions: ["tmo"]
      },
      "application/vnd.tri.onesource": {
        source: "iana"
      },
      "application/vnd.trid.tpt": {
        source: "iana",
        extensions: ["tpt"]
      },
      "application/vnd.triscape.mxs": {
        source: "iana",
        extensions: ["mxs"]
      },
      "application/vnd.trueapp": {
        source: "iana",
        extensions: ["tra"]
      },
      "application/vnd.truedoc": {
        source: "iana"
      },
      "application/vnd.ubisoft.webplayer": {
        source: "iana"
      },
      "application/vnd.ufdl": {
        source: "iana",
        extensions: ["ufd", "ufdl"]
      },
      "application/vnd.uiq.theme": {
        source: "iana",
        extensions: ["utz"]
      },
      "application/vnd.umajin": {
        source: "iana",
        extensions: ["umj"]
      },
      "application/vnd.unity": {
        source: "iana",
        extensions: ["unityweb"]
      },
      "application/vnd.uoml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["uoml"]
      },
      "application/vnd.uplanet.alert": {
        source: "iana"
      },
      "application/vnd.uplanet.alert-wbxml": {
        source: "iana"
      },
      "application/vnd.uplanet.bearer-choice": {
        source: "iana"
      },
      "application/vnd.uplanet.bearer-choice-wbxml": {
        source: "iana"
      },
      "application/vnd.uplanet.cacheop": {
        source: "iana"
      },
      "application/vnd.uplanet.cacheop-wbxml": {
        source: "iana"
      },
      "application/vnd.uplanet.channel": {
        source: "iana"
      },
      "application/vnd.uplanet.channel-wbxml": {
        source: "iana"
      },
      "application/vnd.uplanet.list": {
        source: "iana"
      },
      "application/vnd.uplanet.list-wbxml": {
        source: "iana"
      },
      "application/vnd.uplanet.listcmd": {
        source: "iana"
      },
      "application/vnd.uplanet.listcmd-wbxml": {
        source: "iana"
      },
      "application/vnd.uplanet.signal": {
        source: "iana"
      },
      "application/vnd.uri-map": {
        source: "iana"
      },
      "application/vnd.valve.source.material": {
        source: "iana"
      },
      "application/vnd.vcx": {
        source: "iana",
        extensions: ["vcx"]
      },
      "application/vnd.vd-study": {
        source: "iana"
      },
      "application/vnd.vectorworks": {
        source: "iana"
      },
      "application/vnd.vel+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.verimatrix.vcas": {
        source: "iana"
      },
      "application/vnd.veritone.aion+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.veryant.thin": {
        source: "iana"
      },
      "application/vnd.ves.encrypted": {
        source: "iana"
      },
      "application/vnd.vidsoft.vidconference": {
        source: "iana"
      },
      "application/vnd.visio": {
        source: "iana",
        extensions: ["vsd", "vst", "vss", "vsw"]
      },
      "application/vnd.visionary": {
        source: "iana",
        extensions: ["vis"]
      },
      "application/vnd.vividence.scriptfile": {
        source: "iana"
      },
      "application/vnd.vsf": {
        source: "iana",
        extensions: ["vsf"]
      },
      "application/vnd.wap.sic": {
        source: "iana"
      },
      "application/vnd.wap.slc": {
        source: "iana"
      },
      "application/vnd.wap.wbxml": {
        source: "iana",
        charset: "UTF-8",
        extensions: ["wbxml"]
      },
      "application/vnd.wap.wmlc": {
        source: "iana",
        extensions: ["wmlc"]
      },
      "application/vnd.wap.wmlscriptc": {
        source: "iana",
        extensions: ["wmlsc"]
      },
      "application/vnd.webturbo": {
        source: "iana",
        extensions: ["wtb"]
      },
      "application/vnd.wfa.dpp": {
        source: "iana"
      },
      "application/vnd.wfa.p2p": {
        source: "iana"
      },
      "application/vnd.wfa.wsc": {
        source: "iana"
      },
      "application/vnd.windows.devicepairing": {
        source: "iana"
      },
      "application/vnd.wmc": {
        source: "iana"
      },
      "application/vnd.wmf.bootstrap": {
        source: "iana"
      },
      "application/vnd.wolfram.mathematica": {
        source: "iana"
      },
      "application/vnd.wolfram.mathematica.package": {
        source: "iana"
      },
      "application/vnd.wolfram.player": {
        source: "iana",
        extensions: ["nbp"]
      },
      "application/vnd.wordperfect": {
        source: "iana",
        extensions: ["wpd"]
      },
      "application/vnd.wqd": {
        source: "iana",
        extensions: ["wqd"]
      },
      "application/vnd.wrq-hp3000-labelled": {
        source: "iana"
      },
      "application/vnd.wt.stf": {
        source: "iana",
        extensions: ["stf"]
      },
      "application/vnd.wv.csp+wbxml": {
        source: "iana"
      },
      "application/vnd.wv.csp+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.wv.ssp+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.xacml+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.xara": {
        source: "iana",
        extensions: ["xar"]
      },
      "application/vnd.xfdl": {
        source: "iana",
        extensions: ["xfdl"]
      },
      "application/vnd.xfdl.webform": {
        source: "iana"
      },
      "application/vnd.xmi+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.xmpie.cpkg": {
        source: "iana"
      },
      "application/vnd.xmpie.dpkg": {
        source: "iana"
      },
      "application/vnd.xmpie.plan": {
        source: "iana"
      },
      "application/vnd.xmpie.ppkg": {
        source: "iana"
      },
      "application/vnd.xmpie.xlim": {
        source: "iana"
      },
      "application/vnd.yamaha.hv-dic": {
        source: "iana",
        extensions: ["hvd"]
      },
      "application/vnd.yamaha.hv-script": {
        source: "iana",
        extensions: ["hvs"]
      },
      "application/vnd.yamaha.hv-voice": {
        source: "iana",
        extensions: ["hvp"]
      },
      "application/vnd.yamaha.openscoreformat": {
        source: "iana",
        extensions: ["osf"]
      },
      "application/vnd.yamaha.openscoreformat.osfpvg+xml": {
        source: "iana",
        compressible: true,
        extensions: ["osfpvg"]
      },
      "application/vnd.yamaha.remote-setup": {
        source: "iana"
      },
      "application/vnd.yamaha.smaf-audio": {
        source: "iana",
        extensions: ["saf"]
      },
      "application/vnd.yamaha.smaf-phrase": {
        source: "iana",
        extensions: ["spf"]
      },
      "application/vnd.yamaha.through-ngn": {
        source: "iana"
      },
      "application/vnd.yamaha.tunnel-udpencap": {
        source: "iana"
      },
      "application/vnd.yaoweme": {
        source: "iana"
      },
      "application/vnd.yellowriver-custom-menu": {
        source: "iana",
        extensions: ["cmp"]
      },
      "application/vnd.youtube.yt": {
        source: "iana"
      },
      "application/vnd.zul": {
        source: "iana",
        extensions: ["zir", "zirz"]
      },
      "application/vnd.zzazz.deck+xml": {
        source: "iana",
        compressible: true,
        extensions: ["zaz"]
      },
      "application/voicexml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["vxml"]
      },
      "application/voucher-cms+json": {
        source: "iana",
        compressible: true
      },
      "application/vq-rtcpxr": {
        source: "iana"
      },
      "application/wasm": {
        source: "iana",
        compressible: true,
        extensions: ["wasm"]
      },
      "application/watcherinfo+xml": {
        source: "iana",
        compressible: true,
        extensions: ["wif"]
      },
      "application/webpush-options+json": {
        source: "iana",
        compressible: true
      },
      "application/whoispp-query": {
        source: "iana"
      },
      "application/whoispp-response": {
        source: "iana"
      },
      "application/widget": {
        source: "iana",
        extensions: ["wgt"]
      },
      "application/winhlp": {
        source: "apache",
        extensions: ["hlp"]
      },
      "application/wita": {
        source: "iana"
      },
      "application/wordperfect5.1": {
        source: "iana"
      },
      "application/wsdl+xml": {
        source: "iana",
        compressible: true,
        extensions: ["wsdl"]
      },
      "application/wspolicy+xml": {
        source: "iana",
        compressible: true,
        extensions: ["wspolicy"]
      },
      "application/x-7z-compressed": {
        source: "apache",
        compressible: false,
        extensions: ["7z"]
      },
      "application/x-abiword": {
        source: "apache",
        extensions: ["abw"]
      },
      "application/x-ace-compressed": {
        source: "apache",
        extensions: ["ace"]
      },
      "application/x-amf": {
        source: "apache"
      },
      "application/x-apple-diskimage": {
        source: "apache",
        extensions: ["dmg"]
      },
      "application/x-arj": {
        compressible: false,
        extensions: ["arj"]
      },
      "application/x-authorware-bin": {
        source: "apache",
        extensions: ["aab", "x32", "u32", "vox"]
      },
      "application/x-authorware-map": {
        source: "apache",
        extensions: ["aam"]
      },
      "application/x-authorware-seg": {
        source: "apache",
        extensions: ["aas"]
      },
      "application/x-bcpio": {
        source: "apache",
        extensions: ["bcpio"]
      },
      "application/x-bdoc": {
        compressible: false,
        extensions: ["bdoc"]
      },
      "application/x-bittorrent": {
        source: "apache",
        extensions: ["torrent"]
      },
      "application/x-blorb": {
        source: "apache",
        extensions: ["blb", "blorb"]
      },
      "application/x-bzip": {
        source: "apache",
        compressible: false,
        extensions: ["bz"]
      },
      "application/x-bzip2": {
        source: "apache",
        compressible: false,
        extensions: ["bz2", "boz"]
      },
      "application/x-cbr": {
        source: "apache",
        extensions: ["cbr", "cba", "cbt", "cbz", "cb7"]
      },
      "application/x-cdlink": {
        source: "apache",
        extensions: ["vcd"]
      },
      "application/x-cfs-compressed": {
        source: "apache",
        extensions: ["cfs"]
      },
      "application/x-chat": {
        source: "apache",
        extensions: ["chat"]
      },
      "application/x-chess-pgn": {
        source: "apache",
        extensions: ["pgn"]
      },
      "application/x-chrome-extension": {
        extensions: ["crx"]
      },
      "application/x-cocoa": {
        source: "nginx",
        extensions: ["cco"]
      },
      "application/x-compress": {
        source: "apache"
      },
      "application/x-conference": {
        source: "apache",
        extensions: ["nsc"]
      },
      "application/x-cpio": {
        source: "apache",
        extensions: ["cpio"]
      },
      "application/x-csh": {
        source: "apache",
        extensions: ["csh"]
      },
      "application/x-deb": {
        compressible: false
      },
      "application/x-debian-package": {
        source: "apache",
        extensions: ["deb", "udeb"]
      },
      "application/x-dgc-compressed": {
        source: "apache",
        extensions: ["dgc"]
      },
      "application/x-director": {
        source: "apache",
        extensions: ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"]
      },
      "application/x-doom": {
        source: "apache",
        extensions: ["wad"]
      },
      "application/x-dtbncx+xml": {
        source: "apache",
        compressible: true,
        extensions: ["ncx"]
      },
      "application/x-dtbook+xml": {
        source: "apache",
        compressible: true,
        extensions: ["dtb"]
      },
      "application/x-dtbresource+xml": {
        source: "apache",
        compressible: true,
        extensions: ["res"]
      },
      "application/x-dvi": {
        source: "apache",
        compressible: false,
        extensions: ["dvi"]
      },
      "application/x-envoy": {
        source: "apache",
        extensions: ["evy"]
      },
      "application/x-eva": {
        source: "apache",
        extensions: ["eva"]
      },
      "application/x-font-bdf": {
        source: "apache",
        extensions: ["bdf"]
      },
      "application/x-font-dos": {
        source: "apache"
      },
      "application/x-font-framemaker": {
        source: "apache"
      },
      "application/x-font-ghostscript": {
        source: "apache",
        extensions: ["gsf"]
      },
      "application/x-font-libgrx": {
        source: "apache"
      },
      "application/x-font-linux-psf": {
        source: "apache",
        extensions: ["psf"]
      },
      "application/x-font-pcf": {
        source: "apache",
        extensions: ["pcf"]
      },
      "application/x-font-snf": {
        source: "apache",
        extensions: ["snf"]
      },
      "application/x-font-speedo": {
        source: "apache"
      },
      "application/x-font-sunos-news": {
        source: "apache"
      },
      "application/x-font-type1": {
        source: "apache",
        extensions: ["pfa", "pfb", "pfm", "afm"]
      },
      "application/x-font-vfont": {
        source: "apache"
      },
      "application/x-freearc": {
        source: "apache",
        extensions: ["arc"]
      },
      "application/x-futuresplash": {
        source: "apache",
        extensions: ["spl"]
      },
      "application/x-gca-compressed": {
        source: "apache",
        extensions: ["gca"]
      },
      "application/x-glulx": {
        source: "apache",
        extensions: ["ulx"]
      },
      "application/x-gnumeric": {
        source: "apache",
        extensions: ["gnumeric"]
      },
      "application/x-gramps-xml": {
        source: "apache",
        extensions: ["gramps"]
      },
      "application/x-gtar": {
        source: "apache",
        extensions: ["gtar"]
      },
      "application/x-gzip": {
        source: "apache"
      },
      "application/x-hdf": {
        source: "apache",
        extensions: ["hdf"]
      },
      "application/x-httpd-php": {
        compressible: true,
        extensions: ["php"]
      },
      "application/x-install-instructions": {
        source: "apache",
        extensions: ["install"]
      },
      "application/x-iso9660-image": {
        source: "apache",
        extensions: ["iso"]
      },
      "application/x-iwork-keynote-sffkey": {
        extensions: ["key"]
      },
      "application/x-iwork-numbers-sffnumbers": {
        extensions: ["numbers"]
      },
      "application/x-iwork-pages-sffpages": {
        extensions: ["pages"]
      },
      "application/x-java-archive-diff": {
        source: "nginx",
        extensions: ["jardiff"]
      },
      "application/x-java-jnlp-file": {
        source: "apache",
        compressible: false,
        extensions: ["jnlp"]
      },
      "application/x-javascript": {
        compressible: true
      },
      "application/x-keepass2": {
        extensions: ["kdbx"]
      },
      "application/x-latex": {
        source: "apache",
        compressible: false,
        extensions: ["latex"]
      },
      "application/x-lua-bytecode": {
        extensions: ["luac"]
      },
      "application/x-lzh-compressed": {
        source: "apache",
        extensions: ["lzh", "lha"]
      },
      "application/x-makeself": {
        source: "nginx",
        extensions: ["run"]
      },
      "application/x-mie": {
        source: "apache",
        extensions: ["mie"]
      },
      "application/x-mobipocket-ebook": {
        source: "apache",
        extensions: ["prc", "mobi"]
      },
      "application/x-mpegurl": {
        compressible: false
      },
      "application/x-ms-application": {
        source: "apache",
        extensions: ["application"]
      },
      "application/x-ms-shortcut": {
        source: "apache",
        extensions: ["lnk"]
      },
      "application/x-ms-wmd": {
        source: "apache",
        extensions: ["wmd"]
      },
      "application/x-ms-wmz": {
        source: "apache",
        extensions: ["wmz"]
      },
      "application/x-ms-xbap": {
        source: "apache",
        extensions: ["xbap"]
      },
      "application/x-msaccess": {
        source: "apache",
        extensions: ["mdb"]
      },
      "application/x-msbinder": {
        source: "apache",
        extensions: ["obd"]
      },
      "application/x-mscardfile": {
        source: "apache",
        extensions: ["crd"]
      },
      "application/x-msclip": {
        source: "apache",
        extensions: ["clp"]
      },
      "application/x-msdos-program": {
        extensions: ["exe"]
      },
      "application/x-msdownload": {
        source: "apache",
        extensions: ["exe", "dll", "com", "bat", "msi"]
      },
      "application/x-msmediaview": {
        source: "apache",
        extensions: ["mvb", "m13", "m14"]
      },
      "application/x-msmetafile": {
        source: "apache",
        extensions: ["wmf", "wmz", "emf", "emz"]
      },
      "application/x-msmoney": {
        source: "apache",
        extensions: ["mny"]
      },
      "application/x-mspublisher": {
        source: "apache",
        extensions: ["pub"]
      },
      "application/x-msschedule": {
        source: "apache",
        extensions: ["scd"]
      },
      "application/x-msterminal": {
        source: "apache",
        extensions: ["trm"]
      },
      "application/x-mswrite": {
        source: "apache",
        extensions: ["wri"]
      },
      "application/x-netcdf": {
        source: "apache",
        extensions: ["nc", "cdf"]
      },
      "application/x-ns-proxy-autoconfig": {
        compressible: true,
        extensions: ["pac"]
      },
      "application/x-nzb": {
        source: "apache",
        extensions: ["nzb"]
      },
      "application/x-perl": {
        source: "nginx",
        extensions: ["pl", "pm"]
      },
      "application/x-pilot": {
        source: "nginx",
        extensions: ["prc", "pdb"]
      },
      "application/x-pkcs12": {
        source: "apache",
        compressible: false,
        extensions: ["p12", "pfx"]
      },
      "application/x-pkcs7-certificates": {
        source: "apache",
        extensions: ["p7b", "spc"]
      },
      "application/x-pkcs7-certreqresp": {
        source: "apache",
        extensions: ["p7r"]
      },
      "application/x-pki-message": {
        source: "iana"
      },
      "application/x-rar-compressed": {
        source: "apache",
        compressible: false,
        extensions: ["rar"]
      },
      "application/x-redhat-package-manager": {
        source: "nginx",
        extensions: ["rpm"]
      },
      "application/x-research-info-systems": {
        source: "apache",
        extensions: ["ris"]
      },
      "application/x-sea": {
        source: "nginx",
        extensions: ["sea"]
      },
      "application/x-sh": {
        source: "apache",
        compressible: true,
        extensions: ["sh"]
      },
      "application/x-shar": {
        source: "apache",
        extensions: ["shar"]
      },
      "application/x-shockwave-flash": {
        source: "apache",
        compressible: false,
        extensions: ["swf"]
      },
      "application/x-silverlight-app": {
        source: "apache",
        extensions: ["xap"]
      },
      "application/x-sql": {
        source: "apache",
        extensions: ["sql"]
      },
      "application/x-stuffit": {
        source: "apache",
        compressible: false,
        extensions: ["sit"]
      },
      "application/x-stuffitx": {
        source: "apache",
        extensions: ["sitx"]
      },
      "application/x-subrip": {
        source: "apache",
        extensions: ["srt"]
      },
      "application/x-sv4cpio": {
        source: "apache",
        extensions: ["sv4cpio"]
      },
      "application/x-sv4crc": {
        source: "apache",
        extensions: ["sv4crc"]
      },
      "application/x-t3vm-image": {
        source: "apache",
        extensions: ["t3"]
      },
      "application/x-tads": {
        source: "apache",
        extensions: ["gam"]
      },
      "application/x-tar": {
        source: "apache",
        compressible: true,
        extensions: ["tar"]
      },
      "application/x-tcl": {
        source: "apache",
        extensions: ["tcl", "tk"]
      },
      "application/x-tex": {
        source: "apache",
        extensions: ["tex"]
      },
      "application/x-tex-tfm": {
        source: "apache",
        extensions: ["tfm"]
      },
      "application/x-texinfo": {
        source: "apache",
        extensions: ["texinfo", "texi"]
      },
      "application/x-tgif": {
        source: "apache",
        extensions: ["obj"]
      },
      "application/x-ustar": {
        source: "apache",
        extensions: ["ustar"]
      },
      "application/x-virtualbox-hdd": {
        compressible: true,
        extensions: ["hdd"]
      },
      "application/x-virtualbox-ova": {
        compressible: true,
        extensions: ["ova"]
      },
      "application/x-virtualbox-ovf": {
        compressible: true,
        extensions: ["ovf"]
      },
      "application/x-virtualbox-vbox": {
        compressible: true,
        extensions: ["vbox"]
      },
      "application/x-virtualbox-vbox-extpack": {
        compressible: false,
        extensions: ["vbox-extpack"]
      },
      "application/x-virtualbox-vdi": {
        compressible: true,
        extensions: ["vdi"]
      },
      "application/x-virtualbox-vhd": {
        compressible: true,
        extensions: ["vhd"]
      },
      "application/x-virtualbox-vmdk": {
        compressible: true,
        extensions: ["vmdk"]
      },
      "application/x-wais-source": {
        source: "apache",
        extensions: ["src"]
      },
      "application/x-web-app-manifest+json": {
        compressible: true,
        extensions: ["webapp"]
      },
      "application/x-www-form-urlencoded": {
        source: "iana",
        compressible: true
      },
      "application/x-x509-ca-cert": {
        source: "iana",
        extensions: ["der", "crt", "pem"]
      },
      "application/x-x509-ca-ra-cert": {
        source: "iana"
      },
      "application/x-x509-next-ca-cert": {
        source: "iana"
      },
      "application/x-xfig": {
        source: "apache",
        extensions: ["fig"]
      },
      "application/x-xliff+xml": {
        source: "apache",
        compressible: true,
        extensions: ["xlf"]
      },
      "application/x-xpinstall": {
        source: "apache",
        compressible: false,
        extensions: ["xpi"]
      },
      "application/x-xz": {
        source: "apache",
        extensions: ["xz"]
      },
      "application/x-zmachine": {
        source: "apache",
        extensions: ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"]
      },
      "application/x400-bp": {
        source: "iana"
      },
      "application/xacml+xml": {
        source: "iana",
        compressible: true
      },
      "application/xaml+xml": {
        source: "apache",
        compressible: true,
        extensions: ["xaml"]
      },
      "application/xcap-att+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xav"]
      },
      "application/xcap-caps+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xca"]
      },
      "application/xcap-diff+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xdf"]
      },
      "application/xcap-el+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xel"]
      },
      "application/xcap-error+xml": {
        source: "iana",
        compressible: true
      },
      "application/xcap-ns+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xns"]
      },
      "application/xcon-conference-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/xcon-conference-info-diff+xml": {
        source: "iana",
        compressible: true
      },
      "application/xenc+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xenc"]
      },
      "application/xhtml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xhtml", "xht"]
      },
      "application/xhtml-voice+xml": {
        source: "apache",
        compressible: true
      },
      "application/xliff+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xlf"]
      },
      "application/xml": {
        source: "iana",
        compressible: true,
        extensions: ["xml", "xsl", "xsd", "rng"]
      },
      "application/xml-dtd": {
        source: "iana",
        compressible: true,
        extensions: ["dtd"]
      },
      "application/xml-external-parsed-entity": {
        source: "iana"
      },
      "application/xml-patch+xml": {
        source: "iana",
        compressible: true
      },
      "application/xmpp+xml": {
        source: "iana",
        compressible: true
      },
      "application/xop+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xop"]
      },
      "application/xproc+xml": {
        source: "apache",
        compressible: true,
        extensions: ["xpl"]
      },
      "application/xslt+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xsl", "xslt"]
      },
      "application/xspf+xml": {
        source: "apache",
        compressible: true,
        extensions: ["xspf"]
      },
      "application/xv+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mxml", "xhvml", "xvml", "xvm"]
      },
      "application/yang": {
        source: "iana",
        extensions: ["yang"]
      },
      "application/yang-data+json": {
        source: "iana",
        compressible: true
      },
      "application/yang-data+xml": {
        source: "iana",
        compressible: true
      },
      "application/yang-patch+json": {
        source: "iana",
        compressible: true
      },
      "application/yang-patch+xml": {
        source: "iana",
        compressible: true
      },
      "application/yin+xml": {
        source: "iana",
        compressible: true,
        extensions: ["yin"]
      },
      "application/zip": {
        source: "iana",
        compressible: false,
        extensions: ["zip"]
      },
      "application/zlib": {
        source: "iana"
      },
      "application/zstd": {
        source: "iana"
      },
      "audio/1d-interleaved-parityfec": {
        source: "iana"
      },
      "audio/32kadpcm": {
        source: "iana"
      },
      "audio/3gpp": {
        source: "iana",
        compressible: false,
        extensions: ["3gpp"]
      },
      "audio/3gpp2": {
        source: "iana"
      },
      "audio/aac": {
        source: "iana"
      },
      "audio/ac3": {
        source: "iana"
      },
      "audio/adpcm": {
        source: "apache",
        extensions: ["adp"]
      },
      "audio/amr": {
        source: "iana",
        extensions: ["amr"]
      },
      "audio/amr-wb": {
        source: "iana"
      },
      "audio/amr-wb+": {
        source: "iana"
      },
      "audio/aptx": {
        source: "iana"
      },
      "audio/asc": {
        source: "iana"
      },
      "audio/atrac-advanced-lossless": {
        source: "iana"
      },
      "audio/atrac-x": {
        source: "iana"
      },
      "audio/atrac3": {
        source: "iana"
      },
      "audio/basic": {
        source: "iana",
        compressible: false,
        extensions: ["au", "snd"]
      },
      "audio/bv16": {
        source: "iana"
      },
      "audio/bv32": {
        source: "iana"
      },
      "audio/clearmode": {
        source: "iana"
      },
      "audio/cn": {
        source: "iana"
      },
      "audio/dat12": {
        source: "iana"
      },
      "audio/dls": {
        source: "iana"
      },
      "audio/dsr-es201108": {
        source: "iana"
      },
      "audio/dsr-es202050": {
        source: "iana"
      },
      "audio/dsr-es202211": {
        source: "iana"
      },
      "audio/dsr-es202212": {
        source: "iana"
      },
      "audio/dv": {
        source: "iana"
      },
      "audio/dvi4": {
        source: "iana"
      },
      "audio/eac3": {
        source: "iana"
      },
      "audio/encaprtp": {
        source: "iana"
      },
      "audio/evrc": {
        source: "iana"
      },
      "audio/evrc-qcp": {
        source: "iana"
      },
      "audio/evrc0": {
        source: "iana"
      },
      "audio/evrc1": {
        source: "iana"
      },
      "audio/evrcb": {
        source: "iana"
      },
      "audio/evrcb0": {
        source: "iana"
      },
      "audio/evrcb1": {
        source: "iana"
      },
      "audio/evrcnw": {
        source: "iana"
      },
      "audio/evrcnw0": {
        source: "iana"
      },
      "audio/evrcnw1": {
        source: "iana"
      },
      "audio/evrcwb": {
        source: "iana"
      },
      "audio/evrcwb0": {
        source: "iana"
      },
      "audio/evrcwb1": {
        source: "iana"
      },
      "audio/evs": {
        source: "iana"
      },
      "audio/flexfec": {
        source: "iana"
      },
      "audio/fwdred": {
        source: "iana"
      },
      "audio/g711-0": {
        source: "iana"
      },
      "audio/g719": {
        source: "iana"
      },
      "audio/g722": {
        source: "iana"
      },
      "audio/g7221": {
        source: "iana"
      },
      "audio/g723": {
        source: "iana"
      },
      "audio/g726-16": {
        source: "iana"
      },
      "audio/g726-24": {
        source: "iana"
      },
      "audio/g726-32": {
        source: "iana"
      },
      "audio/g726-40": {
        source: "iana"
      },
      "audio/g728": {
        source: "iana"
      },
      "audio/g729": {
        source: "iana"
      },
      "audio/g7291": {
        source: "iana"
      },
      "audio/g729d": {
        source: "iana"
      },
      "audio/g729e": {
        source: "iana"
      },
      "audio/gsm": {
        source: "iana"
      },
      "audio/gsm-efr": {
        source: "iana"
      },
      "audio/gsm-hr-08": {
        source: "iana"
      },
      "audio/ilbc": {
        source: "iana"
      },
      "audio/ip-mr_v2.5": {
        source: "iana"
      },
      "audio/isac": {
        source: "apache"
      },
      "audio/l16": {
        source: "iana"
      },
      "audio/l20": {
        source: "iana"
      },
      "audio/l24": {
        source: "iana",
        compressible: false
      },
      "audio/l8": {
        source: "iana"
      },
      "audio/lpc": {
        source: "iana"
      },
      "audio/melp": {
        source: "iana"
      },
      "audio/melp1200": {
        source: "iana"
      },
      "audio/melp2400": {
        source: "iana"
      },
      "audio/melp600": {
        source: "iana"
      },
      "audio/mhas": {
        source: "iana"
      },
      "audio/midi": {
        source: "apache",
        extensions: ["mid", "midi", "kar", "rmi"]
      },
      "audio/mobile-xmf": {
        source: "iana",
        extensions: ["mxmf"]
      },
      "audio/mp3": {
        compressible: false,
        extensions: ["mp3"]
      },
      "audio/mp4": {
        source: "iana",
        compressible: false,
        extensions: ["m4a", "mp4a"]
      },
      "audio/mp4a-latm": {
        source: "iana"
      },
      "audio/mpa": {
        source: "iana"
      },
      "audio/mpa-robust": {
        source: "iana"
      },
      "audio/mpeg": {
        source: "iana",
        compressible: false,
        extensions: ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"]
      },
      "audio/mpeg4-generic": {
        source: "iana"
      },
      "audio/musepack": {
        source: "apache"
      },
      "audio/ogg": {
        source: "iana",
        compressible: false,
        extensions: ["oga", "ogg", "spx", "opus"]
      },
      "audio/opus": {
        source: "iana"
      },
      "audio/parityfec": {
        source: "iana"
      },
      "audio/pcma": {
        source: "iana"
      },
      "audio/pcma-wb": {
        source: "iana"
      },
      "audio/pcmu": {
        source: "iana"
      },
      "audio/pcmu-wb": {
        source: "iana"
      },
      "audio/prs.sid": {
        source: "iana"
      },
      "audio/qcelp": {
        source: "iana"
      },
      "audio/raptorfec": {
        source: "iana"
      },
      "audio/red": {
        source: "iana"
      },
      "audio/rtp-enc-aescm128": {
        source: "iana"
      },
      "audio/rtp-midi": {
        source: "iana"
      },
      "audio/rtploopback": {
        source: "iana"
      },
      "audio/rtx": {
        source: "iana"
      },
      "audio/s3m": {
        source: "apache",
        extensions: ["s3m"]
      },
      "audio/scip": {
        source: "iana"
      },
      "audio/silk": {
        source: "apache",
        extensions: ["sil"]
      },
      "audio/smv": {
        source: "iana"
      },
      "audio/smv-qcp": {
        source: "iana"
      },
      "audio/smv0": {
        source: "iana"
      },
      "audio/sofa": {
        source: "iana"
      },
      "audio/sp-midi": {
        source: "iana"
      },
      "audio/speex": {
        source: "iana"
      },
      "audio/t140c": {
        source: "iana"
      },
      "audio/t38": {
        source: "iana"
      },
      "audio/telephone-event": {
        source: "iana"
      },
      "audio/tetra_acelp": {
        source: "iana"
      },
      "audio/tetra_acelp_bb": {
        source: "iana"
      },
      "audio/tone": {
        source: "iana"
      },
      "audio/tsvcis": {
        source: "iana"
      },
      "audio/uemclip": {
        source: "iana"
      },
      "audio/ulpfec": {
        source: "iana"
      },
      "audio/usac": {
        source: "iana"
      },
      "audio/vdvi": {
        source: "iana"
      },
      "audio/vmr-wb": {
        source: "iana"
      },
      "audio/vnd.3gpp.iufp": {
        source: "iana"
      },
      "audio/vnd.4sb": {
        source: "iana"
      },
      "audio/vnd.audiokoz": {
        source: "iana"
      },
      "audio/vnd.celp": {
        source: "iana"
      },
      "audio/vnd.cisco.nse": {
        source: "iana"
      },
      "audio/vnd.cmles.radio-events": {
        source: "iana"
      },
      "audio/vnd.cns.anp1": {
        source: "iana"
      },
      "audio/vnd.cns.inf1": {
        source: "iana"
      },
      "audio/vnd.dece.audio": {
        source: "iana",
        extensions: ["uva", "uvva"]
      },
      "audio/vnd.digital-winds": {
        source: "iana",
        extensions: ["eol"]
      },
      "audio/vnd.dlna.adts": {
        source: "iana"
      },
      "audio/vnd.dolby.heaac.1": {
        source: "iana"
      },
      "audio/vnd.dolby.heaac.2": {
        source: "iana"
      },
      "audio/vnd.dolby.mlp": {
        source: "iana"
      },
      "audio/vnd.dolby.mps": {
        source: "iana"
      },
      "audio/vnd.dolby.pl2": {
        source: "iana"
      },
      "audio/vnd.dolby.pl2x": {
        source: "iana"
      },
      "audio/vnd.dolby.pl2z": {
        source: "iana"
      },
      "audio/vnd.dolby.pulse.1": {
        source: "iana"
      },
      "audio/vnd.dra": {
        source: "iana",
        extensions: ["dra"]
      },
      "audio/vnd.dts": {
        source: "iana",
        extensions: ["dts"]
      },
      "audio/vnd.dts.hd": {
        source: "iana",
        extensions: ["dtshd"]
      },
      "audio/vnd.dts.uhd": {
        source: "iana"
      },
      "audio/vnd.dvb.file": {
        source: "iana"
      },
      "audio/vnd.everad.plj": {
        source: "iana"
      },
      "audio/vnd.hns.audio": {
        source: "iana"
      },
      "audio/vnd.lucent.voice": {
        source: "iana",
        extensions: ["lvp"]
      },
      "audio/vnd.ms-playready.media.pya": {
        source: "iana",
        extensions: ["pya"]
      },
      "audio/vnd.nokia.mobile-xmf": {
        source: "iana"
      },
      "audio/vnd.nortel.vbk": {
        source: "iana"
      },
      "audio/vnd.nuera.ecelp4800": {
        source: "iana",
        extensions: ["ecelp4800"]
      },
      "audio/vnd.nuera.ecelp7470": {
        source: "iana",
        extensions: ["ecelp7470"]
      },
      "audio/vnd.nuera.ecelp9600": {
        source: "iana",
        extensions: ["ecelp9600"]
      },
      "audio/vnd.octel.sbc": {
        source: "iana"
      },
      "audio/vnd.presonus.multitrack": {
        source: "iana"
      },
      "audio/vnd.qcelp": {
        source: "iana"
      },
      "audio/vnd.rhetorex.32kadpcm": {
        source: "iana"
      },
      "audio/vnd.rip": {
        source: "iana",
        extensions: ["rip"]
      },
      "audio/vnd.rn-realaudio": {
        compressible: false
      },
      "audio/vnd.sealedmedia.softseal.mpeg": {
        source: "iana"
      },
      "audio/vnd.vmx.cvsd": {
        source: "iana"
      },
      "audio/vnd.wave": {
        compressible: false
      },
      "audio/vorbis": {
        source: "iana",
        compressible: false
      },
      "audio/vorbis-config": {
        source: "iana"
      },
      "audio/wav": {
        compressible: false,
        extensions: ["wav"]
      },
      "audio/wave": {
        compressible: false,
        extensions: ["wav"]
      },
      "audio/webm": {
        source: "apache",
        compressible: false,
        extensions: ["weba"]
      },
      "audio/x-aac": {
        source: "apache",
        compressible: false,
        extensions: ["aac"]
      },
      "audio/x-aiff": {
        source: "apache",
        extensions: ["aif", "aiff", "aifc"]
      },
      "audio/x-caf": {
        source: "apache",
        compressible: false,
        extensions: ["caf"]
      },
      "audio/x-flac": {
        source: "apache",
        extensions: ["flac"]
      },
      "audio/x-m4a": {
        source: "nginx",
        extensions: ["m4a"]
      },
      "audio/x-matroska": {
        source: "apache",
        extensions: ["mka"]
      },
      "audio/x-mpegurl": {
        source: "apache",
        extensions: ["m3u"]
      },
      "audio/x-ms-wax": {
        source: "apache",
        extensions: ["wax"]
      },
      "audio/x-ms-wma": {
        source: "apache",
        extensions: ["wma"]
      },
      "audio/x-pn-realaudio": {
        source: "apache",
        extensions: ["ram", "ra"]
      },
      "audio/x-pn-realaudio-plugin": {
        source: "apache",
        extensions: ["rmp"]
      },
      "audio/x-realaudio": {
        source: "nginx",
        extensions: ["ra"]
      },
      "audio/x-tta": {
        source: "apache"
      },
      "audio/x-wav": {
        source: "apache",
        extensions: ["wav"]
      },
      "audio/xm": {
        source: "apache",
        extensions: ["xm"]
      },
      "chemical/x-cdx": {
        source: "apache",
        extensions: ["cdx"]
      },
      "chemical/x-cif": {
        source: "apache",
        extensions: ["cif"]
      },
      "chemical/x-cmdf": {
        source: "apache",
        extensions: ["cmdf"]
      },
      "chemical/x-cml": {
        source: "apache",
        extensions: ["cml"]
      },
      "chemical/x-csml": {
        source: "apache",
        extensions: ["csml"]
      },
      "chemical/x-pdb": {
        source: "apache"
      },
      "chemical/x-xyz": {
        source: "apache",
        extensions: ["xyz"]
      },
      "font/collection": {
        source: "iana",
        extensions: ["ttc"]
      },
      "font/otf": {
        source: "iana",
        compressible: true,
        extensions: ["otf"]
      },
      "font/sfnt": {
        source: "iana"
      },
      "font/ttf": {
        source: "iana",
        compressible: true,
        extensions: ["ttf"]
      },
      "font/woff": {
        source: "iana",
        extensions: ["woff"]
      },
      "font/woff2": {
        source: "iana",
        extensions: ["woff2"]
      },
      "image/aces": {
        source: "iana",
        extensions: ["exr"]
      },
      "image/apng": {
        compressible: false,
        extensions: ["apng"]
      },
      "image/avci": {
        source: "iana",
        extensions: ["avci"]
      },
      "image/avcs": {
        source: "iana",
        extensions: ["avcs"]
      },
      "image/avif": {
        source: "iana",
        compressible: false,
        extensions: ["avif"]
      },
      "image/bmp": {
        source: "iana",
        compressible: true,
        extensions: ["bmp"]
      },
      "image/cgm": {
        source: "iana",
        extensions: ["cgm"]
      },
      "image/dicom-rle": {
        source: "iana",
        extensions: ["drle"]
      },
      "image/emf": {
        source: "iana",
        extensions: ["emf"]
      },
      "image/fits": {
        source: "iana",
        extensions: ["fits"]
      },
      "image/g3fax": {
        source: "iana",
        extensions: ["g3"]
      },
      "image/gif": {
        source: "iana",
        compressible: false,
        extensions: ["gif"]
      },
      "image/heic": {
        source: "iana",
        extensions: ["heic"]
      },
      "image/heic-sequence": {
        source: "iana",
        extensions: ["heics"]
      },
      "image/heif": {
        source: "iana",
        extensions: ["heif"]
      },
      "image/heif-sequence": {
        source: "iana",
        extensions: ["heifs"]
      },
      "image/hej2k": {
        source: "iana",
        extensions: ["hej2"]
      },
      "image/hsj2": {
        source: "iana",
        extensions: ["hsj2"]
      },
      "image/ief": {
        source: "iana",
        extensions: ["ief"]
      },
      "image/jls": {
        source: "iana",
        extensions: ["jls"]
      },
      "image/jp2": {
        source: "iana",
        compressible: false,
        extensions: ["jp2", "jpg2"]
      },
      "image/jpeg": {
        source: "iana",
        compressible: false,
        extensions: ["jpeg", "jpg", "jpe"]
      },
      "image/jph": {
        source: "iana",
        extensions: ["jph"]
      },
      "image/jphc": {
        source: "iana",
        extensions: ["jhc"]
      },
      "image/jpm": {
        source: "iana",
        compressible: false,
        extensions: ["jpm"]
      },
      "image/jpx": {
        source: "iana",
        compressible: false,
        extensions: ["jpx", "jpf"]
      },
      "image/jxr": {
        source: "iana",
        extensions: ["jxr"]
      },
      "image/jxra": {
        source: "iana",
        extensions: ["jxra"]
      },
      "image/jxrs": {
        source: "iana",
        extensions: ["jxrs"]
      },
      "image/jxs": {
        source: "iana",
        extensions: ["jxs"]
      },
      "image/jxsc": {
        source: "iana",
        extensions: ["jxsc"]
      },
      "image/jxsi": {
        source: "iana",
        extensions: ["jxsi"]
      },
      "image/jxss": {
        source: "iana",
        extensions: ["jxss"]
      },
      "image/ktx": {
        source: "iana",
        extensions: ["ktx"]
      },
      "image/ktx2": {
        source: "iana",
        extensions: ["ktx2"]
      },
      "image/naplps": {
        source: "iana"
      },
      "image/pjpeg": {
        compressible: false
      },
      "image/png": {
        source: "iana",
        compressible: false,
        extensions: ["png"]
      },
      "image/prs.btif": {
        source: "iana",
        extensions: ["btif"]
      },
      "image/prs.pti": {
        source: "iana",
        extensions: ["pti"]
      },
      "image/pwg-raster": {
        source: "iana"
      },
      "image/sgi": {
        source: "apache",
        extensions: ["sgi"]
      },
      "image/svg+xml": {
        source: "iana",
        compressible: true,
        extensions: ["svg", "svgz"]
      },
      "image/t38": {
        source: "iana",
        extensions: ["t38"]
      },
      "image/tiff": {
        source: "iana",
        compressible: false,
        extensions: ["tif", "tiff"]
      },
      "image/tiff-fx": {
        source: "iana",
        extensions: ["tfx"]
      },
      "image/vnd.adobe.photoshop": {
        source: "iana",
        compressible: true,
        extensions: ["psd"]
      },
      "image/vnd.airzip.accelerator.azv": {
        source: "iana",
        extensions: ["azv"]
      },
      "image/vnd.cns.inf2": {
        source: "iana"
      },
      "image/vnd.dece.graphic": {
        source: "iana",
        extensions: ["uvi", "uvvi", "uvg", "uvvg"]
      },
      "image/vnd.djvu": {
        source: "iana",
        extensions: ["djvu", "djv"]
      },
      "image/vnd.dvb.subtitle": {
        source: "iana",
        extensions: ["sub"]
      },
      "image/vnd.dwg": {
        source: "iana",
        extensions: ["dwg"]
      },
      "image/vnd.dxf": {
        source: "iana",
        extensions: ["dxf"]
      },
      "image/vnd.fastbidsheet": {
        source: "iana",
        extensions: ["fbs"]
      },
      "image/vnd.fpx": {
        source: "iana",
        extensions: ["fpx"]
      },
      "image/vnd.fst": {
        source: "iana",
        extensions: ["fst"]
      },
      "image/vnd.fujixerox.edmics-mmr": {
        source: "iana",
        extensions: ["mmr"]
      },
      "image/vnd.fujixerox.edmics-rlc": {
        source: "iana",
        extensions: ["rlc"]
      },
      "image/vnd.globalgraphics.pgb": {
        source: "iana"
      },
      "image/vnd.microsoft.icon": {
        source: "iana",
        compressible: true,
        extensions: ["ico"]
      },
      "image/vnd.mix": {
        source: "iana"
      },
      "image/vnd.mozilla.apng": {
        source: "iana"
      },
      "image/vnd.ms-dds": {
        compressible: true,
        extensions: ["dds"]
      },
      "image/vnd.ms-modi": {
        source: "iana",
        extensions: ["mdi"]
      },
      "image/vnd.ms-photo": {
        source: "apache",
        extensions: ["wdp"]
      },
      "image/vnd.net-fpx": {
        source: "iana",
        extensions: ["npx"]
      },
      "image/vnd.pco.b16": {
        source: "iana",
        extensions: ["b16"]
      },
      "image/vnd.radiance": {
        source: "iana"
      },
      "image/vnd.sealed.png": {
        source: "iana"
      },
      "image/vnd.sealedmedia.softseal.gif": {
        source: "iana"
      },
      "image/vnd.sealedmedia.softseal.jpg": {
        source: "iana"
      },
      "image/vnd.svf": {
        source: "iana"
      },
      "image/vnd.tencent.tap": {
        source: "iana",
        extensions: ["tap"]
      },
      "image/vnd.valve.source.texture": {
        source: "iana",
        extensions: ["vtf"]
      },
      "image/vnd.wap.wbmp": {
        source: "iana",
        extensions: ["wbmp"]
      },
      "image/vnd.xiff": {
        source: "iana",
        extensions: ["xif"]
      },
      "image/vnd.zbrush.pcx": {
        source: "iana",
        extensions: ["pcx"]
      },
      "image/webp": {
        source: "apache",
        extensions: ["webp"]
      },
      "image/wmf": {
        source: "iana",
        extensions: ["wmf"]
      },
      "image/x-3ds": {
        source: "apache",
        extensions: ["3ds"]
      },
      "image/x-cmu-raster": {
        source: "apache",
        extensions: ["ras"]
      },
      "image/x-cmx": {
        source: "apache",
        extensions: ["cmx"]
      },
      "image/x-freehand": {
        source: "apache",
        extensions: ["fh", "fhc", "fh4", "fh5", "fh7"]
      },
      "image/x-icon": {
        source: "apache",
        compressible: true,
        extensions: ["ico"]
      },
      "image/x-jng": {
        source: "nginx",
        extensions: ["jng"]
      },
      "image/x-mrsid-image": {
        source: "apache",
        extensions: ["sid"]
      },
      "image/x-ms-bmp": {
        source: "nginx",
        compressible: true,
        extensions: ["bmp"]
      },
      "image/x-pcx": {
        source: "apache",
        extensions: ["pcx"]
      },
      "image/x-pict": {
        source: "apache",
        extensions: ["pic", "pct"]
      },
      "image/x-portable-anymap": {
        source: "apache",
        extensions: ["pnm"]
      },
      "image/x-portable-bitmap": {
        source: "apache",
        extensions: ["pbm"]
      },
      "image/x-portable-graymap": {
        source: "apache",
        extensions: ["pgm"]
      },
      "image/x-portable-pixmap": {
        source: "apache",
        extensions: ["ppm"]
      },
      "image/x-rgb": {
        source: "apache",
        extensions: ["rgb"]
      },
      "image/x-tga": {
        source: "apache",
        extensions: ["tga"]
      },
      "image/x-xbitmap": {
        source: "apache",
        extensions: ["xbm"]
      },
      "image/x-xcf": {
        compressible: false
      },
      "image/x-xpixmap": {
        source: "apache",
        extensions: ["xpm"]
      },
      "image/x-xwindowdump": {
        source: "apache",
        extensions: ["xwd"]
      },
      "message/cpim": {
        source: "iana"
      },
      "message/delivery-status": {
        source: "iana"
      },
      "message/disposition-notification": {
        source: "iana",
        extensions: [
          "disposition-notification"
        ]
      },
      "message/external-body": {
        source: "iana"
      },
      "message/feedback-report": {
        source: "iana"
      },
      "message/global": {
        source: "iana",
        extensions: ["u8msg"]
      },
      "message/global-delivery-status": {
        source: "iana",
        extensions: ["u8dsn"]
      },
      "message/global-disposition-notification": {
        source: "iana",
        extensions: ["u8mdn"]
      },
      "message/global-headers": {
        source: "iana",
        extensions: ["u8hdr"]
      },
      "message/http": {
        source: "iana",
        compressible: false
      },
      "message/imdn+xml": {
        source: "iana",
        compressible: true
      },
      "message/news": {
        source: "iana"
      },
      "message/partial": {
        source: "iana",
        compressible: false
      },
      "message/rfc822": {
        source: "iana",
        compressible: true,
        extensions: ["eml", "mime"]
      },
      "message/s-http": {
        source: "iana"
      },
      "message/sip": {
        source: "iana"
      },
      "message/sipfrag": {
        source: "iana"
      },
      "message/tracking-status": {
        source: "iana"
      },
      "message/vnd.si.simp": {
        source: "iana"
      },
      "message/vnd.wfa.wsc": {
        source: "iana",
        extensions: ["wsc"]
      },
      "model/3mf": {
        source: "iana",
        extensions: ["3mf"]
      },
      "model/e57": {
        source: "iana"
      },
      "model/gltf+json": {
        source: "iana",
        compressible: true,
        extensions: ["gltf"]
      },
      "model/gltf-binary": {
        source: "iana",
        compressible: true,
        extensions: ["glb"]
      },
      "model/iges": {
        source: "iana",
        compressible: false,
        extensions: ["igs", "iges"]
      },
      "model/mesh": {
        source: "iana",
        compressible: false,
        extensions: ["msh", "mesh", "silo"]
      },
      "model/mtl": {
        source: "iana",
        extensions: ["mtl"]
      },
      "model/obj": {
        source: "iana",
        extensions: ["obj"]
      },
      "model/step": {
        source: "iana"
      },
      "model/step+xml": {
        source: "iana",
        compressible: true,
        extensions: ["stpx"]
      },
      "model/step+zip": {
        source: "iana",
        compressible: false,
        extensions: ["stpz"]
      },
      "model/step-xml+zip": {
        source: "iana",
        compressible: false,
        extensions: ["stpxz"]
      },
      "model/stl": {
        source: "iana",
        extensions: ["stl"]
      },
      "model/vnd.collada+xml": {
        source: "iana",
        compressible: true,
        extensions: ["dae"]
      },
      "model/vnd.dwf": {
        source: "iana",
        extensions: ["dwf"]
      },
      "model/vnd.flatland.3dml": {
        source: "iana"
      },
      "model/vnd.gdl": {
        source: "iana",
        extensions: ["gdl"]
      },
      "model/vnd.gs-gdl": {
        source: "apache"
      },
      "model/vnd.gs.gdl": {
        source: "iana"
      },
      "model/vnd.gtw": {
        source: "iana",
        extensions: ["gtw"]
      },
      "model/vnd.moml+xml": {
        source: "iana",
        compressible: true
      },
      "model/vnd.mts": {
        source: "iana",
        extensions: ["mts"]
      },
      "model/vnd.opengex": {
        source: "iana",
        extensions: ["ogex"]
      },
      "model/vnd.parasolid.transmit.binary": {
        source: "iana",
        extensions: ["x_b"]
      },
      "model/vnd.parasolid.transmit.text": {
        source: "iana",
        extensions: ["x_t"]
      },
      "model/vnd.pytha.pyox": {
        source: "iana"
      },
      "model/vnd.rosette.annotated-data-model": {
        source: "iana"
      },
      "model/vnd.sap.vds": {
        source: "iana",
        extensions: ["vds"]
      },
      "model/vnd.usdz+zip": {
        source: "iana",
        compressible: false,
        extensions: ["usdz"]
      },
      "model/vnd.valve.source.compiled-map": {
        source: "iana",
        extensions: ["bsp"]
      },
      "model/vnd.vtu": {
        source: "iana",
        extensions: ["vtu"]
      },
      "model/vrml": {
        source: "iana",
        compressible: false,
        extensions: ["wrl", "vrml"]
      },
      "model/x3d+binary": {
        source: "apache",
        compressible: false,
        extensions: ["x3db", "x3dbz"]
      },
      "model/x3d+fastinfoset": {
        source: "iana",
        extensions: ["x3db"]
      },
      "model/x3d+vrml": {
        source: "apache",
        compressible: false,
        extensions: ["x3dv", "x3dvz"]
      },
      "model/x3d+xml": {
        source: "iana",
        compressible: true,
        extensions: ["x3d", "x3dz"]
      },
      "model/x3d-vrml": {
        source: "iana",
        extensions: ["x3dv"]
      },
      "multipart/alternative": {
        source: "iana",
        compressible: false
      },
      "multipart/appledouble": {
        source: "iana"
      },
      "multipart/byteranges": {
        source: "iana"
      },
      "multipart/digest": {
        source: "iana"
      },
      "multipart/encrypted": {
        source: "iana",
        compressible: false
      },
      "multipart/form-data": {
        source: "iana",
        compressible: false
      },
      "multipart/header-set": {
        source: "iana"
      },
      "multipart/mixed": {
        source: "iana"
      },
      "multipart/multilingual": {
        source: "iana"
      },
      "multipart/parallel": {
        source: "iana"
      },
      "multipart/related": {
        source: "iana",
        compressible: false
      },
      "multipart/report": {
        source: "iana"
      },
      "multipart/signed": {
        source: "iana",
        compressible: false
      },
      "multipart/vnd.bint.med-plus": {
        source: "iana"
      },
      "multipart/voice-message": {
        source: "iana"
      },
      "multipart/x-mixed-replace": {
        source: "iana"
      },
      "text/1d-interleaved-parityfec": {
        source: "iana"
      },
      "text/cache-manifest": {
        source: "iana",
        compressible: true,
        extensions: ["appcache", "manifest"]
      },
      "text/calendar": {
        source: "iana",
        extensions: ["ics", "ifb"]
      },
      "text/calender": {
        compressible: true
      },
      "text/cmd": {
        compressible: true
      },
      "text/coffeescript": {
        extensions: ["coffee", "litcoffee"]
      },
      "text/cql": {
        source: "iana"
      },
      "text/cql-expression": {
        source: "iana"
      },
      "text/cql-identifier": {
        source: "iana"
      },
      "text/css": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["css"]
      },
      "text/csv": {
        source: "iana",
        compressible: true,
        extensions: ["csv"]
      },
      "text/csv-schema": {
        source: "iana"
      },
      "text/directory": {
        source: "iana"
      },
      "text/dns": {
        source: "iana"
      },
      "text/ecmascript": {
        source: "iana"
      },
      "text/encaprtp": {
        source: "iana"
      },
      "text/enriched": {
        source: "iana"
      },
      "text/fhirpath": {
        source: "iana"
      },
      "text/flexfec": {
        source: "iana"
      },
      "text/fwdred": {
        source: "iana"
      },
      "text/gff3": {
        source: "iana"
      },
      "text/grammar-ref-list": {
        source: "iana"
      },
      "text/html": {
        source: "iana",
        compressible: true,
        extensions: ["html", "htm", "shtml"]
      },
      "text/jade": {
        extensions: ["jade"]
      },
      "text/javascript": {
        source: "iana",
        compressible: true
      },
      "text/jcr-cnd": {
        source: "iana"
      },
      "text/jsx": {
        compressible: true,
        extensions: ["jsx"]
      },
      "text/less": {
        compressible: true,
        extensions: ["less"]
      },
      "text/markdown": {
        source: "iana",
        compressible: true,
        extensions: ["markdown", "md"]
      },
      "text/mathml": {
        source: "nginx",
        extensions: ["mml"]
      },
      "text/mdx": {
        compressible: true,
        extensions: ["mdx"]
      },
      "text/mizar": {
        source: "iana"
      },
      "text/n3": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["n3"]
      },
      "text/parameters": {
        source: "iana",
        charset: "UTF-8"
      },
      "text/parityfec": {
        source: "iana"
      },
      "text/plain": {
        source: "iana",
        compressible: true,
        extensions: ["txt", "text", "conf", "def", "list", "log", "in", "ini"]
      },
      "text/provenance-notation": {
        source: "iana",
        charset: "UTF-8"
      },
      "text/prs.fallenstein.rst": {
        source: "iana"
      },
      "text/prs.lines.tag": {
        source: "iana",
        extensions: ["dsc"]
      },
      "text/prs.prop.logic": {
        source: "iana"
      },
      "text/raptorfec": {
        source: "iana"
      },
      "text/red": {
        source: "iana"
      },
      "text/rfc822-headers": {
        source: "iana"
      },
      "text/richtext": {
        source: "iana",
        compressible: true,
        extensions: ["rtx"]
      },
      "text/rtf": {
        source: "iana",
        compressible: true,
        extensions: ["rtf"]
      },
      "text/rtp-enc-aescm128": {
        source: "iana"
      },
      "text/rtploopback": {
        source: "iana"
      },
      "text/rtx": {
        source: "iana"
      },
      "text/sgml": {
        source: "iana",
        extensions: ["sgml", "sgm"]
      },
      "text/shaclc": {
        source: "iana"
      },
      "text/shex": {
        source: "iana",
        extensions: ["shex"]
      },
      "text/slim": {
        extensions: ["slim", "slm"]
      },
      "text/spdx": {
        source: "iana",
        extensions: ["spdx"]
      },
      "text/strings": {
        source: "iana"
      },
      "text/stylus": {
        extensions: ["stylus", "styl"]
      },
      "text/t140": {
        source: "iana"
      },
      "text/tab-separated-values": {
        source: "iana",
        compressible: true,
        extensions: ["tsv"]
      },
      "text/troff": {
        source: "iana",
        extensions: ["t", "tr", "roff", "man", "me", "ms"]
      },
      "text/turtle": {
        source: "iana",
        charset: "UTF-8",
        extensions: ["ttl"]
      },
      "text/ulpfec": {
        source: "iana"
      },
      "text/uri-list": {
        source: "iana",
        compressible: true,
        extensions: ["uri", "uris", "urls"]
      },
      "text/vcard": {
        source: "iana",
        compressible: true,
        extensions: ["vcard"]
      },
      "text/vnd.a": {
        source: "iana"
      },
      "text/vnd.abc": {
        source: "iana"
      },
      "text/vnd.ascii-art": {
        source: "iana"
      },
      "text/vnd.curl": {
        source: "iana",
        extensions: ["curl"]
      },
      "text/vnd.curl.dcurl": {
        source: "apache",
        extensions: ["dcurl"]
      },
      "text/vnd.curl.mcurl": {
        source: "apache",
        extensions: ["mcurl"]
      },
      "text/vnd.curl.scurl": {
        source: "apache",
        extensions: ["scurl"]
      },
      "text/vnd.debian.copyright": {
        source: "iana",
        charset: "UTF-8"
      },
      "text/vnd.dmclientscript": {
        source: "iana"
      },
      "text/vnd.dvb.subtitle": {
        source: "iana",
        extensions: ["sub"]
      },
      "text/vnd.esmertec.theme-descriptor": {
        source: "iana",
        charset: "UTF-8"
      },
      "text/vnd.familysearch.gedcom": {
        source: "iana",
        extensions: ["ged"]
      },
      "text/vnd.ficlab.flt": {
        source: "iana"
      },
      "text/vnd.fly": {
        source: "iana",
        extensions: ["fly"]
      },
      "text/vnd.fmi.flexstor": {
        source: "iana",
        extensions: ["flx"]
      },
      "text/vnd.gml": {
        source: "iana"
      },
      "text/vnd.graphviz": {
        source: "iana",
        extensions: ["gv"]
      },
      "text/vnd.hans": {
        source: "iana"
      },
      "text/vnd.hgl": {
        source: "iana"
      },
      "text/vnd.in3d.3dml": {
        source: "iana",
        extensions: ["3dml"]
      },
      "text/vnd.in3d.spot": {
        source: "iana",
        extensions: ["spot"]
      },
      "text/vnd.iptc.newsml": {
        source: "iana"
      },
      "text/vnd.iptc.nitf": {
        source: "iana"
      },
      "text/vnd.latex-z": {
        source: "iana"
      },
      "text/vnd.motorola.reflex": {
        source: "iana"
      },
      "text/vnd.ms-mediapackage": {
        source: "iana"
      },
      "text/vnd.net2phone.commcenter.command": {
        source: "iana"
      },
      "text/vnd.radisys.msml-basic-layout": {
        source: "iana"
      },
      "text/vnd.senx.warpscript": {
        source: "iana"
      },
      "text/vnd.si.uricatalogue": {
        source: "iana"
      },
      "text/vnd.sosi": {
        source: "iana"
      },
      "text/vnd.sun.j2me.app-descriptor": {
        source: "iana",
        charset: "UTF-8",
        extensions: ["jad"]
      },
      "text/vnd.trolltech.linguist": {
        source: "iana",
        charset: "UTF-8"
      },
      "text/vnd.wap.si": {
        source: "iana"
      },
      "text/vnd.wap.sl": {
        source: "iana"
      },
      "text/vnd.wap.wml": {
        source: "iana",
        extensions: ["wml"]
      },
      "text/vnd.wap.wmlscript": {
        source: "iana",
        extensions: ["wmls"]
      },
      "text/vtt": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["vtt"]
      },
      "text/x-asm": {
        source: "apache",
        extensions: ["s", "asm"]
      },
      "text/x-c": {
        source: "apache",
        extensions: ["c", "cc", "cxx", "cpp", "h", "hh", "dic"]
      },
      "text/x-component": {
        source: "nginx",
        extensions: ["htc"]
      },
      "text/x-fortran": {
        source: "apache",
        extensions: ["f", "for", "f77", "f90"]
      },
      "text/x-gwt-rpc": {
        compressible: true
      },
      "text/x-handlebars-template": {
        extensions: ["hbs"]
      },
      "text/x-java-source": {
        source: "apache",
        extensions: ["java"]
      },
      "text/x-jquery-tmpl": {
        compressible: true
      },
      "text/x-lua": {
        extensions: ["lua"]
      },
      "text/x-markdown": {
        compressible: true,
        extensions: ["mkd"]
      },
      "text/x-nfo": {
        source: "apache",
        extensions: ["nfo"]
      },
      "text/x-opml": {
        source: "apache",
        extensions: ["opml"]
      },
      "text/x-org": {
        compressible: true,
        extensions: ["org"]
      },
      "text/x-pascal": {
        source: "apache",
        extensions: ["p", "pas"]
      },
      "text/x-processing": {
        compressible: true,
        extensions: ["pde"]
      },
      "text/x-sass": {
        extensions: ["sass"]
      },
      "text/x-scss": {
        extensions: ["scss"]
      },
      "text/x-setext": {
        source: "apache",
        extensions: ["etx"]
      },
      "text/x-sfv": {
        source: "apache",
        extensions: ["sfv"]
      },
      "text/x-suse-ymp": {
        compressible: true,
        extensions: ["ymp"]
      },
      "text/x-uuencode": {
        source: "apache",
        extensions: ["uu"]
      },
      "text/x-vcalendar": {
        source: "apache",
        extensions: ["vcs"]
      },
      "text/x-vcard": {
        source: "apache",
        extensions: ["vcf"]
      },
      "text/xml": {
        source: "iana",
        compressible: true,
        extensions: ["xml"]
      },
      "text/xml-external-parsed-entity": {
        source: "iana"
      },
      "text/yaml": {
        compressible: true,
        extensions: ["yaml", "yml"]
      },
      "video/1d-interleaved-parityfec": {
        source: "iana"
      },
      "video/3gpp": {
        source: "iana",
        extensions: ["3gp", "3gpp"]
      },
      "video/3gpp-tt": {
        source: "iana"
      },
      "video/3gpp2": {
        source: "iana",
        extensions: ["3g2"]
      },
      "video/av1": {
        source: "iana"
      },
      "video/bmpeg": {
        source: "iana"
      },
      "video/bt656": {
        source: "iana"
      },
      "video/celb": {
        source: "iana"
      },
      "video/dv": {
        source: "iana"
      },
      "video/encaprtp": {
        source: "iana"
      },
      "video/ffv1": {
        source: "iana"
      },
      "video/flexfec": {
        source: "iana"
      },
      "video/h261": {
        source: "iana",
        extensions: ["h261"]
      },
      "video/h263": {
        source: "iana",
        extensions: ["h263"]
      },
      "video/h263-1998": {
        source: "iana"
      },
      "video/h263-2000": {
        source: "iana"
      },
      "video/h264": {
        source: "iana",
        extensions: ["h264"]
      },
      "video/h264-rcdo": {
        source: "iana"
      },
      "video/h264-svc": {
        source: "iana"
      },
      "video/h265": {
        source: "iana"
      },
      "video/iso.segment": {
        source: "iana",
        extensions: ["m4s"]
      },
      "video/jpeg": {
        source: "iana",
        extensions: ["jpgv"]
      },
      "video/jpeg2000": {
        source: "iana"
      },
      "video/jpm": {
        source: "apache",
        extensions: ["jpm", "jpgm"]
      },
      "video/jxsv": {
        source: "iana"
      },
      "video/mj2": {
        source: "iana",
        extensions: ["mj2", "mjp2"]
      },
      "video/mp1s": {
        source: "iana"
      },
      "video/mp2p": {
        source: "iana"
      },
      "video/mp2t": {
        source: "iana",
        extensions: ["ts"]
      },
      "video/mp4": {
        source: "iana",
        compressible: false,
        extensions: ["mp4", "mp4v", "mpg4"]
      },
      "video/mp4v-es": {
        source: "iana"
      },
      "video/mpeg": {
        source: "iana",
        compressible: false,
        extensions: ["mpeg", "mpg", "mpe", "m1v", "m2v"]
      },
      "video/mpeg4-generic": {
        source: "iana"
      },
      "video/mpv": {
        source: "iana"
      },
      "video/nv": {
        source: "iana"
      },
      "video/ogg": {
        source: "iana",
        compressible: false,
        extensions: ["ogv"]
      },
      "video/parityfec": {
        source: "iana"
      },
      "video/pointer": {
        source: "iana"
      },
      "video/quicktime": {
        source: "iana",
        compressible: false,
        extensions: ["qt", "mov"]
      },
      "video/raptorfec": {
        source: "iana"
      },
      "video/raw": {
        source: "iana"
      },
      "video/rtp-enc-aescm128": {
        source: "iana"
      },
      "video/rtploopback": {
        source: "iana"
      },
      "video/rtx": {
        source: "iana"
      },
      "video/scip": {
        source: "iana"
      },
      "video/smpte291": {
        source: "iana"
      },
      "video/smpte292m": {
        source: "iana"
      },
      "video/ulpfec": {
        source: "iana"
      },
      "video/vc1": {
        source: "iana"
      },
      "video/vc2": {
        source: "iana"
      },
      "video/vnd.cctv": {
        source: "iana"
      },
      "video/vnd.dece.hd": {
        source: "iana",
        extensions: ["uvh", "uvvh"]
      },
      "video/vnd.dece.mobile": {
        source: "iana",
        extensions: ["uvm", "uvvm"]
      },
      "video/vnd.dece.mp4": {
        source: "iana"
      },
      "video/vnd.dece.pd": {
        source: "iana",
        extensions: ["uvp", "uvvp"]
      },
      "video/vnd.dece.sd": {
        source: "iana",
        extensions: ["uvs", "uvvs"]
      },
      "video/vnd.dece.video": {
        source: "iana",
        extensions: ["uvv", "uvvv"]
      },
      "video/vnd.directv.mpeg": {
        source: "iana"
      },
      "video/vnd.directv.mpeg-tts": {
        source: "iana"
      },
      "video/vnd.dlna.mpeg-tts": {
        source: "iana"
      },
      "video/vnd.dvb.file": {
        source: "iana",
        extensions: ["dvb"]
      },
      "video/vnd.fvt": {
        source: "iana",
        extensions: ["fvt"]
      },
      "video/vnd.hns.video": {
        source: "iana"
      },
      "video/vnd.iptvforum.1dparityfec-1010": {
        source: "iana"
      },
      "video/vnd.iptvforum.1dparityfec-2005": {
        source: "iana"
      },
      "video/vnd.iptvforum.2dparityfec-1010": {
        source: "iana"
      },
      "video/vnd.iptvforum.2dparityfec-2005": {
        source: "iana"
      },
      "video/vnd.iptvforum.ttsavc": {
        source: "iana"
      },
      "video/vnd.iptvforum.ttsmpeg2": {
        source: "iana"
      },
      "video/vnd.motorola.video": {
        source: "iana"
      },
      "video/vnd.motorola.videop": {
        source: "iana"
      },
      "video/vnd.mpegurl": {
        source: "iana",
        extensions: ["mxu", "m4u"]
      },
      "video/vnd.ms-playready.media.pyv": {
        source: "iana",
        extensions: ["pyv"]
      },
      "video/vnd.nokia.interleaved-multimedia": {
        source: "iana"
      },
      "video/vnd.nokia.mp4vr": {
        source: "iana"
      },
      "video/vnd.nokia.videovoip": {
        source: "iana"
      },
      "video/vnd.objectvideo": {
        source: "iana"
      },
      "video/vnd.radgamettools.bink": {
        source: "iana"
      },
      "video/vnd.radgamettools.smacker": {
        source: "iana"
      },
      "video/vnd.sealed.mpeg1": {
        source: "iana"
      },
      "video/vnd.sealed.mpeg4": {
        source: "iana"
      },
      "video/vnd.sealed.swf": {
        source: "iana"
      },
      "video/vnd.sealedmedia.softseal.mov": {
        source: "iana"
      },
      "video/vnd.uvvu.mp4": {
        source: "iana",
        extensions: ["uvu", "uvvu"]
      },
      "video/vnd.vivo": {
        source: "iana",
        extensions: ["viv"]
      },
      "video/vnd.youtube.yt": {
        source: "iana"
      },
      "video/vp8": {
        source: "iana"
      },
      "video/vp9": {
        source: "iana"
      },
      "video/webm": {
        source: "apache",
        compressible: false,
        extensions: ["webm"]
      },
      "video/x-f4v": {
        source: "apache",
        extensions: ["f4v"]
      },
      "video/x-fli": {
        source: "apache",
        extensions: ["fli"]
      },
      "video/x-flv": {
        source: "apache",
        compressible: false,
        extensions: ["flv"]
      },
      "video/x-m4v": {
        source: "apache",
        extensions: ["m4v"]
      },
      "video/x-matroska": {
        source: "apache",
        compressible: false,
        extensions: ["mkv", "mk3d", "mks"]
      },
      "video/x-mng": {
        source: "apache",
        extensions: ["mng"]
      },
      "video/x-ms-asf": {
        source: "apache",
        extensions: ["asf", "asx"]
      },
      "video/x-ms-vob": {
        source: "apache",
        extensions: ["vob"]
      },
      "video/x-ms-wm": {
        source: "apache",
        extensions: ["wm"]
      },
      "video/x-ms-wmv": {
        source: "apache",
        compressible: false,
        extensions: ["wmv"]
      },
      "video/x-ms-wmx": {
        source: "apache",
        extensions: ["wmx"]
      },
      "video/x-ms-wvx": {
        source: "apache",
        extensions: ["wvx"]
      },
      "video/x-msvideo": {
        source: "apache",
        extensions: ["avi"]
      },
      "video/x-sgi-movie": {
        source: "apache",
        extensions: ["movie"]
      },
      "video/x-smv": {
        source: "apache",
        extensions: ["smv"]
      },
      "x-conference/x-cooltalk": {
        source: "apache",
        extensions: ["ice"]
      },
      "x-shader/x-fragment": {
        compressible: true
      },
      "x-shader/x-vertex": {
        compressible: true
      }
    };
  }
});

// node_modules/mime-db/index.js
var require_mime_db = __commonJS({
  "node_modules/mime-db/index.js"(exports2, module2) {
    init_prefix();
    module2.exports = require_db();
  }
});

// node_modules/mime-types/index.js
var require_mime_types = __commonJS({
  "node_modules/mime-types/index.js"(exports2) {
    "use strict";
    init_prefix();
    var db = require_mime_db();
    var extname2 = require("path").extname;
    var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/;
    var TEXT_TYPE_REGEXP = /^text\//i;
    exports2.charset = charset;
    exports2.charsets = { lookup: charset };
    exports2.contentType = contentType;
    exports2.extension = extension;
    exports2.extensions = /* @__PURE__ */ Object.create(null);
    exports2.lookup = lookup;
    exports2.types = /* @__PURE__ */ Object.create(null);
    populateMaps(exports2.extensions, exports2.types);
    function charset(type) {
      if (!type || typeof type !== "string") {
        return false;
      }
      var match = EXTRACT_TYPE_REGEXP.exec(type);
      var mime = match && db[match[1].toLowerCase()];
      if (mime && mime.charset) {
        return mime.charset;
      }
      if (match && TEXT_TYPE_REGEXP.test(match[1])) {
        return "UTF-8";
      }
      return false;
    }
    function contentType(str) {
      if (!str || typeof str !== "string") {
        return false;
      }
      var mime = str.indexOf("/") === -1 ? exports2.lookup(str) : str;
      if (!mime) {
        return false;
      }
      if (mime.indexOf("charset") === -1) {
        var charset2 = exports2.charset(mime);
        if (charset2) mime += "; charset=" + charset2.toLowerCase();
      }
      return mime;
    }
    function extension(type) {
      if (!type || typeof type !== "string") {
        return false;
      }
      var match = EXTRACT_TYPE_REGEXP.exec(type);
      var exts = match && exports2.extensions[match[1].toLowerCase()];
      if (!exts || !exts.length) {
        return false;
      }
      return exts[0];
    }
    function lookup(path2) {
      if (!path2 || typeof path2 !== "string") {
        return false;
      }
      var extension2 = extname2("x." + path2).toLowerCase().substr(1);
      if (!extension2) {
        return false;
      }
      return exports2.types[extension2] || false;
    }
    function populateMaps(extensions, types) {
      var preference = ["nginx", "apache", void 0, "iana"];
      Object.keys(db).forEach(function forEachMimeType(type) {
        var mime = db[type];
        var exts = mime.extensions;
        if (!exts || !exts.length) {
          return;
        }
        extensions[type] = exts;
        for (var i = 0; i < exts.length; i++) {
          var extension2 = exts[i];
          if (types[extension2]) {
            var from = preference.indexOf(db[types[extension2]].source);
            var to = preference.indexOf(mime.source);
            if (types[extension2] !== "application/octet-stream" && (from > to || from === to && types[extension2].substr(0, 12) === "application/")) {
              continue;
            }
          }
          types[extension2] = type;
        }
      });
    }
  }
});

// node_modules/asynckit/lib/defer.js
var require_defer = __commonJS({
  "node_modules/asynckit/lib/defer.js"(exports2, module2) {
    init_prefix();
    module2.exports = defer;
    function defer(fn) {
      var nextTick = typeof setImmediate == "function" ? setImmediate : typeof process == "object" && typeof process.nextTick == "function" ? process.nextTick : null;
      if (nextTick) {
        nextTick(fn);
      } else {
        setTimeout(fn, 0);
      }
    }
  }
});

// node_modules/asynckit/lib/async.js
var require_async = __commonJS({
  "node_modules/asynckit/lib/async.js"(exports2, module2) {
    init_prefix();
    var defer = require_defer();
    module2.exports = async;
    function async(callback) {
      var isAsync = false;
      defer(function() {
        isAsync = true;
      });
      return function async_callback(err, result) {
        if (isAsync) {
          callback(err, result);
        } else {
          defer(function nextTick_callback() {
            callback(err, result);
          });
        }
      };
    }
  }
});

// node_modules/asynckit/lib/abort.js
var require_abort = __commonJS({
  "node_modules/asynckit/lib/abort.js"(exports2, module2) {
    init_prefix();
    module2.exports = abort;
    function abort(state) {
      Object.keys(state.jobs).forEach(clean.bind(state));
      state.jobs = {};
    }
    function clean(key) {
      if (typeof this.jobs[key] == "function") {
        this.jobs[key]();
      }
    }
  }
});

// node_modules/asynckit/lib/iterate.js
var require_iterate = __commonJS({
  "node_modules/asynckit/lib/iterate.js"(exports2, module2) {
    init_prefix();
    var async = require_async();
    var abort = require_abort();
    module2.exports = iterate;
    function iterate(list, iterator, state, callback) {
      var key = state["keyedList"] ? state["keyedList"][state.index] : state.index;
      state.jobs[key] = runJob(iterator, key, list[key], function(error, output) {
        if (!(key in state.jobs)) {
          return;
        }
        delete state.jobs[key];
        if (error) {
          abort(state);
        } else {
          state.results[key] = output;
        }
        callback(error, state.results);
      });
    }
    function runJob(iterator, key, item, callback) {
      var aborter;
      if (iterator.length == 2) {
        aborter = iterator(item, async(callback));
      } else {
        aborter = iterator(item, key, async(callback));
      }
      return aborter;
    }
  }
});

// node_modules/asynckit/lib/state.js
var require_state = __commonJS({
  "node_modules/asynckit/lib/state.js"(exports2, module2) {
    init_prefix();
    module2.exports = state;
    function state(list, sortMethod) {
      var isNamedList = !Array.isArray(list), initState = {
        index: 0,
        keyedList: isNamedList || sortMethod ? Object.keys(list) : null,
        jobs: {},
        results: isNamedList ? {} : [],
        size: isNamedList ? Object.keys(list).length : list.length
      };
      if (sortMethod) {
        initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) {
          return sortMethod(list[a], list[b]);
        });
      }
      return initState;
    }
  }
});

// node_modules/asynckit/lib/terminator.js
var require_terminator = __commonJS({
  "node_modules/asynckit/lib/terminator.js"(exports2, module2) {
    init_prefix();
    var abort = require_abort();
    var async = require_async();
    module2.exports = terminator;
    function terminator(callback) {
      if (!Object.keys(this.jobs).length) {
        return;
      }
      this.index = this.size;
      abort(this);
      async(callback)(null, this.results);
    }
  }
});

// node_modules/asynckit/parallel.js
var require_parallel = __commonJS({
  "node_modules/asynckit/parallel.js"(exports2, module2) {
    init_prefix();
    var iterate = require_iterate();
    var initState = require_state();
    var terminator = require_terminator();
    module2.exports = parallel;
    function parallel(list, iterator, callback) {
      var state = initState(list);
      while (state.index < (state["keyedList"] || list).length) {
        iterate(list, iterator, state, function(error, result) {
          if (error) {
            callback(error, result);
            return;
          }
          if (Object.keys(state.jobs).length === 0) {
            callback(null, state.results);
            return;
          }
        });
        state.index++;
      }
      return terminator.bind(state, callback);
    }
  }
});

// node_modules/asynckit/serialOrdered.js
var require_serialOrdered = __commonJS({
  "node_modules/asynckit/serialOrdered.js"(exports2, module2) {
    init_prefix();
    var iterate = require_iterate();
    var initState = require_state();
    var terminator = require_terminator();
    module2.exports = serialOrdered;
    module2.exports.ascending = ascending;
    module2.exports.descending = descending;
    function serialOrdered(list, iterator, sortMethod, callback) {
      var state = initState(list, sortMethod);
      iterate(list, iterator, state, function iteratorHandler(error, result) {
        if (error) {
          callback(error, result);
          return;
        }
        state.index++;
        if (state.index < (state["keyedList"] || list).length) {
          iterate(list, iterator, state, iteratorHandler);
          return;
        }
        callback(null, state.results);
      });
      return terminator.bind(state, callback);
    }
    function ascending(a, b) {
      return a < b ? -1 : a > b ? 1 : 0;
    }
    function descending(a, b) {
      return -1 * ascending(a, b);
    }
  }
});

// node_modules/asynckit/serial.js
var require_serial = __commonJS({
  "node_modules/asynckit/serial.js"(exports2, module2) {
    init_prefix();
    var serialOrdered = require_serialOrdered();
    module2.exports = serial;
    function serial(list, iterator, callback) {
      return serialOrdered(list, iterator, null, callback);
    }
  }
});

// node_modules/asynckit/index.js
var require_asynckit = __commonJS({
  "node_modules/asynckit/index.js"(exports2, module2) {
    init_prefix();
    module2.exports = {
      parallel: require_parallel(),
      serial: require_serial(),
      serialOrdered: require_serialOrdered()
    };
  }
});

// node_modules/es-object-atoms/index.js
var require_es_object_atoms = __commonJS({
  "node_modules/es-object-atoms/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = Object;
  }
});

// node_modules/es-errors/index.js
var require_es_errors = __commonJS({
  "node_modules/es-errors/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = Error;
  }
});

// node_modules/es-errors/eval.js
var require_eval = __commonJS({
  "node_modules/es-errors/eval.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = EvalError;
  }
});

// node_modules/es-errors/range.js
var require_range2 = __commonJS({
  "node_modules/es-errors/range.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = RangeError;
  }
});

// node_modules/es-errors/ref.js
var require_ref = __commonJS({
  "node_modules/es-errors/ref.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = ReferenceError;
  }
});

// node_modules/es-errors/syntax.js
var require_syntax = __commonJS({
  "node_modules/es-errors/syntax.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = SyntaxError;
  }
});

// node_modules/es-errors/type.js
var require_type = __commonJS({
  "node_modules/es-errors/type.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = TypeError;
  }
});

// node_modules/es-errors/uri.js
var require_uri = __commonJS({
  "node_modules/es-errors/uri.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = URIError;
  }
});

// node_modules/math-intrinsics/abs.js
var require_abs = __commonJS({
  "node_modules/math-intrinsics/abs.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = Math.abs;
  }
});

// node_modules/math-intrinsics/floor.js
var require_floor = __commonJS({
  "node_modules/math-intrinsics/floor.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = Math.floor;
  }
});

// node_modules/math-intrinsics/max.js
var require_max = __commonJS({
  "node_modules/math-intrinsics/max.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = Math.max;
  }
});

// node_modules/math-intrinsics/min.js
var require_min = __commonJS({
  "node_modules/math-intrinsics/min.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = Math.min;
  }
});

// node_modules/math-intrinsics/pow.js
var require_pow = __commonJS({
  "node_modules/math-intrinsics/pow.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = Math.pow;
  }
});

// node_modules/math-intrinsics/round.js
var require_round = __commonJS({
  "node_modules/math-intrinsics/round.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = Math.round;
  }
});

// node_modules/math-intrinsics/isNaN.js
var require_isNaN = __commonJS({
  "node_modules/math-intrinsics/isNaN.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = Number.isNaN || function isNaN2(a) {
      return a !== a;
    };
  }
});

// node_modules/math-intrinsics/sign.js
var require_sign = __commonJS({
  "node_modules/math-intrinsics/sign.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var $isNaN = require_isNaN();
    module2.exports = function sign(number) {
      if ($isNaN(number) || number === 0) {
        return number;
      }
      return number < 0 ? -1 : 1;
    };
  }
});

// node_modules/gopd/gOPD.js
var require_gOPD = __commonJS({
  "node_modules/gopd/gOPD.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = Object.getOwnPropertyDescriptor;
  }
});

// node_modules/gopd/index.js
var require_gopd = __commonJS({
  "node_modules/gopd/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var $gOPD = require_gOPD();
    if ($gOPD) {
      try {
        $gOPD([], "length");
      } catch (e) {
        $gOPD = null;
      }
    }
    module2.exports = $gOPD;
  }
});

// node_modules/es-define-property/index.js
var require_es_define_property = __commonJS({
  "node_modules/es-define-property/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var $defineProperty = Object.defineProperty || false;
    if ($defineProperty) {
      try {
        $defineProperty({}, "a", { value: 1 });
      } catch (e) {
        $defineProperty = false;
      }
    }
    module2.exports = $defineProperty;
  }
});

// node_modules/has-symbols/shams.js
var require_shams = __commonJS({
  "node_modules/has-symbols/shams.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = function hasSymbols() {
      if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") {
        return false;
      }
      if (typeof Symbol.iterator === "symbol") {
        return true;
      }
      var obj = {};
      var sym = /* @__PURE__ */ Symbol("test");
      var symObj = Object(sym);
      if (typeof sym === "string") {
        return false;
      }
      if (Object.prototype.toString.call(sym) !== "[object Symbol]") {
        return false;
      }
      if (Object.prototype.toString.call(symObj) !== "[object Symbol]") {
        return false;
      }
      var symVal = 42;
      obj[sym] = symVal;
      for (var _ in obj) {
        return false;
      }
      if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) {
        return false;
      }
      if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) {
        return false;
      }
      var syms = Object.getOwnPropertySymbols(obj);
      if (syms.length !== 1 || syms[0] !== sym) {
        return false;
      }
      if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) {
        return false;
      }
      if (typeof Object.getOwnPropertyDescriptor === "function") {
        var descriptor = (
          /** @type {PropertyDescriptor} */
          Object.getOwnPropertyDescriptor(obj, sym)
        );
        if (descriptor.value !== symVal || descriptor.enumerable !== true) {
          return false;
        }
      }
      return true;
    };
  }
});

// node_modules/has-symbols/index.js
var require_has_symbols = __commonJS({
  "node_modules/has-symbols/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var origSymbol = typeof Symbol !== "undefined" && Symbol;
    var hasSymbolSham = require_shams();
    module2.exports = function hasNativeSymbols() {
      if (typeof origSymbol !== "function") {
        return false;
      }
      if (typeof Symbol !== "function") {
        return false;
      }
      if (typeof origSymbol("foo") !== "symbol") {
        return false;
      }
      if (typeof /* @__PURE__ */ Symbol("bar") !== "symbol") {
        return false;
      }
      return hasSymbolSham();
    };
  }
});

// node_modules/get-proto/Reflect.getPrototypeOf.js
var require_Reflect_getPrototypeOf = __commonJS({
  "node_modules/get-proto/Reflect.getPrototypeOf.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null;
  }
});

// node_modules/get-proto/Object.getPrototypeOf.js
var require_Object_getPrototypeOf = __commonJS({
  "node_modules/get-proto/Object.getPrototypeOf.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var $Object = require_es_object_atoms();
    module2.exports = $Object.getPrototypeOf || null;
  }
});

// node_modules/function-bind/implementation.js
var require_implementation = __commonJS({
  "node_modules/function-bind/implementation.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var ERROR_MESSAGE = "Function.prototype.bind called on incompatible ";
    var toStr = Object.prototype.toString;
    var max = Math.max;
    var funcType = "[object Function]";
    var concatty = function concatty2(a, b) {
      var arr = [];
      for (var i = 0; i < a.length; i += 1) {
        arr[i] = a[i];
      }
      for (var j = 0; j < b.length; j += 1) {
        arr[j + a.length] = b[j];
      }
      return arr;
    };
    var slicy = function slicy2(arrLike, offset) {
      var arr = [];
      for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
        arr[j] = arrLike[i];
      }
      return arr;
    };
    var joiny = function(arr, joiner) {
      var str = "";
      for (var i = 0; i < arr.length; i += 1) {
        str += arr[i];
        if (i + 1 < arr.length) {
          str += joiner;
        }
      }
      return str;
    };
    module2.exports = function bind(that) {
      var target = this;
      if (typeof target !== "function" || toStr.apply(target) !== funcType) {
        throw new TypeError(ERROR_MESSAGE + target);
      }
      var args2 = slicy(arguments, 1);
      var bound;
      var binder = function() {
        if (this instanceof bound) {
          var result = target.apply(
            this,
            concatty(args2, arguments)
          );
          if (Object(result) === result) {
            return result;
          }
          return this;
        }
        return target.apply(
          that,
          concatty(args2, arguments)
        );
      };
      var boundLength = max(0, target.length - args2.length);
      var boundArgs = [];
      for (var i = 0; i < boundLength; i++) {
        boundArgs[i] = "$" + i;
      }
      bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder);
      if (target.prototype) {
        var Empty = function Empty2() {
        };
        Empty.prototype = target.prototype;
        bound.prototype = new Empty();
        Empty.prototype = null;
      }
      return bound;
    };
  }
});

// node_modules/function-bind/index.js
var require_function_bind = __commonJS({
  "node_modules/function-bind/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var implementation = require_implementation();
    module2.exports = Function.prototype.bind || implementation;
  }
});

// node_modules/call-bind-apply-helpers/functionCall.js
var require_functionCall = __commonJS({
  "node_modules/call-bind-apply-helpers/functionCall.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = Function.prototype.call;
  }
});

// node_modules/call-bind-apply-helpers/functionApply.js
var require_functionApply = __commonJS({
  "node_modules/call-bind-apply-helpers/functionApply.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = Function.prototype.apply;
  }
});

// node_modules/call-bind-apply-helpers/reflectApply.js
var require_reflectApply = __commonJS({
  "node_modules/call-bind-apply-helpers/reflectApply.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = typeof Reflect !== "undefined" && Reflect && Reflect.apply;
  }
});

// node_modules/call-bind-apply-helpers/actualApply.js
var require_actualApply = __commonJS({
  "node_modules/call-bind-apply-helpers/actualApply.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var bind = require_function_bind();
    var $apply = require_functionApply();
    var $call = require_functionCall();
    var $reflectApply = require_reflectApply();
    module2.exports = $reflectApply || bind.call($call, $apply);
  }
});

// node_modules/call-bind-apply-helpers/index.js
var require_call_bind_apply_helpers = __commonJS({
  "node_modules/call-bind-apply-helpers/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var bind = require_function_bind();
    var $TypeError = require_type();
    var $call = require_functionCall();
    var $actualApply = require_actualApply();
    module2.exports = function callBindBasic(args2) {
      if (args2.length < 1 || typeof args2[0] !== "function") {
        throw new $TypeError("a function is required");
      }
      return $actualApply(bind, $call, args2);
    };
  }
});

// node_modules/dunder-proto/get.js
var require_get = __commonJS({
  "node_modules/dunder-proto/get.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var callBind = require_call_bind_apply_helpers();
    var gOPD = require_gopd();
    var hasProtoAccessor;
    try {
      hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */
      [].__proto__ === Array.prototype;
    } catch (e) {
      if (!e || typeof e !== "object" || !("code" in e) || e.code !== "ERR_PROTO_ACCESS") {
        throw e;
      }
    }
    var desc = !!hasProtoAccessor && gOPD && gOPD(
      Object.prototype,
      /** @type {keyof typeof Object.prototype} */
      "__proto__"
    );
    var $Object = Object;
    var $getPrototypeOf = $Object.getPrototypeOf;
    module2.exports = desc && typeof desc.get === "function" ? callBind([desc.get]) : typeof $getPrototypeOf === "function" ? (
      /** @type {import('./get')} */
      function getDunder(value) {
        return $getPrototypeOf(value == null ? value : $Object(value));
      }
    ) : false;
  }
});

// node_modules/get-proto/index.js
var require_get_proto = __commonJS({
  "node_modules/get-proto/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var reflectGetProto = require_Reflect_getPrototypeOf();
    var originalGetProto = require_Object_getPrototypeOf();
    var getDunderProto = require_get();
    module2.exports = reflectGetProto ? function getProto(O) {
      return reflectGetProto(O);
    } : originalGetProto ? function getProto(O) {
      if (!O || typeof O !== "object" && typeof O !== "function") {
        throw new TypeError("getProto: not an object");
      }
      return originalGetProto(O);
    } : getDunderProto ? function getProto(O) {
      return getDunderProto(O);
    } : null;
  }
});

// node_modules/hasown/index.js
var require_hasown = __commonJS({
  "node_modules/hasown/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var call = Function.prototype.call;
    var $hasOwn = Object.prototype.hasOwnProperty;
    var bind = require_function_bind();
    module2.exports = bind.call(call, $hasOwn);
  }
});

// node_modules/get-intrinsic/index.js
var require_get_intrinsic = __commonJS({
  "node_modules/get-intrinsic/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var undefined2;
    var $Object = require_es_object_atoms();
    var $Error = require_es_errors();
    var $EvalError = require_eval();
    var $RangeError = require_range2();
    var $ReferenceError = require_ref();
    var $SyntaxError = require_syntax();
    var $TypeError = require_type();
    var $URIError = require_uri();
    var abs = require_abs();
    var floor = require_floor();
    var max = require_max();
    var min = require_min();
    var pow = require_pow();
    var round = require_round();
    var sign = require_sign();
    var $Function = Function;
    var getEvalledConstructor = function(expressionSyntax) {
      try {
        return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")();
      } catch (e) {
      }
    };
    var $gOPD = require_gopd();
    var $defineProperty = require_es_define_property();
    var throwTypeError = function() {
      throw new $TypeError();
    };
    var ThrowTypeError = $gOPD ? (function() {
      try {
        arguments.callee;
        return throwTypeError;
      } catch (calleeThrows) {
        try {
          return $gOPD(arguments, "callee").get;
        } catch (gOPDthrows) {
          return throwTypeError;
        }
      }
    })() : throwTypeError;
    var hasSymbols = require_has_symbols()();
    var getProto = require_get_proto();
    var $ObjectGPO = require_Object_getPrototypeOf();
    var $ReflectGPO = require_Reflect_getPrototypeOf();
    var $apply = require_functionApply();
    var $call = require_functionCall();
    var needsEval = {};
    var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined2 : getProto(Uint8Array);
    var INTRINSICS = {
      __proto__: null,
      "%AggregateError%": typeof AggregateError === "undefined" ? undefined2 : AggregateError,
      "%Array%": Array,
      "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined2 : ArrayBuffer,
      "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined2,
      "%AsyncFromSyncIteratorPrototype%": undefined2,
      "%AsyncFunction%": needsEval,
      "%AsyncGenerator%": needsEval,
      "%AsyncGeneratorFunction%": needsEval,
      "%AsyncIteratorPrototype%": needsEval,
      "%Atomics%": typeof Atomics === "undefined" ? undefined2 : Atomics,
      "%BigInt%": typeof BigInt === "undefined" ? undefined2 : BigInt,
      "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined2 : BigInt64Array,
      "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined2 : BigUint64Array,
      "%Boolean%": Boolean,
      "%DataView%": typeof DataView === "undefined" ? undefined2 : DataView,
      "%Date%": Date,
      "%decodeURI%": decodeURI,
      "%decodeURIComponent%": decodeURIComponent,
      "%encodeURI%": encodeURI,
      "%encodeURIComponent%": encodeURIComponent,
      "%Error%": $Error,
      "%eval%": eval,
      // eslint-disable-line no-eval
      "%EvalError%": $EvalError,
      "%Float16Array%": typeof Float16Array === "undefined" ? undefined2 : Float16Array,
      "%Float32Array%": typeof Float32Array === "undefined" ? undefined2 : Float32Array,
      "%Float64Array%": typeof Float64Array === "undefined" ? undefined2 : Float64Array,
      "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined2 : FinalizationRegistry,
      "%Function%": $Function,
      "%GeneratorFunction%": needsEval,
      "%Int8Array%": typeof Int8Array === "undefined" ? undefined2 : Int8Array,
      "%Int16Array%": typeof Int16Array === "undefined" ? undefined2 : Int16Array,
      "%Int32Array%": typeof Int32Array === "undefined" ? undefined2 : Int32Array,
      "%isFinite%": isFinite,
      "%isNaN%": isNaN,
      "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined2,
      "%JSON%": typeof JSON === "object" ? JSON : undefined2,
      "%Map%": typeof Map === "undefined" ? undefined2 : Map,
      "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Map())[Symbol.iterator]()),
      "%Math%": Math,
      "%Number%": Number,
      "%Object%": $Object,
      "%Object.getOwnPropertyDescriptor%": $gOPD,
      "%parseFloat%": parseFloat,
      "%parseInt%": parseInt,
      "%Promise%": typeof Promise === "undefined" ? undefined2 : Promise,
      "%Proxy%": typeof Proxy === "undefined" ? undefined2 : Proxy,
      "%RangeError%": $RangeError,
      "%ReferenceError%": $ReferenceError,
      "%Reflect%": typeof Reflect === "undefined" ? undefined2 : Reflect,
      "%RegExp%": RegExp,
      "%Set%": typeof Set === "undefined" ? undefined2 : Set,
      "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Set())[Symbol.iterator]()),
      "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined2 : SharedArrayBuffer,
      "%String%": String,
      "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined2,
      "%Symbol%": hasSymbols ? Symbol : undefined2,
      "%SyntaxError%": $SyntaxError,
      "%ThrowTypeError%": ThrowTypeError,
      "%TypedArray%": TypedArray,
      "%TypeError%": $TypeError,
      "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined2 : Uint8Array,
      "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined2 : Uint8ClampedArray,
      "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined2 : Uint16Array,
      "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined2 : Uint32Array,
      "%URIError%": $URIError,
      "%WeakMap%": typeof WeakMap === "undefined" ? undefined2 : WeakMap,
      "%WeakRef%": typeof WeakRef === "undefined" ? undefined2 : WeakRef,
      "%WeakSet%": typeof WeakSet === "undefined" ? undefined2 : WeakSet,
      "%Function.prototype.call%": $call,
      "%Function.prototype.apply%": $apply,
      "%Object.defineProperty%": $defineProperty,
      "%Object.getPrototypeOf%": $ObjectGPO,
      "%Math.abs%": abs,
      "%Math.floor%": floor,
      "%Math.max%": max,
      "%Math.min%": min,
      "%Math.pow%": pow,
      "%Math.round%": round,
      "%Math.sign%": sign,
      "%Reflect.getPrototypeOf%": $ReflectGPO
    };
    if (getProto) {
      try {
        null.error;
      } catch (e) {
        errorProto = getProto(getProto(e));
        INTRINSICS["%Error.prototype%"] = errorProto;
      }
    }
    var errorProto;
    var doEval = function doEval2(name) {
      var value;
      if (name === "%AsyncFunction%") {
        value = getEvalledConstructor("async function () {}");
      } else if (name === "%GeneratorFunction%") {
        value = getEvalledConstructor("function* () {}");
      } else if (name === "%AsyncGeneratorFunction%") {
        value = getEvalledConstructor("async function* () {}");
      } else if (name === "%AsyncGenerator%") {
        var fn = doEval2("%AsyncGeneratorFunction%");
        if (fn) {
          value = fn.prototype;
        }
      } else if (name === "%AsyncIteratorPrototype%") {
        var gen = doEval2("%AsyncGenerator%");
        if (gen && getProto) {
          value = getProto(gen.prototype);
        }
      }
      INTRINSICS[name] = value;
      return value;
    };
    var LEGACY_ALIASES = {
      __proto__: null,
      "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"],
      "%ArrayPrototype%": ["Array", "prototype"],
      "%ArrayProto_entries%": ["Array", "prototype", "entries"],
      "%ArrayProto_forEach%": ["Array", "prototype", "forEach"],
      "%ArrayProto_keys%": ["Array", "prototype", "keys"],
      "%ArrayProto_values%": ["Array", "prototype", "values"],
      "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"],
      "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"],
      "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"],
      "%BooleanPrototype%": ["Boolean", "prototype"],
      "%DataViewPrototype%": ["DataView", "prototype"],
      "%DatePrototype%": ["Date", "prototype"],
      "%ErrorPrototype%": ["Error", "prototype"],
      "%EvalErrorPrototype%": ["EvalError", "prototype"],
      "%Float32ArrayPrototype%": ["Float32Array", "prototype"],
      "%Float64ArrayPrototype%": ["Float64Array", "prototype"],
      "%FunctionPrototype%": ["Function", "prototype"],
      "%Generator%": ["GeneratorFunction", "prototype"],
      "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"],
      "%Int8ArrayPrototype%": ["Int8Array", "prototype"],
      "%Int16ArrayPrototype%": ["Int16Array", "prototype"],
      "%Int32ArrayPrototype%": ["Int32Array", "prototype"],
      "%JSONParse%": ["JSON", "parse"],
      "%JSONStringify%": ["JSON", "stringify"],
      "%MapPrototype%": ["Map", "prototype"],
      "%NumberPrototype%": ["Number", "prototype"],
      "%ObjectPrototype%": ["Object", "prototype"],
      "%ObjProto_toString%": ["Object", "prototype", "toString"],
      "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"],
      "%PromisePrototype%": ["Promise", "prototype"],
      "%PromiseProto_then%": ["Promise", "prototype", "then"],
      "%Promise_all%": ["Promise", "all"],
      "%Promise_reject%": ["Promise", "reject"],
      "%Promise_resolve%": ["Promise", "resolve"],
      "%RangeErrorPrototype%": ["RangeError", "prototype"],
      "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"],
      "%RegExpPrototype%": ["RegExp", "prototype"],
      "%SetPrototype%": ["Set", "prototype"],
      "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"],
      "%StringPrototype%": ["String", "prototype"],
      "%SymbolPrototype%": ["Symbol", "prototype"],
      "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"],
      "%TypedArrayPrototype%": ["TypedArray", "prototype"],
      "%TypeErrorPrototype%": ["TypeError", "prototype"],
      "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"],
      "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"],
      "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"],
      "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"],
      "%URIErrorPrototype%": ["URIError", "prototype"],
      "%WeakMapPrototype%": ["WeakMap", "prototype"],
      "%WeakSetPrototype%": ["WeakSet", "prototype"]
    };
    var bind = require_function_bind();
    var hasOwn = require_hasown();
    var $concat = bind.call($call, Array.prototype.concat);
    var $spliceApply = bind.call($apply, Array.prototype.splice);
    var $replace = bind.call($call, String.prototype.replace);
    var $strSlice = bind.call($call, String.prototype.slice);
    var $exec = bind.call($call, RegExp.prototype.exec);
    var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
    var reEscapeChar = /\\(\\)?/g;
    var stringToPath = function stringToPath2(string) {
      var first = $strSlice(string, 0, 1);
      var last = $strSlice(string, -1);
      if (first === "%" && last !== "%") {
        throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");
      } else if (last === "%" && first !== "%") {
        throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");
      }
      var result = [];
      $replace(string, rePropName, function(match, number, quote, subString) {
        result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match;
      });
      return result;
    };
    var getBaseIntrinsic = function getBaseIntrinsic2(name, allowMissing) {
      var intrinsicName = name;
      var alias;
      if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
        alias = LEGACY_ALIASES[intrinsicName];
        intrinsicName = "%" + alias[0] + "%";
      }
      if (hasOwn(INTRINSICS, intrinsicName)) {
        var value = INTRINSICS[intrinsicName];
        if (value === needsEval) {
          value = doEval(intrinsicName);
        }
        if (typeof value === "undefined" && !allowMissing) {
          throw new $TypeError("intrinsic " + name + " exists, but is not available. Please file an issue!");
        }
        return {
          alias,
          name: intrinsicName,
          value
        };
      }
      throw new $SyntaxError("intrinsic " + name + " does not exist!");
    };
    module2.exports = function GetIntrinsic(name, allowMissing) {
      if (typeof name !== "string" || name.length === 0) {
        throw new $TypeError("intrinsic name must be a non-empty string");
      }
      if (arguments.length > 1 && typeof allowMissing !== "boolean") {
        throw new $TypeError('"allowMissing" argument must be a boolean');
      }
      if ($exec(/^%?[^%]*%?$/, name) === null) {
        throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");
      }
      var parts = stringToPath(name);
      var intrinsicBaseName = parts.length > 0 ? parts[0] : "";
      var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing);
      var intrinsicRealName = intrinsic.name;
      var value = intrinsic.value;
      var skipFurtherCaching = false;
      var alias = intrinsic.alias;
      if (alias) {
        intrinsicBaseName = alias[0];
        $spliceApply(parts, $concat([0, 1], alias));
      }
      for (var i = 1, isOwn = true; i < parts.length; i += 1) {
        var part = parts[i];
        var first = $strSlice(part, 0, 1);
        var last = $strSlice(part, -1);
        if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) {
          throw new $SyntaxError("property names with quotes must have matching quotes");
        }
        if (part === "constructor" || !isOwn) {
          skipFurtherCaching = true;
        }
        intrinsicBaseName += "." + part;
        intrinsicRealName = "%" + intrinsicBaseName + "%";
        if (hasOwn(INTRINSICS, intrinsicRealName)) {
          value = INTRINSICS[intrinsicRealName];
        } else if (value != null) {
          if (!(part in value)) {
            if (!allowMissing) {
              throw new $TypeError("base intrinsic for " + name + " exists, but the property is not available.");
            }
            return void undefined2;
          }
          if ($gOPD && i + 1 >= parts.length) {
            var desc = $gOPD(value, part);
            isOwn = !!desc;
            if (isOwn && "get" in desc && !("originalValue" in desc.get)) {
              value = desc.get;
            } else {
              value = value[part];
            }
          } else {
            isOwn = hasOwn(value, part);
            value = value[part];
          }
          if (isOwn && !skipFurtherCaching) {
            INTRINSICS[intrinsicRealName] = value;
          }
        }
      }
      return value;
    };
  }
});

// node_modules/has-tostringtag/shams.js
var require_shams2 = __commonJS({
  "node_modules/has-tostringtag/shams.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var hasSymbols = require_shams();
    module2.exports = function hasToStringTagShams() {
      return hasSymbols() && !!Symbol.toStringTag;
    };
  }
});

// node_modules/es-set-tostringtag/index.js
var require_es_set_tostringtag = __commonJS({
  "node_modules/es-set-tostringtag/index.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var GetIntrinsic = require_get_intrinsic();
    var $defineProperty = GetIntrinsic("%Object.defineProperty%", true);
    var hasToStringTag = require_shams2()();
    var hasOwn = require_hasown();
    var $TypeError = require_type();
    var toStringTag = hasToStringTag ? Symbol.toStringTag : null;
    module2.exports = function setToStringTag(object, value) {
      var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force;
      var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable;
      if (typeof overrideIfSet !== "undefined" && typeof overrideIfSet !== "boolean" || typeof nonConfigurable !== "undefined" && typeof nonConfigurable !== "boolean") {
        throw new $TypeError("if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans");
      }
      if (toStringTag && (overrideIfSet || !hasOwn(object, toStringTag))) {
        if ($defineProperty) {
          $defineProperty(object, toStringTag, {
            configurable: !nonConfigurable,
            enumerable: false,
            value,
            writable: false
          });
        } else {
          object[toStringTag] = value;
        }
      }
    };
  }
});

// node_modules/form-data/lib/populate.js
var require_populate = __commonJS({
  "node_modules/form-data/lib/populate.js"(exports2, module2) {
    "use strict";
    init_prefix();
    module2.exports = function(dst, src) {
      Object.keys(src).forEach(function(prop) {
        dst[prop] = dst[prop] || src[prop];
      });
      return dst;
    };
  }
});

// node_modules/form-data/lib/form_data.js
var require_form_data = __commonJS({
  "node_modules/form-data/lib/form_data.js"(exports2, module2) {
    "use strict";
    init_prefix();
    var CombinedStream = require_combined_stream();
    var util = require("util");
    var path2 = require("path");
    var http = require("http");
    var https = require("https");
    var parseUrl = require("url").parse;
    var fs2 = require("fs");
    var Stream = require("stream").Stream;
    var crypto = require("crypto");
    var mime = require_mime_types();
    var asynckit = require_asynckit();
    var setToStringTag = require_es_set_tostringtag();
    var hasOwn = require_hasown();
    var populate = require_populate();
    function FormData2(options) {
      if (!(this instanceof FormData2)) {
        return new FormData2(options);
      }
      this._overheadLength = 0;
      this._valueLength = 0;
      this._valuesToMeasure = [];
      CombinedStream.call(this);
      options = options || {};
      for (var option in options) {
        this[option] = options[option];
      }
    }
    util.inherits(FormData2, CombinedStream);
    FormData2.LINE_BREAK = "\r\n";
    FormData2.DEFAULT_CONTENT_TYPE = "application/octet-stream";
    FormData2.prototype.append = function(field, value, options) {
      options = options || {};
      if (typeof options === "string") {
        options = { filename: options };
      }
      var append = CombinedStream.prototype.append.bind(this);
      if (typeof value === "number" || value == null) {
        value = String(value);
      }
      if (Array.isArray(value)) {
        this._error(new Error("Arrays are not supported."));
        return;
      }
      var header = this._multiPartHeader(field, value, options);
      var footer = this._multiPartFooter();
      append(header);
      append(value);
      append(footer);
      this._trackLength(header, value, options);
    };
    FormData2.prototype._trackLength = function(header, value, options) {
      var valueLength = 0;
      if (options.knownLength != null) {
        valueLength += Number(options.knownLength);
      } else if (Buffer.isBuffer(value)) {
        valueLength = value.length;
      } else if (typeof value === "string") {
        valueLength = Buffer.byteLength(value);
      }
      this._valueLength += valueLength;
      this._overheadLength += Buffer.byteLength(header) + FormData2.LINE_BREAK.length;
      if (!value || !value.path && !(value.readable && hasOwn(value, "httpVersion")) && !(value instanceof Stream)) {
        return;
      }
      if (!options.knownLength) {
        this._valuesToMeasure.push(value);
      }
    };
    FormData2.prototype._lengthRetriever = function(value, callback) {
      if (hasOwn(value, "fd")) {
        if (value.end != void 0 && value.end != Infinity && value.start != void 0) {
          callback(null, value.end + 1 - (value.start ? value.start : 0));
        } else {
          fs2.stat(value.path, function(err, stat) {
            if (err) {
              callback(err);
              return;
            }
            var fileSize = stat.size - (value.start ? value.start : 0);
            callback(null, fileSize);
          });
        }
      } else if (hasOwn(value, "httpVersion")) {
        callback(null, Number(value.headers["content-length"]));
      } else if (hasOwn(value, "httpModule")) {
        value.on("response", function(response) {
          value.pause();
          callback(null, Number(response.headers["content-length"]));
        });
        value.resume();
      } else {
        callback("Unknown stream");
      }
    };
    FormData2.prototype._multiPartHeader = function(field, value, options) {
      if (typeof options.header === "string") {
        return options.header;
      }
      var contentDisposition = this._getContentDisposition(value, options);
      var contentType = this._getContentType(value, options);
      var contents = "";
      var headers = {
        // add custom disposition as third element or keep it two elements if not
        "Content-Disposition": ["form-data", 'name="' + field + '"'].concat(contentDisposition || []),
        // if no content type. allow it to be empty array
        "Content-Type": [].concat(contentType || [])
      };
      if (typeof options.header === "object") {
        populate(headers, options.header);
      }
      var header;
      for (var prop in headers) {
        if (hasOwn(headers, prop)) {
          header = headers[prop];
          if (header == null) {
            continue;
          }
          if (!Array.isArray(header)) {
            header = [header];
          }
          if (header.length) {
            contents += prop + ": " + header.join("; ") + FormData2.LINE_BREAK;
          }
        }
      }
      return "--" + this.getBoundary() + FormData2.LINE_BREAK + contents + FormData2.LINE_BREAK;
    };
    FormData2.prototype._getContentDisposition = function(value, options) {
      var filename;
      if (typeof options.filepath === "string") {
        filename = path2.normalize(options.filepath).replace(/\\/g, "/");
      } else if (options.filename || value && (value.name || value.path)) {
        filename = path2.basename(options.filename || value && (value.name || value.path));
      } else if (value && value.readable && hasOwn(value, "httpVersion")) {
        filename = path2.basename(value.client._httpMessage.path || "");
      }
      if (filename) {
        return 'filename="' + filename + '"';
      }
    };
    FormData2.prototype._getContentType = function(value, options) {
      var contentType = options.contentType;
      if (!contentType && value && value.name) {
        contentType = mime.lookup(value.name);
      }
      if (!contentType && value && value.path) {
        contentType = mime.lookup(value.path);
      }
      if (!contentType && value && value.readable && hasOwn(value, "httpVersion")) {
        contentType = value.headers["content-type"];
      }
      if (!contentType && (options.filepath || options.filename)) {
        contentType = mime.lookup(options.filepath || options.filename);
      }
      if (!contentType && value && typeof value === "object") {
        contentType = FormData2.DEFAULT_CONTENT_TYPE;
      }
      return contentType;
    };
    FormData2.prototype._multiPartFooter = function() {
      return function(next) {
        var footer = FormData2.LINE_BREAK;
        var lastPart = this._streams.length === 0;
        if (lastPart) {
          footer += this._lastBoundary();
        }
        next(footer);
      }.bind(this);
    };
    FormData2.prototype._lastBoundary = function() {
      return "--" + this.getBoundary() + "--" + FormData2.LINE_BREAK;
    };
    FormData2.prototype.getHeaders = function(userHeaders) {
      var header;
      var formHeaders = {
        "content-type": "multipart/form-data; boundary=" + this.getBoundary()
      };
      for (header in userHeaders) {
        if (hasOwn(userHeaders, header)) {
          formHeaders[header.toLowerCase()] = userHeaders[header];
        }
      }
      return formHeaders;
    };
    FormData2.prototype.setBoundary = function(boundary) {
      if (typeof boundary !== "string") {
        throw new TypeError("FormData boundary must be a string");
      }
      this._boundary = boundary;
    };
    FormData2.prototype.getBoundary = function() {
      if (!this._boundary) {
        this._generateBoundary();
      }
      return this._boundary;
    };
    FormData2.prototype.getBuffer = function() {
      var dataBuffer = new Buffer.alloc(0);
      var boundary = this.getBoundary();
      for (var i = 0, len = this._streams.length; i < len; i++) {
        if (typeof this._streams[i] !== "function") {
          if (Buffer.isBuffer(this._streams[i])) {
            dataBuffer = Buffer.concat([dataBuffer, this._streams[i]]);
          } else {
            dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i])]);
          }
          if (typeof this._streams[i] !== "string" || this._streams[i].substring(2, boundary.length + 2) !== boundary) {
            dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData2.LINE_BREAK)]);
          }
        }
      }
      return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]);
    };
    FormData2.prototype._generateBoundary = function() {
      this._boundary = "--------------------------" + crypto.randomBytes(12).toString("hex");
    };
    FormData2.prototype.getLengthSync = function() {
      var knownLength = this._overheadLength + this._valueLength;
      if (this._streams.length) {
        knownLength += this._lastBoundary().length;
      }
      if (!this.hasKnownLength()) {
        this._error(new Error("Cannot calculate proper length in synchronous way."));
      }
      return knownLength;
    };
    FormData2.prototype.hasKnownLength = function() {
      var hasKnownLength = true;
      if (this._valuesToMeasure.length) {
        hasKnownLength = false;
      }
      return hasKnownLength;
    };
    FormData2.prototype.getLength = function(cb) {
      var knownLength = this._overheadLength + this._valueLength;
      if (this._streams.length) {
        knownLength += this._lastBoundary().length;
      }
      if (!this._valuesToMeasure.length) {
        process.nextTick(cb.bind(this, null, knownLength));
        return;
      }
      asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) {
        if (err) {
          cb(err);
          return;
        }
        values.forEach(function(length) {
          knownLength += length;
        });
        cb(null, knownLength);
      });
    };
    FormData2.prototype.submit = function(params, cb) {
      var request;
      var options;
      var defaults = { method: "post" };
      if (typeof params === "string") {
        params = parseUrl(params);
        options = populate({
          port: params.port,
          path: params.pathname,
          host: params.hostname,
          protocol: params.protocol
        }, defaults);
      } else {
        options = populate(params, defaults);
        if (!options.port) {
          options.port = options.protocol === "https:" ? 443 : 80;
        }
      }
      options.headers = this.getHeaders(params.headers);
      if (options.protocol === "https:") {
        request = https.request(options);
      } else {
        request = http.request(options);
      }
      this.getLength(function(err, length) {
        if (err && err !== "Unknown stream") {
          this._error(err);
          return;
        }
        if (length) {
          request.setHeader("Content-Length", length);
        }
        this.pipe(request);
        if (cb) {
          var onResponse;
          var callback = function(error, responce) {
            request.removeListener("error", callback);
            request.removeListener("response", onResponse);
            return cb.call(this, error, responce);
          };
          onResponse = callback.bind(this, null);
          request.on("error", callback);
          request.on("response", onResponse);
        }
      }.bind(this));
      return request;
    };
    FormData2.prototype._error = function(err) {
      if (!this.error) {
        this.error = err;
        this.pause();
        this.emit("error", err);
      }
    };
    FormData2.prototype.toString = function() {
      return "[object FormData]";
    };
    setToStringTag(FormData2.prototype, "FormData");
    module2.exports = FormData2;
  }
});

// node_modules/follow-redirects/debug.js
var require_debug4 = __commonJS({
  "node_modules/follow-redirects/debug.js"(exports2, module2) {
    init_prefix();
    var debug;
    module2.exports = function() {
      if (!debug) {
        try {
          debug = require_src()("follow-redirects");
        } catch (error) {
        }
        if (typeof debug !== "function") {
          debug = function() {
          };
        }
      }
      debug.apply(null, arguments);
    };
  }
});

// node_modules/follow-redirects/index.js
var require_follow_redirects = __commonJS({
  "node_modules/follow-redirects/index.js"(exports2, module2) {
    init_prefix();
    var url = require("url");
    var URL2 = url.URL;
    var http = require("http");
    var https = require("https");
    var Writable = require("stream").Writable;
    var assert = require("assert");
    var debug = require_debug4();
    (function detectUnsupportedEnvironment() {
      var looksLikeNode = typeof process !== "undefined";
      var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined";
      var looksLikeV8 = isFunction2(Error.captureStackTrace);
      if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) {
        console.warn("The follow-redirects package should be excluded from browser builds.");
      }
    })();
    var useNativeURL = false;
    try {
      assert(new URL2(""));
    } catch (error) {
      useNativeURL = error.code === "ERR_INVALID_URL";
    }
    var preservedUrlFields = [
      "auth",
      "host",
      "hostname",
      "href",
      "path",
      "pathname",
      "port",
      "protocol",
      "query",
      "search",
      "hash"
    ];
    var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
    var eventHandlers = /* @__PURE__ */ Object.create(null);
    events.forEach(function(event) {
      eventHandlers[event] = function(arg1, arg2, arg3) {
        this._redirectable.emit(event, arg1, arg2, arg3);
      };
    });
    var InvalidUrlError = createErrorType(
      "ERR_INVALID_URL",
      "Invalid URL",
      TypeError
    );
    var RedirectionError = createErrorType(
      "ERR_FR_REDIRECTION_FAILURE",
      "Redirected request failed"
    );
    var TooManyRedirectsError = createErrorType(
      "ERR_FR_TOO_MANY_REDIRECTS",
      "Maximum number of redirects exceeded",
      RedirectionError
    );
    var MaxBodyLengthExceededError = createErrorType(
      "ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
      "Request body larger than maxBodyLength limit"
    );
    var WriteAfterEndError = createErrorType(
      "ERR_STREAM_WRITE_AFTER_END",
      "write after end"
    );
    var destroy = Writable.prototype.destroy || noop;
    function RedirectableRequest(options, responseCallback) {
      Writable.call(this);
      this._sanitizeOptions(options);
      this._options = options;
      this._ended = false;
      this._ending = false;
      this._redirectCount = 0;
      this._redirects = [];
      this._requestBodyLength = 0;
      this._requestBodyBuffers = [];
      if (responseCallback) {
        this.on("response", responseCallback);
      }
      var self2 = this;
      this._onNativeResponse = function(response) {
        try {
          self2._processResponse(response);
        } catch (cause) {
          self2.emit("error", cause instanceof RedirectionError ? cause : new RedirectionError({ cause }));
        }
      };
      this._performRequest();
    }
    RedirectableRequest.prototype = Object.create(Writable.prototype);
    RedirectableRequest.prototype.abort = function() {
      destroyRequest(this._currentRequest);
      this._currentRequest.abort();
      this.emit("abort");
    };
    RedirectableRequest.prototype.destroy = function(error) {
      destroyRequest(this._currentRequest, error);
      destroy.call(this, error);
      return this;
    };
    RedirectableRequest.prototype.write = function(data, encoding, callback) {
      if (this._ending) {
        throw new WriteAfterEndError();
      }
      if (!isString(data) && !isBuffer(data)) {
        throw new TypeError("data should be a string, Buffer or Uint8Array");
      }
      if (isFunction2(encoding)) {
        callback = encoding;
        encoding = null;
      }
      if (data.length === 0) {
        if (callback) {
          callback();
        }
        return;
      }
      if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
        this._requestBodyLength += data.length;
        this._requestBodyBuffers.push({ data, encoding });
        this._currentRequest.write(data, encoding, callback);
      } else {
        this.emit("error", new MaxBodyLengthExceededError());
        this.abort();
      }
    };
    RedirectableRequest.prototype.end = function(data, encoding, callback) {
      if (isFunction2(data)) {
        callback = data;
        data = encoding = null;
      } else if (isFunction2(encoding)) {
        callback = encoding;
        encoding = null;
      }
      if (!data) {
        this._ended = this._ending = true;
        this._currentRequest.end(null, null, callback);
      } else {
        var self2 = this;
        var currentRequest = this._currentRequest;
        this.write(data, encoding, function() {
          self2._ended = true;
          currentRequest.end(null, null, callback);
        });
        this._ending = true;
      }
    };
    RedirectableRequest.prototype.setHeader = function(name, value) {
      this._options.headers[name] = value;
      this._currentRequest.setHeader(name, value);
    };
    RedirectableRequest.prototype.removeHeader = function(name) {
      delete this._options.headers[name];
      this._currentRequest.removeHeader(name);
    };
    RedirectableRequest.prototype.setTimeout = function(msecs, callback) {
      var self2 = this;
      function destroyOnTimeout(socket) {
        socket.setTimeout(msecs);
        socket.removeListener("timeout", socket.destroy);
        socket.addListener("timeout", socket.destroy);
      }
      function startTimer(socket) {
        if (self2._timeout) {
          clearTimeout(self2._timeout);
        }
        self2._timeout = setTimeout(function() {
          self2.emit("timeout");
          clearTimer();
        }, msecs);
        destroyOnTimeout(socket);
      }
      function clearTimer() {
        if (self2._timeout) {
          clearTimeout(self2._timeout);
          self2._timeout = null;
        }
        self2.removeListener("abort", clearTimer);
        self2.removeListener("error", clearTimer);
        self2.removeListener("response", clearTimer);
        self2.removeListener("close", clearTimer);
        if (callback) {
          self2.removeListener("timeout", callback);
        }
        if (!self2.socket) {
          self2._currentRequest.removeListener("socket", startTimer);
        }
      }
      if (callback) {
        this.on("timeout", callback);
      }
      if (this.socket) {
        startTimer(this.socket);
      } else {
        this._currentRequest.once("socket", startTimer);
      }
      this.on("socket", destroyOnTimeout);
      this.on("abort", clearTimer);
      this.on("error", clearTimer);
      this.on("response", clearTimer);
      this.on("close", clearTimer);
      return this;
    };
    [
      "flushHeaders",
      "getHeader",
      "setNoDelay",
      "setSocketKeepAlive"
    ].forEach(function(method) {
      RedirectableRequest.prototype[method] = function(a, b) {
        return this._currentRequest[method](a, b);
      };
    });
    ["aborted", "connection", "socket"].forEach(function(property) {
      Object.defineProperty(RedirectableRequest.prototype, property, {
        get: function() {
          return this._currentRequest[property];
        }
      });
    });
    RedirectableRequest.prototype._sanitizeOptions = function(options) {
      if (!options.headers) {
        options.headers = {};
      }
      if (options.host) {
        if (!options.hostname) {
          options.hostname = options.host;
        }
        delete options.host;
      }
      if (!options.pathname && options.path) {
        var searchPos = options.path.indexOf("?");
        if (searchPos < 0) {
          options.pathname = options.path;
        } else {
          options.pathname = options.path.substring(0, searchPos);
          options.search = options.path.substring(searchPos);
        }
      }
    };
    RedirectableRequest.prototype._performRequest = function() {
      var protocol = this._options.protocol;
      var nativeProtocol = this._options.nativeProtocols[protocol];
      if (!nativeProtocol) {
        throw new TypeError("Unsupported protocol " + protocol);
      }
      if (this._options.agents) {
        var scheme = protocol.slice(0, -1);
        this._options.agent = this._options.agents[scheme];
      }
      var request = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse);
      request._redirectable = this;
      for (var event of events) {
        request.on(event, eventHandlers[event]);
      }
      this._currentUrl = /^\//.test(this._options.path) ? url.format(this._options) : (
        // When making a request to a proxy, […]
        // a client MUST send the target URI in absolute-form […].
        this._options.path
      );
      if (this._isRedirect) {
        var i = 0;
        var self2 = this;
        var buffers = this._requestBodyBuffers;
        (function writeNext(error) {
          if (request === self2._currentRequest) {
            if (error) {
              self2.emit("error", error);
            } else if (i < buffers.length) {
              var buffer = buffers[i++];
              if (!request.finished) {
                request.write(buffer.data, buffer.encoding, writeNext);
              }
            } else if (self2._ended) {
              request.end();
            }
          }
        })();
      }
    };
    RedirectableRequest.prototype._processResponse = function(response) {
      var statusCode = response.statusCode;
      if (this._options.trackRedirects) {
        this._redirects.push({
          url: this._currentUrl,
          headers: response.headers,
          statusCode
        });
      }
      var location2 = response.headers.location;
      if (!location2 || this._options.followRedirects === false || statusCode < 300 || statusCode >= 400) {
        response.responseUrl = this._currentUrl;
        response.redirects = this._redirects;
        this.emit("response", response);
        this._requestBodyBuffers = [];
        return;
      }
      destroyRequest(this._currentRequest);
      response.destroy();
      if (++this._redirectCount > this._options.maxRedirects) {
        throw new TooManyRedirectsError();
      }
      var requestHeaders;
      var beforeRedirect = this._options.beforeRedirect;
      if (beforeRedirect) {
        requestHeaders = Object.assign({
          // The Host header was set by nativeProtocol.request
          Host: response.req.getHeader("host")
        }, this._options.headers);
      }
      var method = this._options.method;
      if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || // RFC7231§6.4.4: The 303 (See Other) status code indicates that
      // the server is redirecting the user agent to a different resource […]
      // A user agent can perform a retrieval request targeting that URI
      // (a GET or HEAD request if using HTTP) […]
      statusCode === 303 && !/^(?:GET|HEAD)$/.test(this._options.method)) {
        this._options.method = "GET";
        this._requestBodyBuffers = [];
        removeMatchingHeaders(/^content-/i, this._options.headers);
      }
      var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
      var currentUrlParts = parseUrl(this._currentUrl);
      var currentHost = currentHostHeader || currentUrlParts.host;
      var currentUrl = /^\w+:/.test(location2) ? this._currentUrl : url.format(Object.assign(currentUrlParts, { host: currentHost }));
      var redirectUrl = resolveUrl(location2, currentUrl);
      debug("redirecting to", redirectUrl.href);
      this._isRedirect = true;
      spreadUrlObject(redirectUrl, this._options);
      if (redirectUrl.protocol !== currentUrlParts.protocol && redirectUrl.protocol !== "https:" || redirectUrl.host !== currentHost && !isSubdomain(redirectUrl.host, currentHost)) {
        removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers);
      }
      if (isFunction2(beforeRedirect)) {
        var responseDetails = {
          headers: response.headers,
          statusCode
        };
        var requestDetails = {
          url: currentUrl,
          method,
          headers: requestHeaders
        };
        beforeRedirect(this._options, responseDetails, requestDetails);
        this._sanitizeOptions(this._options);
      }
      this._performRequest();
    };
    function wrap2(protocols) {
      var exports3 = {
        maxRedirects: 21,
        maxBodyLength: 10 * 1024 * 1024
      };
      var nativeProtocols = {};
      Object.keys(protocols).forEach(function(scheme) {
        var protocol = scheme + ":";
        var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
        var wrappedProtocol = exports3[scheme] = Object.create(nativeProtocol);
        function request(input, options, callback) {
          if (isURL(input)) {
            input = spreadUrlObject(input);
          } else if (isString(input)) {
            input = spreadUrlObject(parseUrl(input));
          } else {
            callback = options;
            options = validateUrl(input);
            input = { protocol };
          }
          if (isFunction2(options)) {
            callback = options;
            options = null;
          }
          options = Object.assign({
            maxRedirects: exports3.maxRedirects,
            maxBodyLength: exports3.maxBodyLength
          }, input, options);
          options.nativeProtocols = nativeProtocols;
          if (!isString(options.host) && !isString(options.hostname)) {
            options.hostname = "::1";
          }
          assert.equal(options.protocol, protocol, "protocol mismatch");
          debug("options", options);
          return new RedirectableRequest(options, callback);
        }
        function get(input, options, callback) {
          var wrappedRequest = wrappedProtocol.request(input, options, callback);
          wrappedRequest.end();
          return wrappedRequest;
        }
        Object.defineProperties(wrappedProtocol, {
          request: { value: request, configurable: true, enumerable: true, writable: true },
          get: { value: get, configurable: true, enumerable: true, writable: true }
        });
      });
      return exports3;
    }
    function noop() {
    }
    function parseUrl(input) {
      var parsed;
      if (useNativeURL) {
        parsed = new URL2(input);
      } else {
        parsed = validateUrl(url.parse(input));
        if (!isString(parsed.protocol)) {
          throw new InvalidUrlError({ input });
        }
      }
      return parsed;
    }
    function resolveUrl(relative2, base) {
      return useNativeURL ? new URL2(relative2, base) : parseUrl(url.resolve(base, relative2));
    }
    function validateUrl(input) {
      if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) {
        throw new InvalidUrlError({ input: input.href || input });
      }
      if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) {
        throw new InvalidUrlError({ input: input.href || input });
      }
      return input;
    }
    function spreadUrlObject(urlObject, target) {
      var spread = target || {};
      for (var key of preservedUrlFields) {
        spread[key] = urlObject[key];
      }
      if (spread.hostname.startsWith("[")) {
        spread.hostname = spread.hostname.slice(1, -1);
      }
      if (spread.port !== "") {
        spread.port = Number(spread.port);
      }
      spread.path = spread.search ? spread.pathname + spread.search : spread.pathname;
      return spread;
    }
    function removeMatchingHeaders(regex, headers) {
      var lastValue;
      for (var header in headers) {
        if (regex.test(header)) {
          lastValue = headers[header];
          delete headers[header];
        }
      }
      return lastValue === null || typeof lastValue === "undefined" ? void 0 : String(lastValue).trim();
    }
    function createErrorType(code, message, baseClass) {
      function CustomError(properties) {
        if (isFunction2(Error.captureStackTrace)) {
          Error.captureStackTrace(this, this.constructor);
        }
        Object.assign(this, properties || {});
        this.code = code;
        this.message = this.cause ? message + ": " + this.cause.message : message;
      }
      CustomError.prototype = new (baseClass || Error)();
      Object.defineProperties(CustomError.prototype, {
        constructor: {
          value: CustomError,
          enumerable: false
        },
        name: {
          value: "Error [" + code + "]",
          enumerable: false
        }
      });
      return CustomError;
    }
    function destroyRequest(request, error) {
      for (var event of events) {
        request.removeListener(event, eventHandlers[event]);
      }
      request.on("error", noop);
      request.destroy(error);
    }
    function isSubdomain(subdomain, domain) {
      assert(isString(subdomain) && isString(domain));
      var dot = subdomain.length - domain.length - 1;
      return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
    }
    function isString(value) {
      return typeof value === "string" || value instanceof String;
    }
    function isFunction2(value) {
      return typeof value === "function";
    }
    function isBuffer(value) {
      return typeof value === "object" && "length" in value;
    }
    function isURL(value) {
      return URL2 && value instanceof URL2;
    }
    module2.exports = wrap2({ http, https });
    module2.exports.wrap = wrap2;
  }
});

// node_modules/axios/dist/node/axios.cjs
var require_axios = __commonJS({
  "node_modules/axios/dist/node/axios.cjs"(exports2, module2) {
    "use strict";
    init_prefix();
    var FormData$1 = require_form_data();
    var crypto = require("crypto");
    var url = require("url");
    var http = require("http");
    var https = require("https");
    var http2 = require("http2");
    var util = require("util");
    var followRedirects = require_follow_redirects();
    var zlib = require("zlib");
    var stream = require("stream");
    var events = require("events");
    function bind(fn, thisArg) {
      return function wrap2() {
        return fn.apply(thisArg, arguments);
      };
    }
    var {
      toString
    } = Object.prototype;
    var {
      getPrototypeOf
    } = Object;
    var {
      iterator,
      toStringTag
    } = Symbol;
    var kindOf = /* @__PURE__ */ ((cache) => (thing) => {
      const str = toString.call(thing);
      return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
    })(/* @__PURE__ */ Object.create(null));
    var kindOfTest = (type) => {
      type = type.toLowerCase();
      return (thing) => kindOf(thing) === type;
    };
    var typeOfTest = (type) => (thing) => typeof thing === type;
    var {
      isArray
    } = Array;
    var isUndefined = typeOfTest("undefined");
    function isBuffer(val) {
      return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction$1(val.constructor.isBuffer) && val.constructor.isBuffer(val);
    }
    var isArrayBuffer = kindOfTest("ArrayBuffer");
    function isArrayBufferView(val) {
      let result;
      if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
        result = ArrayBuffer.isView(val);
      } else {
        result = val && val.buffer && isArrayBuffer(val.buffer);
      }
      return result;
    }
    var isString = typeOfTest("string");
    var isFunction$1 = typeOfTest("function");
    var isNumber = typeOfTest("number");
    var isObject = (thing) => thing !== null && typeof thing === "object";
    var isBoolean2 = (thing) => thing === true || thing === false;
    var isPlainObject = (val) => {
      if (kindOf(val) !== "object") {
        return false;
      }
      const prototype2 = getPrototypeOf(val);
      return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(toStringTag in val) && !(iterator in val);
    };
    var isEmptyObject = (val) => {
      if (!isObject(val) || isBuffer(val)) {
        return false;
      }
      try {
        return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
      } catch (e) {
        return false;
      }
    };
    var isDate = kindOfTest("Date");
    var isFile = kindOfTest("File");
    var isReactNativeBlob = (value) => {
      return !!(value && typeof value.uri !== "undefined");
    };
    var isReactNative = (formData) => formData && typeof formData.getParts !== "undefined";
    var isBlob = kindOfTest("Blob");
    var isFileList = kindOfTest("FileList");
    var isStream = (val) => isObject(val) && isFunction$1(val.pipe);
    function getGlobal() {
      if (typeof globalThis !== "undefined") return globalThis;
      if (typeof self !== "undefined") return self;
      if (typeof window !== "undefined") return window;
      if (typeof global !== "undefined") return global;
      return {};
    }
    var G = getGlobal();
    var FormDataCtor = typeof G.FormData !== "undefined" ? G.FormData : void 0;
    var isFormData = (thing) => {
      let kind;
      return thing && (FormDataCtor && thing instanceof FormDataCtor || isFunction$1(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance
      kind === "object" && isFunction$1(thing.toString) && thing.toString() === "[object FormData]"));
    };
    var isURLSearchParams = kindOfTest("URLSearchParams");
    var [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest);
    var trim = (str) => {
      return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
    };
    function forEach(obj, fn, {
      allOwnKeys = false
    } = {}) {
      if (obj === null || typeof obj === "undefined") {
        return;
      }
      let i;
      let l;
      if (typeof obj !== "object") {
        obj = [obj];
      }
      if (isArray(obj)) {
        for (i = 0, l = obj.length; i < l; i++) {
          fn.call(null, obj[i], i, obj);
        }
      } else {
        if (isBuffer(obj)) {
          return;
        }
        const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
        const len = keys.length;
        let key;
        for (i = 0; i < len; i++) {
          key = keys[i];
          fn.call(null, obj[key], key, obj);
        }
      }
    }
    function findKey(obj, key) {
      if (isBuffer(obj)) {
        return null;
      }
      key = key.toLowerCase();
      const keys = Object.keys(obj);
      let i = keys.length;
      let _key;
      while (i-- > 0) {
        _key = keys[i];
        if (key === _key.toLowerCase()) {
          return _key;
        }
      }
      return null;
    }
    var _global = (() => {
      if (typeof globalThis !== "undefined") return globalThis;
      return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global;
    })();
    var isContextDefined = (context) => !isUndefined(context) && context !== _global;
    function merge() {
      const {
        caseless,
        skipUndefined
      } = isContextDefined(this) && this || {};
      const result = {};
      const assignValue = (val, key) => {
        if (key === "__proto__" || key === "constructor" || key === "prototype") {
          return;
        }
        const targetKey = caseless && findKey(result, key) || key;
        if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
          result[targetKey] = merge(result[targetKey], val);
        } else if (isPlainObject(val)) {
          result[targetKey] = merge({}, val);
        } else if (isArray(val)) {
          result[targetKey] = val.slice();
        } else if (!skipUndefined || !isUndefined(val)) {
          result[targetKey] = val;
        }
      };
      for (let i = 0, l = arguments.length; i < l; i++) {
        arguments[i] && forEach(arguments[i], assignValue);
      }
      return result;
    }
    var extend = (a, b, thisArg, {
      allOwnKeys
    } = {}) => {
      forEach(b, (val, key) => {
        if (thisArg && isFunction$1(val)) {
          Object.defineProperty(a, key, {
            value: bind(val, thisArg),
            writable: true,
            enumerable: true,
            configurable: true
          });
        } else {
          Object.defineProperty(a, key, {
            value: val,
            writable: true,
            enumerable: true,
            configurable: true
          });
        }
      }, {
        allOwnKeys
      });
      return a;
    };
    var stripBOM = (content) => {
      if (content.charCodeAt(0) === 65279) {
        content = content.slice(1);
      }
      return content;
    };
    var inherits = (constructor, superConstructor, props, descriptors) => {
      constructor.prototype = Object.create(superConstructor.prototype, descriptors);
      Object.defineProperty(constructor.prototype, "constructor", {
        value: constructor,
        writable: true,
        enumerable: false,
        configurable: true
      });
      Object.defineProperty(constructor, "super", {
        value: superConstructor.prototype
      });
      props && Object.assign(constructor.prototype, props);
    };
    var toFlatObject = (sourceObj, destObj, filter, propFilter) => {
      let props;
      let i;
      let prop;
      const merged = {};
      destObj = destObj || {};
      if (sourceObj == null) return destObj;
      do {
        props = Object.getOwnPropertyNames(sourceObj);
        i = props.length;
        while (i-- > 0) {
          prop = props[i];
          if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
            destObj[prop] = sourceObj[prop];
            merged[prop] = true;
          }
        }
        sourceObj = filter !== false && getPrototypeOf(sourceObj);
      } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
      return destObj;
    };
    var endsWith = (str, searchString, position) => {
      str = String(str);
      if (position === void 0 || position > str.length) {
        position = str.length;
      }
      position -= searchString.length;
      const lastIndex = str.indexOf(searchString, position);
      return lastIndex !== -1 && lastIndex === position;
    };
    var toArray = (thing) => {
      if (!thing) return null;
      if (isArray(thing)) return thing;
      let i = thing.length;
      if (!isNumber(i)) return null;
      const arr = new Array(i);
      while (i-- > 0) {
        arr[i] = thing[i];
      }
      return arr;
    };
    var isTypedArray = /* @__PURE__ */ ((TypedArray) => {
      return (thing) => {
        return TypedArray && thing instanceof TypedArray;
      };
    })(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));
    var forEachEntry = (obj, fn) => {
      const generator = obj && obj[iterator];
      const _iterator = generator.call(obj);
      let result;
      while ((result = _iterator.next()) && !result.done) {
        const pair = result.value;
        fn.call(obj, pair[0], pair[1]);
      }
    };
    var matchAll = (regExp, str) => {
      let matches;
      const arr = [];
      while ((matches = regExp.exec(str)) !== null) {
        arr.push(matches);
      }
      return arr;
    };
    var isHTMLForm = kindOfTest("HTMLFormElement");
    var toCamelCase = (str) => {
      return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {
        return p1.toUpperCase() + p2;
      });
    };
    var hasOwnProperty = (({
      hasOwnProperty: hasOwnProperty2
    }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype);
    var isRegExp = kindOfTest("RegExp");
    var reduceDescriptors = (obj, reducer) => {
      const descriptors = Object.getOwnPropertyDescriptors(obj);
      const reducedDescriptors = {};
      forEach(descriptors, (descriptor, name) => {
        let ret;
        if ((ret = reducer(descriptor, name, obj)) !== false) {
          reducedDescriptors[name] = ret || descriptor;
        }
      });
      Object.defineProperties(obj, reducedDescriptors);
    };
    var freezeMethods = (obj) => {
      reduceDescriptors(obj, (descriptor, name) => {
        if (isFunction$1(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) {
          return false;
        }
        const value = obj[name];
        if (!isFunction$1(value)) return;
        descriptor.enumerable = false;
        if ("writable" in descriptor) {
          descriptor.writable = false;
          return;
        }
        if (!descriptor.set) {
          descriptor.set = () => {
            throw Error("Can not rewrite read-only method '" + name + "'");
          };
        }
      });
    };
    var toObjectSet = (arrayOrString, delimiter) => {
      const obj = {};
      const define2 = (arr) => {
        arr.forEach((value) => {
          obj[value] = true;
        });
      };
      isArray(arrayOrString) ? define2(arrayOrString) : define2(String(arrayOrString).split(delimiter));
      return obj;
    };
    var noop = () => {
    };
    var toFiniteNumber = (value, defaultValue) => {
      return value != null && Number.isFinite(value = +value) ? value : defaultValue;
    };
    function isSpecCompliantForm(thing) {
      return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]);
    }
    var toJSONObject = (obj) => {
      const stack = new Array(10);
      const visit = (source, i) => {
        if (isObject(source)) {
          if (stack.indexOf(source) >= 0) {
            return;
          }
          if (isBuffer(source)) {
            return source;
          }
          if (!("toJSON" in source)) {
            stack[i] = source;
            const target = isArray(source) ? [] : {};
            forEach(source, (value, key) => {
              const reducedValue = visit(value, i + 1);
              !isUndefined(reducedValue) && (target[key] = reducedValue);
            });
            stack[i] = void 0;
            return target;
          }
        }
        return source;
      };
      return visit(obj, 0);
    };
    var isAsyncFn = kindOfTest("AsyncFunction");
    var isThenable = (thing) => thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch);
    var _setImmediate = ((setImmediateSupported, postMessageSupported) => {
      if (setImmediateSupported) {
        return setImmediate;
      }
      return postMessageSupported ? ((token, callbacks) => {
        _global.addEventListener("message", ({
          source,
          data
        }) => {
          if (source === _global && data === token) {
            callbacks.length && callbacks.shift()();
          }
        }, false);
        return (cb) => {
          callbacks.push(cb);
          _global.postMessage(token, "*");
        };
      })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
    })(typeof setImmediate === "function", isFunction$1(_global.postMessage));
    var asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate;
    var isIterable = (thing) => thing != null && isFunction$1(thing[iterator]);
    var utils$1 = {
      isArray,
      isArrayBuffer,
      isBuffer,
      isFormData,
      isArrayBufferView,
      isString,
      isNumber,
      isBoolean: isBoolean2,
      isObject,
      isPlainObject,
      isEmptyObject,
      isReadableStream,
      isRequest,
      isResponse,
      isHeaders,
      isUndefined,
      isDate,
      isFile,
      isReactNativeBlob,
      isReactNative,
      isBlob,
      isRegExp,
      isFunction: isFunction$1,
      isStream,
      isURLSearchParams,
      isTypedArray,
      isFileList,
      forEach,
      merge,
      extend,
      trim,
      stripBOM,
      inherits,
      toFlatObject,
      kindOf,
      kindOfTest,
      endsWith,
      toArray,
      forEachEntry,
      matchAll,
      isHTMLForm,
      hasOwnProperty,
      hasOwnProp: hasOwnProperty,
      // an alias to avoid ESLint no-prototype-builtins detection
      reduceDescriptors,
      freezeMethods,
      toObjectSet,
      toCamelCase,
      noop,
      toFiniteNumber,
      findKey,
      global: _global,
      isContextDefined,
      isSpecCompliantForm,
      toJSONObject,
      isAsyncFn,
      isThenable,
      setImmediate: _setImmediate,
      asap,
      isIterable
    };
    var AxiosError = class _AxiosError extends Error {
      static from(error, code, config2, request, response, customProps) {
        const axiosError = new _AxiosError(error.message, code || error.code, config2, request, response);
        axiosError.cause = error;
        axiosError.name = error.name;
        if (error.status != null && axiosError.status == null) {
          axiosError.status = error.status;
        }
        customProps && Object.assign(axiosError, customProps);
        return axiosError;
      }
      /**
       * Create an Error with the specified message, config, error code, request and response.
       *
       * @param {string} message The error message.
       * @param {string} [code] The error code (for example, 'ECONNABORTED').
       * @param {Object} [config] The config.
       * @param {Object} [request] The request.
       * @param {Object} [response] The response.
       *
       * @returns {Error} The created error.
       */
      constructor(message, code, config2, request, response) {
        super(message);
        Object.defineProperty(this, "message", {
          value: message,
          enumerable: true,
          writable: true,
          configurable: true
        });
        this.name = "AxiosError";
        this.isAxiosError = true;
        code && (this.code = code);
        config2 && (this.config = config2);
        request && (this.request = request);
        if (response) {
          this.response = response;
          this.status = response.status;
        }
      }
      toJSON() {
        return {
          // Standard
          message: this.message,
          name: this.name,
          // Microsoft
          description: this.description,
          number: this.number,
          // Mozilla
          fileName: this.fileName,
          lineNumber: this.lineNumber,
          columnNumber: this.columnNumber,
          stack: this.stack,
          // Axios
          config: utils$1.toJSONObject(this.config),
          code: this.code,
          status: this.status
        };
      }
    };
    AxiosError.ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";
    AxiosError.ERR_BAD_OPTION = "ERR_BAD_OPTION";
    AxiosError.ECONNABORTED = "ECONNABORTED";
    AxiosError.ETIMEDOUT = "ETIMEDOUT";
    AxiosError.ERR_NETWORK = "ERR_NETWORK";
    AxiosError.ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS";
    AxiosError.ERR_DEPRECATED = "ERR_DEPRECATED";
    AxiosError.ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE";
    AxiosError.ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
    AxiosError.ERR_CANCELED = "ERR_CANCELED";
    AxiosError.ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT";
    AxiosError.ERR_INVALID_URL = "ERR_INVALID_URL";
    function isVisitable(thing) {
      return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
    }
    function removeBrackets(key) {
      return utils$1.endsWith(key, "[]") ? key.slice(0, -2) : key;
    }
    function renderKey(path2, key, dots) {
      if (!path2) return key;
      return path2.concat(key).map(function each(token, i) {
        token = removeBrackets(token);
        return !dots && i ? "[" + token + "]" : token;
      }).join(dots ? "." : "");
    }
    function isFlatArray(arr) {
      return utils$1.isArray(arr) && !arr.some(isVisitable);
    }
    var predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
      return /^is[A-Z]/.test(prop);
    });
    function toFormData(obj, formData, options) {
      if (!utils$1.isObject(obj)) {
        throw new TypeError("target must be an object");
      }
      formData = formData || new (FormData$1 || FormData)();
      options = utils$1.toFlatObject(options, {
        metaTokens: true,
        dots: false,
        indexes: false
      }, false, function defined(option, source) {
        return !utils$1.isUndefined(source[option]);
      });
      const metaTokens = options.metaTokens;
      const visitor = options.visitor || defaultVisitor;
      const dots = options.dots;
      const indexes = options.indexes;
      const _Blob = options.Blob || typeof Blob !== "undefined" && Blob;
      const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
      if (!utils$1.isFunction(visitor)) {
        throw new TypeError("visitor must be a function");
      }
      function convertValue(value) {
        if (value === null) return "";
        if (utils$1.isDate(value)) {
          return value.toISOString();
        }
        if (utils$1.isBoolean(value)) {
          return value.toString();
        }
        if (!useBlob && utils$1.isBlob(value)) {
          throw new AxiosError("Blob is not supported. Use a Buffer instead.");
        }
        if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
          return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value);
        }
        return value;
      }
      function defaultVisitor(value, key, path2) {
        let arr = value;
        if (utils$1.isReactNative(formData) && utils$1.isReactNativeBlob(value)) {
          formData.append(renderKey(path2, key, dots), convertValue(value));
          return false;
        }
        if (value && !path2 && typeof value === "object") {
          if (utils$1.endsWith(key, "{}")) {
            key = metaTokens ? key : key.slice(0, -2);
            value = JSON.stringify(value);
          } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value))) {
            key = removeBrackets(key);
            arr.forEach(function each(el, index) {
              !(utils$1.isUndefined(el) || el === null) && formData.append(
                // eslint-disable-next-line no-nested-ternary
                indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]",
                convertValue(el)
              );
            });
            return false;
          }
        }
        if (isVisitable(value)) {
          return true;
        }
        formData.append(renderKey(path2, key, dots), convertValue(value));
        return false;
      }
      const stack = [];
      const exposedHelpers = Object.assign(predicates, {
        defaultVisitor,
        convertValue,
        isVisitable
      });
      function build(value, path2) {
        if (utils$1.isUndefined(value)) return;
        if (stack.indexOf(value) !== -1) {
          throw Error("Circular reference detected in " + path2.join("."));
        }
        stack.push(value);
        utils$1.forEach(value, function each(el, key) {
          const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path2, exposedHelpers);
          if (result === true) {
            build(el, path2 ? path2.concat(key) : [key]);
          }
        });
        stack.pop();
      }
      if (!utils$1.isObject(obj)) {
        throw new TypeError("data must be an object");
      }
      build(obj);
      return formData;
    }
    function encode$1(str) {
      const charMap = {
        "!": "%21",
        "'": "%27",
        "(": "%28",
        ")": "%29",
        "~": "%7E",
        "%20": "+",
        "%00": "\0"
      };
      return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
        return charMap[match];
      });
    }
    function AxiosURLSearchParams(params, options) {
      this._pairs = [];
      params && toFormData(params, this, options);
    }
    var prototype = AxiosURLSearchParams.prototype;
    prototype.append = function append(name, value) {
      this._pairs.push([name, value]);
    };
    prototype.toString = function toString2(encoder) {
      const _encode = encoder ? function(value) {
        return encoder.call(this, value, encode$1);
      } : encode$1;
      return this._pairs.map(function each(pair) {
        return _encode(pair[0]) + "=" + _encode(pair[1]);
      }, "").join("&");
    };
    function encode(val) {
      return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+");
    }
    function buildURL(url2, params, options) {
      if (!params) {
        return url2;
      }
      const _encode = options && options.encode || encode;
      const _options = utils$1.isFunction(options) ? {
        serialize: options
      } : options;
      const serializeFn = _options && _options.serialize;
      let serializedParams;
      if (serializeFn) {
        serializedParams = serializeFn(params, _options);
      } else {
        serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, _options).toString(_encode);
      }
      if (serializedParams) {
        const hashmarkIndex = url2.indexOf("#");
        if (hashmarkIndex !== -1) {
          url2 = url2.slice(0, hashmarkIndex);
        }
        url2 += (url2.indexOf("?") === -1 ? "?" : "&") + serializedParams;
      }
      return url2;
    }
    var InterceptorManager = class {
      constructor() {
        this.handlers = [];
      }
      /**
       * Add a new interceptor to the stack
       *
       * @param {Function} fulfilled The function to handle `then` for a `Promise`
       * @param {Function} rejected The function to handle `reject` for a `Promise`
       * @param {Object} options The options for the interceptor, synchronous and runWhen
       *
       * @return {Number} An ID used to remove interceptor later
       */
      use(fulfilled, rejected, options) {
        this.handlers.push({
          fulfilled,
          rejected,
          synchronous: options ? options.synchronous : false,
          runWhen: options ? options.runWhen : null
        });
        return this.handlers.length - 1;
      }
      /**
       * Remove an interceptor from the stack
       *
       * @param {Number} id The ID that was returned by `use`
       *
       * @returns {void}
       */
      eject(id) {
        if (this.handlers[id]) {
          this.handlers[id] = null;
        }
      }
      /**
       * Clear all interceptors from the stack
       *
       * @returns {void}
       */
      clear() {
        if (this.handlers) {
          this.handlers = [];
        }
      }
      /**
       * Iterate over all the registered interceptors
       *
       * This method is particularly useful for skipping over any
       * interceptors that may have become `null` calling `eject`.
       *
       * @param {Function} fn The function to call for each interceptor
       *
       * @returns {void}
       */
      forEach(fn) {
        utils$1.forEach(this.handlers, function forEachHandler(h) {
          if (h !== null) {
            fn(h);
          }
        });
      }
    };
    var transitionalDefaults = {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false,
      legacyInterceptorReqResOrdering: true
    };
    var URLSearchParams = url.URLSearchParams;
    var ALPHA = "abcdefghijklmnopqrstuvwxyz";
    var DIGIT = "0123456789";
    var ALPHABET = {
      DIGIT,
      ALPHA,
      ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
    };
    var generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
      let str = "";
      const {
        length
      } = alphabet;
      const randomValues = new Uint32Array(size);
      crypto.randomFillSync(randomValues);
      for (let i = 0; i < size; i++) {
        str += alphabet[randomValues[i] % length];
      }
      return str;
    };
    var platform$1 = {
      isNode: true,
      classes: {
        URLSearchParams,
        FormData: FormData$1,
        Blob: typeof Blob !== "undefined" && Blob || null
      },
      ALPHABET,
      generateString,
      protocols: ["http", "https", "file", "data"]
    };
    var hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined";
    var _navigator = typeof navigator === "object" && navigator || void 0;
    var hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator.product) < 0);
    var hasStandardBrowserWebWorkerEnv = (() => {
      return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef
      self instanceof WorkerGlobalScope && typeof self.importScripts === "function";
    })();
    var origin = hasBrowserEnv && window.location.href || "http://localhost";
    var utils = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      hasBrowserEnv,
      hasStandardBrowserEnv,
      hasStandardBrowserWebWorkerEnv,
      navigator: _navigator,
      origin
    });
    var platform = {
      ...utils,
      ...platform$1
    };
    function toURLEncodedForm(data, options) {
      return toFormData(data, new platform.classes.URLSearchParams(), {
        visitor: function(value, key, path2, helpers) {
          if (platform.isNode && utils$1.isBuffer(value)) {
            this.append(key, value.toString("base64"));
            return false;
          }
          return helpers.defaultVisitor.apply(this, arguments);
        },
        ...options
      });
    }
    function parsePropPath(name) {
      return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map((match) => {
        return match[0] === "[]" ? "" : match[1] || match[0];
      });
    }
    function arrayToObject(arr) {
      const obj = {};
      const keys = Object.keys(arr);
      let i;
      const len = keys.length;
      let key;
      for (i = 0; i < len; i++) {
        key = keys[i];
        obj[key] = arr[key];
      }
      return obj;
    }
    function formDataToJSON(formData) {
      function buildPath(path2, value, target, index) {
        let name = path2[index++];
        if (name === "__proto__") return true;
        const isNumericKey = Number.isFinite(+name);
        const isLast = index >= path2.length;
        name = !name && utils$1.isArray(target) ? target.length : name;
        if (isLast) {
          if (utils$1.hasOwnProp(target, name)) {
            target[name] = [target[name], value];
          } else {
            target[name] = value;
          }
          return !isNumericKey;
        }
        if (!target[name] || !utils$1.isObject(target[name])) {
          target[name] = [];
        }
        const result = buildPath(path2, value, target[name], index);
        if (result && utils$1.isArray(target[name])) {
          target[name] = arrayToObject(target[name]);
        }
        return !isNumericKey;
      }
      if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
        const obj = {};
        utils$1.forEachEntry(formData, (name, value) => {
          buildPath(parsePropPath(name), value, obj, 0);
        });
        return obj;
      }
      return null;
    }
    function stringifySafely(rawValue, parser2, encoder) {
      if (utils$1.isString(rawValue)) {
        try {
          (parser2 || JSON.parse)(rawValue);
          return utils$1.trim(rawValue);
        } catch (e) {
          if (e.name !== "SyntaxError") {
            throw e;
          }
        }
      }
      return (encoder || JSON.stringify)(rawValue);
    }
    var defaults = {
      transitional: transitionalDefaults,
      adapter: ["xhr", "http", "fetch"],
      transformRequest: [function transformRequest(data, headers) {
        const contentType = headers.getContentType() || "";
        const hasJSONContentType = contentType.indexOf("application/json") > -1;
        const isObjectPayload = utils$1.isObject(data);
        if (isObjectPayload && utils$1.isHTMLForm(data)) {
          data = new FormData(data);
        }
        const isFormData2 = utils$1.isFormData(data);
        if (isFormData2) {
          return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
        }
        if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data) || utils$1.isReadableStream(data)) {
          return data;
        }
        if (utils$1.isArrayBufferView(data)) {
          return data.buffer;
        }
        if (utils$1.isURLSearchParams(data)) {
          headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false);
          return data.toString();
        }
        let isFileList2;
        if (isObjectPayload) {
          if (contentType.indexOf("application/x-www-form-urlencoded") > -1) {
            return toURLEncodedForm(data, this.formSerializer).toString();
          }
          if ((isFileList2 = utils$1.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) {
            const _FormData = this.env && this.env.FormData;
            return toFormData(isFileList2 ? {
              "files[]": data
            } : data, _FormData && new _FormData(), this.formSerializer);
          }
        }
        if (isObjectPayload || hasJSONContentType) {
          headers.setContentType("application/json", false);
          return stringifySafely(data);
        }
        return data;
      }],
      transformResponse: [function transformResponse(data) {
        const transitional = this.transitional || defaults.transitional;
        const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
        const JSONRequested = this.responseType === "json";
        if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
          return data;
        }
        if (data && utils$1.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) {
          const silentJSONParsing = transitional && transitional.silentJSONParsing;
          const strictJSONParsing = !silentJSONParsing && JSONRequested;
          try {
            return JSON.parse(data, this.parseReviver);
          } catch (e) {
            if (strictJSONParsing) {
              if (e.name === "SyntaxError") {
                throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
              }
              throw e;
            }
          }
        }
        return data;
      }],
      /**
       * A timeout in milliseconds to abort a request. If set to 0 (default) a
       * timeout is not created.
       */
      timeout: 0,
      xsrfCookieName: "XSRF-TOKEN",
      xsrfHeaderName: "X-XSRF-TOKEN",
      maxContentLength: -1,
      maxBodyLength: -1,
      env: {
        FormData: platform.classes.FormData,
        Blob: platform.classes.Blob
      },
      validateStatus: function validateStatus(status) {
        return status >= 200 && status < 300;
      },
      headers: {
        common: {
          Accept: "application/json, text/plain, */*",
          "Content-Type": void 0
        }
      }
    };
    utils$1.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => {
      defaults.headers[method] = {};
    });
    var ignoreDuplicateOf = utils$1.toObjectSet(["age", "authorization", "content-length", "content-type", "etag", "expires", "from", "host", "if-modified-since", "if-unmodified-since", "last-modified", "location", "max-forwards", "proxy-authorization", "referer", "retry-after", "user-agent"]);
    var parseHeaders = (rawHeaders) => {
      const parsed = {};
      let key;
      let val;
      let i;
      rawHeaders && rawHeaders.split("\n").forEach(function parser2(line) {
        i = line.indexOf(":");
        key = line.substring(0, i).trim().toLowerCase();
        val = line.substring(i + 1).trim();
        if (!key || parsed[key] && ignoreDuplicateOf[key]) {
          return;
        }
        if (key === "set-cookie") {
          if (parsed[key]) {
            parsed[key].push(val);
          } else {
            parsed[key] = [val];
          }
        } else {
          parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
        }
      });
      return parsed;
    };
    var $internals = /* @__PURE__ */ Symbol("internals");
    var isValidHeaderValue = (value) => !/[\r\n]/.test(value);
    function assertValidHeaderValue(value, header) {
      if (value === false || value == null) {
        return;
      }
      if (utils$1.isArray(value)) {
        value.forEach((v) => assertValidHeaderValue(v, header));
        return;
      }
      if (!isValidHeaderValue(String(value))) {
        throw new Error(`Invalid character in header content ["${header}"]`);
      }
    }
    function normalizeHeader(header) {
      return header && String(header).trim().toLowerCase();
    }
    function stripTrailingCRLF(str) {
      let end = str.length;
      while (end > 0) {
        const charCode = str.charCodeAt(end - 1);
        if (charCode !== 10 && charCode !== 13) {
          break;
        }
        end -= 1;
      }
      return end === str.length ? str : str.slice(0, end);
    }
    function normalizeValue(value) {
      if (value === false || value == null) {
        return value;
      }
      return utils$1.isArray(value) ? value.map(normalizeValue) : stripTrailingCRLF(String(value));
    }
    function parseTokens(str) {
      const tokens = /* @__PURE__ */ Object.create(null);
      const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
      let match;
      while (match = tokensRE.exec(str)) {
        tokens[match[1]] = match[2];
      }
      return tokens;
    }
    var isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
    function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
      if (utils$1.isFunction(filter)) {
        return filter.call(this, value, header);
      }
      if (isHeaderNameFilter) {
        value = header;
      }
      if (!utils$1.isString(value)) return;
      if (utils$1.isString(filter)) {
        return value.indexOf(filter) !== -1;
      }
      if (utils$1.isRegExp(filter)) {
        return filter.test(value);
      }
    }
    function formatHeader(header) {
      return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
        return char.toUpperCase() + str;
      });
    }
    function buildAccessors(obj, header) {
      const accessorName = utils$1.toCamelCase(" " + header);
      ["get", "set", "has"].forEach((methodName) => {
        Object.defineProperty(obj, methodName + accessorName, {
          value: function(arg1, arg2, arg3) {
            return this[methodName].call(this, header, arg1, arg2, arg3);
          },
          configurable: true
        });
      });
    }
    var AxiosHeaders = class {
      constructor(headers) {
        headers && this.set(headers);
      }
      set(header, valueOrRewrite, rewrite) {
        const self2 = this;
        function setHeader(_value, _header, _rewrite) {
          const lHeader = normalizeHeader(_header);
          if (!lHeader) {
            throw new Error("header name must be a non-empty string");
          }
          const key = utils$1.findKey(self2, lHeader);
          if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) {
            assertValidHeaderValue(_value, _header);
            self2[key || _header] = normalizeValue(_value);
          }
        }
        const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
        if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
          setHeaders(header, valueOrRewrite);
        } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
          setHeaders(parseHeaders(header), valueOrRewrite);
        } else if (utils$1.isObject(header) && utils$1.isIterable(header)) {
          let obj = {}, dest, key;
          for (const entry of header) {
            if (!utils$1.isArray(entry)) {
              throw TypeError("Object iterator must return a key-value pair");
            }
            obj[key = entry[0]] = (dest = obj[key]) ? utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1];
          }
          setHeaders(obj, valueOrRewrite);
        } else {
          header != null && setHeader(valueOrRewrite, header, rewrite);
        }
        return this;
      }
      get(header, parser2) {
        header = normalizeHeader(header);
        if (header) {
          const key = utils$1.findKey(this, header);
          if (key) {
            const value = this[key];
            if (!parser2) {
              return value;
            }
            if (parser2 === true) {
              return parseTokens(value);
            }
            if (utils$1.isFunction(parser2)) {
              return parser2.call(this, value, key);
            }
            if (utils$1.isRegExp(parser2)) {
              return parser2.exec(value);
            }
            throw new TypeError("parser must be boolean|regexp|function");
          }
        }
      }
      has(header, matcher) {
        header = normalizeHeader(header);
        if (header) {
          const key = utils$1.findKey(this, header);
          return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
        }
        return false;
      }
      delete(header, matcher) {
        const self2 = this;
        let deleted = false;
        function deleteHeader(_header) {
          _header = normalizeHeader(_header);
          if (_header) {
            const key = utils$1.findKey(self2, _header);
            if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) {
              delete self2[key];
              deleted = true;
            }
          }
        }
        if (utils$1.isArray(header)) {
          header.forEach(deleteHeader);
        } else {
          deleteHeader(header);
        }
        return deleted;
      }
      clear(matcher) {
        const keys = Object.keys(this);
        let i = keys.length;
        let deleted = false;
        while (i--) {
          const key = keys[i];
          if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
            delete this[key];
            deleted = true;
          }
        }
        return deleted;
      }
      normalize(format3) {
        const self2 = this;
        const headers = {};
        utils$1.forEach(this, (value, header) => {
          const key = utils$1.findKey(headers, header);
          if (key) {
            self2[key] = normalizeValue(value);
            delete self2[header];
            return;
          }
          const normalized = format3 ? formatHeader(header) : String(header).trim();
          if (normalized !== header) {
            delete self2[header];
          }
          self2[normalized] = normalizeValue(value);
          headers[normalized] = true;
        });
        return this;
      }
      concat(...targets) {
        return this.constructor.concat(this, ...targets);
      }
      toJSON(asStrings) {
        const obj = /* @__PURE__ */ Object.create(null);
        utils$1.forEach(this, (value, header) => {
          value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(", ") : value);
        });
        return obj;
      }
      [Symbol.iterator]() {
        return Object.entries(this.toJSON())[Symbol.iterator]();
      }
      toString() {
        return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n");
      }
      getSetCookie() {
        return this.get("set-cookie") || [];
      }
      get [Symbol.toStringTag]() {
        return "AxiosHeaders";
      }
      static from(thing) {
        return thing instanceof this ? thing : new this(thing);
      }
      static concat(first, ...targets) {
        const computed = new this(first);
        targets.forEach((target) => computed.set(target));
        return computed;
      }
      static accessor(header) {
        const internals = this[$internals] = this[$internals] = {
          accessors: {}
        };
        const accessors = internals.accessors;
        const prototype2 = this.prototype;
        function defineAccessor(_header) {
          const lHeader = normalizeHeader(_header);
          if (!accessors[lHeader]) {
            buildAccessors(prototype2, _header);
            accessors[lHeader] = true;
          }
        }
        utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
        return this;
      }
    };
    AxiosHeaders.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]);
    utils$1.reduceDescriptors(AxiosHeaders.prototype, ({
      value
    }, key) => {
      let mapped = key[0].toUpperCase() + key.slice(1);
      return {
        get: () => value,
        set(headerValue) {
          this[mapped] = headerValue;
        }
      };
    });
    utils$1.freezeMethods(AxiosHeaders);
    function transformData(fns, response) {
      const config2 = this || defaults;
      const context = response || config2;
      const headers = AxiosHeaders.from(context.headers);
      let data = context.data;
      utils$1.forEach(fns, function transform(fn) {
        data = fn.call(config2, data, headers.normalize(), response ? response.status : void 0);
      });
      headers.normalize();
      return data;
    }
    function isCancel(value) {
      return !!(value && value.__CANCEL__);
    }
    var CanceledError = class extends AxiosError {
      /**
       * A `CanceledError` is an object that is thrown when an operation is canceled.
       *
       * @param {string=} message The message.
       * @param {Object=} config The config.
       * @param {Object=} request The request.
       *
       * @returns {CanceledError} The created error.
       */
      constructor(message, config2, request) {
        super(message == null ? "canceled" : message, AxiosError.ERR_CANCELED, config2, request);
        this.name = "CanceledError";
        this.__CANCEL__ = true;
      }
    };
    function settle(resolve5, reject, response) {
      const validateStatus = response.config.validateStatus;
      if (!response.status || !validateStatus || validateStatus(response.status)) {
        resolve5(response);
      } else {
        reject(new AxiosError("Request failed with status code " + response.status, [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], response.config, response.request, response));
      }
    }
    function isAbsoluteURL(url2) {
      if (typeof url2 !== "string") {
        return false;
      }
      return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url2);
    }
    function combineURLs(baseURL, relativeURL) {
      return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
    }
    function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
      let isRelativeUrl = !isAbsoluteURL(requestedURL);
      if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
        return combineURLs(baseURL, requestedURL);
      }
      return requestedURL;
    }
    var DEFAULT_PORTS$1 = {
      ftp: 21,
      gopher: 70,
      http: 80,
      https: 443,
      ws: 80,
      wss: 443
    };
    function parseUrl(urlString) {
      try {
        return new URL(urlString);
      } catch {
        return null;
      }
    }
    function getProxyForUrl(url2) {
      var parsedUrl = (typeof url2 === "string" ? parseUrl(url2) : url2) || {};
      var proto = parsedUrl.protocol;
      var hostname = parsedUrl.host;
      var port = parsedUrl.port;
      if (typeof hostname !== "string" || !hostname || typeof proto !== "string") {
        return "";
      }
      proto = proto.split(":", 1)[0];
      hostname = hostname.replace(/:\d*$/, "");
      port = parseInt(port) || DEFAULT_PORTS$1[proto] || 0;
      if (!shouldProxy(hostname, port)) {
        return "";
      }
      var proxy = getEnv(proto + "_proxy") || getEnv("all_proxy");
      if (proxy && proxy.indexOf("://") === -1) {
        proxy = proto + "://" + proxy;
      }
      return proxy;
    }
    function shouldProxy(hostname, port) {
      var 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 !hostname.endsWith(parsedProxyHostname);
      });
    }
    function getEnv(key) {
      return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || "";
    }
    var VERSION = "1.15.0";
    function parseProtocol(url2) {
      const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url2);
      return match && match[1] || "";
    }
    var DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
    function fromDataURI(uri, asBlob, options) {
      const _Blob = options && options.Blob || platform.classes.Blob;
      const protocol = parseProtocol(uri);
      if (asBlob === void 0 && _Blob) {
        asBlob = true;
      }
      if (protocol === "data") {
        uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
        const match = DATA_URL_PATTERN.exec(uri);
        if (!match) {
          throw new AxiosError("Invalid URL", AxiosError.ERR_INVALID_URL);
        }
        const mime = match[1];
        const isBase64 = match[2];
        const body = match[3];
        const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? "base64" : "utf8");
        if (asBlob) {
          if (!_Blob) {
            throw new AxiosError("Blob is not supported", AxiosError.ERR_NOT_SUPPORT);
          }
          return new _Blob([buffer], {
            type: mime
          });
        }
        return buffer;
      }
      throw new AxiosError("Unsupported protocol " + protocol, AxiosError.ERR_NOT_SUPPORT);
    }
    var kInternals = /* @__PURE__ */ Symbol("internals");
    var AxiosTransformStream = class extends stream.Transform {
      constructor(options) {
        options = utils$1.toFlatObject(options, {
          maxRate: 0,
          chunkSize: 64 * 1024,
          minChunkSize: 100,
          timeWindow: 500,
          ticksRate: 2,
          samplesCount: 15
        }, null, (prop, source) => {
          return !utils$1.isUndefined(source[prop]);
        });
        super({
          readableHighWaterMark: options.chunkSize
        });
        const internals = this[kInternals] = {
          timeWindow: options.timeWindow,
          chunkSize: options.chunkSize,
          maxRate: options.maxRate,
          minChunkSize: options.minChunkSize,
          bytesSeen: 0,
          isCaptured: false,
          notifiedBytesLoaded: 0,
          ts: Date.now(),
          bytes: 0,
          onReadCallback: null
        };
        this.on("newListener", (event) => {
          if (event === "progress") {
            if (!internals.isCaptured) {
              internals.isCaptured = true;
            }
          }
        });
      }
      _read(size) {
        const internals = this[kInternals];
        if (internals.onReadCallback) {
          internals.onReadCallback();
        }
        return super._read(size);
      }
      _transform(chunk, encoding, callback) {
        const internals = this[kInternals];
        const maxRate = internals.maxRate;
        const readableHighWaterMark = this.readableHighWaterMark;
        const timeWindow = internals.timeWindow;
        const divider = 1e3 / timeWindow;
        const bytesThreshold = maxRate / divider;
        const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0;
        const pushChunk = (_chunk, _callback) => {
          const bytes = Buffer.byteLength(_chunk);
          internals.bytesSeen += bytes;
          internals.bytes += bytes;
          internals.isCaptured && this.emit("progress", internals.bytesSeen);
          if (this.push(_chunk)) {
            process.nextTick(_callback);
          } else {
            internals.onReadCallback = () => {
              internals.onReadCallback = null;
              process.nextTick(_callback);
            };
          }
        };
        const transformChunk = (_chunk, _callback) => {
          const chunkSize = Buffer.byteLength(_chunk);
          let chunkRemainder = null;
          let maxChunkSize = readableHighWaterMark;
          let bytesLeft;
          let passed = 0;
          if (maxRate) {
            const now = Date.now();
            if (!internals.ts || (passed = now - internals.ts) >= timeWindow) {
              internals.ts = now;
              bytesLeft = bytesThreshold - internals.bytes;
              internals.bytes = bytesLeft < 0 ? -bytesLeft : 0;
              passed = 0;
            }
            bytesLeft = bytesThreshold - internals.bytes;
          }
          if (maxRate) {
            if (bytesLeft <= 0) {
              return setTimeout(() => {
                _callback(null, _chunk);
              }, timeWindow - passed);
            }
            if (bytesLeft < maxChunkSize) {
              maxChunkSize = bytesLeft;
            }
          }
          if (maxChunkSize && chunkSize > maxChunkSize && chunkSize - maxChunkSize > minChunkSize) {
            chunkRemainder = _chunk.subarray(maxChunkSize);
            _chunk = _chunk.subarray(0, maxChunkSize);
          }
          pushChunk(_chunk, chunkRemainder ? () => {
            process.nextTick(_callback, null, chunkRemainder);
          } : _callback);
        };
        transformChunk(chunk, function transformNextChunk(err, _chunk) {
          if (err) {
            return callback(err);
          }
          if (_chunk) {
            transformChunk(_chunk, transformNextChunk);
          } else {
            callback(null);
          }
        });
      }
    };
    var {
      asyncIterator
    } = Symbol;
    var readBlob = async function* (blob) {
      if (blob.stream) {
        yield* blob.stream();
      } else if (blob.arrayBuffer) {
        yield await blob.arrayBuffer();
      } else if (blob[asyncIterator]) {
        yield* blob[asyncIterator]();
      } else {
        yield blob;
      }
    };
    var BOUNDARY_ALPHABET = platform.ALPHABET.ALPHA_DIGIT + "-_";
    var textEncoder = typeof TextEncoder === "function" ? new TextEncoder() : new util.TextEncoder();
    var CRLF = "\r\n";
    var CRLF_BYTES = textEncoder.encode(CRLF);
    var CRLF_BYTES_COUNT = 2;
    var FormDataPart = class {
      constructor(name, value) {
        const {
          escapeName
        } = this.constructor;
        const isStringValue = utils$1.isString(value);
        let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ""}${CRLF}`;
        if (isStringValue) {
          value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF));
        } else {
          headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`;
        }
        this.headers = textEncoder.encode(headers + CRLF);
        this.contentLength = isStringValue ? value.byteLength : value.size;
        this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT;
        this.name = name;
        this.value = value;
      }
      async *encode() {
        yield this.headers;
        const {
          value
        } = this;
        if (utils$1.isTypedArray(value)) {
          yield value;
        } else {
          yield* readBlob(value);
        }
        yield CRLF_BYTES;
      }
      static escapeName(name) {
        return String(name).replace(/[\r\n"]/g, (match) => ({
          "\r": "%0D",
          "\n": "%0A",
          '"': "%22"
        })[match]);
      }
    };
    var formDataToStream = (form, headersHandler, options) => {
      const {
        tag = "form-data-boundary",
        size = 25,
        boundary = tag + "-" + platform.generateString(size, BOUNDARY_ALPHABET)
      } = options || {};
      if (!utils$1.isFormData(form)) {
        throw TypeError("FormData instance required");
      }
      if (boundary.length < 1 || boundary.length > 70) {
        throw Error("boundary must be 10-70 characters long");
      }
      const boundaryBytes = textEncoder.encode("--" + boundary + CRLF);
      const footerBytes = textEncoder.encode("--" + boundary + "--" + CRLF);
      let contentLength = footerBytes.byteLength;
      const parts = Array.from(form.entries()).map(([name, value]) => {
        const part = new FormDataPart(name, value);
        contentLength += part.size;
        return part;
      });
      contentLength += boundaryBytes.byteLength * parts.length;
      contentLength = utils$1.toFiniteNumber(contentLength);
      const computedHeaders = {
        "Content-Type": `multipart/form-data; boundary=${boundary}`
      };
      if (Number.isFinite(contentLength)) {
        computedHeaders["Content-Length"] = contentLength;
      }
      headersHandler && headersHandler(computedHeaders);
      return stream.Readable.from((async function* () {
        for (const part of parts) {
          yield boundaryBytes;
          yield* part.encode();
        }
        yield footerBytes;
      })());
    };
    var ZlibHeaderTransformStream = class extends stream.Transform {
      __transform(chunk, encoding, callback) {
        this.push(chunk);
        callback();
      }
      _transform(chunk, encoding, callback) {
        if (chunk.length !== 0) {
          this._transform = this.__transform;
          if (chunk[0] !== 120) {
            const header = Buffer.alloc(2);
            header[0] = 120;
            header[1] = 156;
            this.push(header, encoding);
          }
        }
        this.__transform(chunk, encoding, callback);
      }
    };
    var callbackify = (fn, reducer) => {
      return utils$1.isAsyncFn(fn) ? function(...args2) {
        const cb = args2.pop();
        fn.apply(this, args2).then((value) => {
          try {
            reducer ? cb(null, ...reducer(value)) : cb(null, value);
          } catch (err) {
            cb(err);
          }
        }, cb);
      } : fn;
    };
    var DEFAULT_PORTS = {
      http: 80,
      https: 443,
      ws: 80,
      wss: 443,
      ftp: 21
    };
    var parseNoProxyEntry = (entry) => {
      let entryHost = entry;
      let entryPort = 0;
      if (entryHost.charAt(0) === "[") {
        const bracketIndex = entryHost.indexOf("]");
        if (bracketIndex !== -1) {
          const host = entryHost.slice(1, bracketIndex);
          const rest = entryHost.slice(bracketIndex + 1);
          if (rest.charAt(0) === ":" && /^\d+$/.test(rest.slice(1))) {
            entryPort = Number.parseInt(rest.slice(1), 10);
          }
          return [host, entryPort];
        }
      }
      const firstColon = entryHost.indexOf(":");
      const lastColon = entryHost.lastIndexOf(":");
      if (firstColon !== -1 && firstColon === lastColon && /^\d+$/.test(entryHost.slice(lastColon + 1))) {
        entryPort = Number.parseInt(entryHost.slice(lastColon + 1), 10);
        entryHost = entryHost.slice(0, lastColon);
      }
      return [entryHost, entryPort];
    };
    var normalizeNoProxyHost = (hostname) => {
      if (!hostname) {
        return hostname;
      }
      if (hostname.charAt(0) === "[" && hostname.charAt(hostname.length - 1) === "]") {
        hostname = hostname.slice(1, -1);
      }
      return hostname.replace(/\.+$/, "");
    };
    function shouldBypassProxy(location2) {
      let parsed;
      try {
        parsed = new URL(location2);
      } catch (_err) {
        return false;
      }
      const noProxy = (process.env.no_proxy || process.env.NO_PROXY || "").toLowerCase();
      if (!noProxy) {
        return false;
      }
      if (noProxy === "*") {
        return true;
      }
      const port = Number.parseInt(parsed.port, 10) || DEFAULT_PORTS[parsed.protocol.split(":", 1)[0]] || 0;
      const hostname = normalizeNoProxyHost(parsed.hostname.toLowerCase());
      return noProxy.split(/[\s,]+/).some((entry) => {
        if (!entry) {
          return false;
        }
        let [entryHost, entryPort] = parseNoProxyEntry(entry);
        entryHost = normalizeNoProxyHost(entryHost);
        if (!entryHost) {
          return false;
        }
        if (entryPort && entryPort !== port) {
          return false;
        }
        if (entryHost.charAt(0) === "*") {
          entryHost = entryHost.slice(1);
        }
        if (entryHost.charAt(0) === ".") {
          return hostname.endsWith(entryHost);
        }
        return hostname === entryHost;
      });
    }
    function speedometer(samplesCount, min) {
      samplesCount = samplesCount || 10;
      const bytes = new Array(samplesCount);
      const timestamps = new Array(samplesCount);
      let head = 0;
      let tail = 0;
      let firstSampleTS;
      min = min !== void 0 ? min : 1e3;
      return function push(chunkLength) {
        const now = Date.now();
        const startedAt = timestamps[tail];
        if (!firstSampleTS) {
          firstSampleTS = now;
        }
        bytes[head] = chunkLength;
        timestamps[head] = now;
        let i = tail;
        let bytesCount = 0;
        while (i !== head) {
          bytesCount += bytes[i++];
          i = i % samplesCount;
        }
        head = (head + 1) % samplesCount;
        if (head === tail) {
          tail = (tail + 1) % samplesCount;
        }
        if (now - firstSampleTS < min) {
          return;
        }
        const passed = startedAt && now - startedAt;
        return passed ? Math.round(bytesCount * 1e3 / passed) : void 0;
      };
    }
    function throttle(fn, freq) {
      let timestamp = 0;
      let threshold = 1e3 / freq;
      let lastArgs;
      let timer;
      const invoke = (args2, now = Date.now()) => {
        timestamp = now;
        lastArgs = null;
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
        fn(...args2);
      };
      const throttled = (...args2) => {
        const now = Date.now();
        const passed = now - timestamp;
        if (passed >= threshold) {
          invoke(args2, now);
        } else {
          lastArgs = args2;
          if (!timer) {
            timer = setTimeout(() => {
              timer = null;
              invoke(lastArgs);
            }, threshold - passed);
          }
        }
      };
      const flush = () => lastArgs && invoke(lastArgs);
      return [throttled, flush];
    }
    var progressEventReducer = (listener, isDownloadStream, freq = 3) => {
      let bytesNotified = 0;
      const _speedometer = speedometer(50, 250);
      return throttle((e) => {
        const loaded = e.loaded;
        const total = e.lengthComputable ? e.total : void 0;
        const progressBytes = loaded - bytesNotified;
        const rate = _speedometer(progressBytes);
        const inRange = loaded <= total;
        bytesNotified = loaded;
        const data = {
          loaded,
          total,
          progress: total ? loaded / total : void 0,
          bytes: progressBytes,
          rate: rate ? rate : void 0,
          estimated: rate && total && inRange ? (total - loaded) / rate : void 0,
          event: e,
          lengthComputable: total != null,
          [isDownloadStream ? "download" : "upload"]: true
        };
        listener(data);
      }, freq);
    };
    var progressEventDecorator = (total, throttled) => {
      const lengthComputable = total != null;
      return [(loaded) => throttled[0]({
        lengthComputable,
        total,
        loaded
      }), throttled[1]];
    };
    var asyncDecorator = (fn) => (...args2) => utils$1.asap(() => fn(...args2));
    function estimateDataURLDecodedBytes(url2) {
      if (!url2 || typeof url2 !== "string") return 0;
      if (!url2.startsWith("data:")) return 0;
      const comma = url2.indexOf(",");
      if (comma < 0) return 0;
      const meta = url2.slice(5, comma);
      const body = url2.slice(comma + 1);
      const isBase64 = /;base64/i.test(meta);
      if (isBase64) {
        let effectiveLen = body.length;
        const len = body.length;
        for (let i = 0; i < len; i++) {
          if (body.charCodeAt(i) === 37 && i + 2 < len) {
            const a = body.charCodeAt(i + 1);
            const b = body.charCodeAt(i + 2);
            const isHex = (a >= 48 && a <= 57 || a >= 65 && a <= 70 || a >= 97 && a <= 102) && (b >= 48 && b <= 57 || b >= 65 && b <= 70 || b >= 97 && b <= 102);
            if (isHex) {
              effectiveLen -= 2;
              i += 2;
            }
          }
        }
        let pad = 0;
        let idx = len - 1;
        const tailIsPct3D = (j) => j >= 2 && body.charCodeAt(j - 2) === 37 && // '%'
        body.charCodeAt(j - 1) === 51 && // '3'
        (body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100);
        if (idx >= 0) {
          if (body.charCodeAt(idx) === 61) {
            pad++;
            idx--;
          } else if (tailIsPct3D(idx)) {
            pad++;
            idx -= 3;
          }
        }
        if (pad === 1 && idx >= 0) {
          if (body.charCodeAt(idx) === 61) {
            pad++;
          } else if (tailIsPct3D(idx)) {
            pad++;
          }
        }
        const groups = Math.floor(effectiveLen / 4);
        const bytes = groups * 3 - (pad || 0);
        return bytes > 0 ? bytes : 0;
      }
      return Buffer.byteLength(body, "utf8");
    }
    var zlibOptions = {
      flush: zlib.constants.Z_SYNC_FLUSH,
      finishFlush: zlib.constants.Z_SYNC_FLUSH
    };
    var brotliOptions = {
      flush: zlib.constants.BROTLI_OPERATION_FLUSH,
      finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
    };
    var isBrotliSupported = utils$1.isFunction(zlib.createBrotliDecompress);
    var {
      http: httpFollow,
      https: httpsFollow
    } = followRedirects;
    var isHttps = /https:?/;
    var supportedProtocols = platform.protocols.map((protocol) => {
      return protocol + ":";
    });
    var flushOnFinish = (stream2, [throttled, flush]) => {
      stream2.on("end", flush).on("error", flush);
      return throttled;
    };
    var Http2Sessions = class {
      constructor() {
        this.sessions = /* @__PURE__ */ Object.create(null);
      }
      getSession(authority, options) {
        options = Object.assign({
          sessionTimeout: 1e3
        }, options);
        let authoritySessions = this.sessions[authority];
        if (authoritySessions) {
          let len = authoritySessions.length;
          for (let i = 0; i < len; i++) {
            const [sessionHandle, sessionOptions] = authoritySessions[i];
            if (!sessionHandle.destroyed && !sessionHandle.closed && util.isDeepStrictEqual(sessionOptions, options)) {
              return sessionHandle;
            }
          }
        }
        const session = http2.connect(authority, options);
        let removed;
        const removeSession = () => {
          if (removed) {
            return;
          }
          removed = true;
          let entries = authoritySessions, len = entries.length, i = len;
          while (i--) {
            if (entries[i][0] === session) {
              if (len === 1) {
                delete this.sessions[authority];
              } else {
                entries.splice(i, 1);
              }
              if (!session.closed) {
                session.close();
              }
              return;
            }
          }
        };
        const originalRequestFn = session.request;
        const {
          sessionTimeout
        } = options;
        if (sessionTimeout != null) {
          let timer;
          let streamsCount = 0;
          session.request = function() {
            const stream2 = originalRequestFn.apply(this, arguments);
            streamsCount++;
            if (timer) {
              clearTimeout(timer);
              timer = null;
            }
            stream2.once("close", () => {
              if (!--streamsCount) {
                timer = setTimeout(() => {
                  timer = null;
                  removeSession();
                }, sessionTimeout);
              }
            });
            return stream2;
          };
        }
        session.once("close", removeSession);
        let entry = [session, options];
        authoritySessions ? authoritySessions.push(entry) : authoritySessions = this.sessions[authority] = [entry];
        return session;
      }
    };
    var http2Sessions = new Http2Sessions();
    function dispatchBeforeRedirect(options, responseDetails) {
      if (options.beforeRedirects.proxy) {
        options.beforeRedirects.proxy(options);
      }
      if (options.beforeRedirects.config) {
        options.beforeRedirects.config(options, responseDetails);
      }
    }
    function setProxy(options, configProxy, location2) {
      let proxy = configProxy;
      if (!proxy && proxy !== false) {
        const proxyUrl = getProxyForUrl(location2);
        if (proxyUrl) {
          if (!shouldBypassProxy(location2)) {
            proxy = new URL(proxyUrl);
          }
        }
      }
      if (proxy) {
        if (proxy.username) {
          proxy.auth = (proxy.username || "") + ":" + (proxy.password || "");
        }
        if (proxy.auth) {
          const validProxyAuth = Boolean(proxy.auth.username || proxy.auth.password);
          if (validProxyAuth) {
            proxy.auth = (proxy.auth.username || "") + ":" + (proxy.auth.password || "");
          } else if (typeof proxy.auth === "object") {
            throw new AxiosError("Invalid proxy authorization", AxiosError.ERR_BAD_OPTION, {
              proxy
            });
          }
          const base64 = Buffer.from(proxy.auth, "utf8").toString("base64");
          options.headers["Proxy-Authorization"] = "Basic " + base64;
        }
        options.headers.host = options.hostname + (options.port ? ":" + options.port : "");
        const proxyHost = proxy.hostname || proxy.host;
        options.hostname = proxyHost;
        options.host = proxyHost;
        options.port = proxy.port;
        options.path = location2;
        if (proxy.protocol) {
          options.protocol = proxy.protocol.includes(":") ? proxy.protocol : `${proxy.protocol}:`;
        }
      }
      options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) {
        setProxy(redirectOptions, configProxy, redirectOptions.href);
      };
    }
    var isHttpAdapterSupported = typeof process !== "undefined" && utils$1.kindOf(process) === "process";
    var wrapAsync = (asyncExecutor) => {
      return new Promise((resolve5, reject) => {
        let onDone;
        let isDone;
        const done = (value, isRejected) => {
          if (isDone) return;
          isDone = true;
          onDone && onDone(value, isRejected);
        };
        const _resolve = (value) => {
          done(value);
          resolve5(value);
        };
        const _reject = (reason) => {
          done(reason, true);
          reject(reason);
        };
        asyncExecutor(_resolve, _reject, (onDoneHandler) => onDone = onDoneHandler).catch(_reject);
      });
    };
    var resolveFamily = ({
      address,
      family
    }) => {
      if (!utils$1.isString(address)) {
        throw TypeError("address must be a string");
      }
      return {
        address,
        family: family || (address.indexOf(".") < 0 ? 6 : 4)
      };
    };
    var buildAddressEntry = (address, family) => resolveFamily(utils$1.isObject(address) ? address : {
      address,
      family
    });
    var http2Transport = {
      request(options, cb) {
        const authority = options.protocol + "//" + options.hostname + ":" + (options.port || (options.protocol === "https:" ? 443 : 80));
        const {
          http2Options,
          headers
        } = options;
        const session = http2Sessions.getSession(authority, http2Options);
        const {
          HTTP2_HEADER_SCHEME,
          HTTP2_HEADER_METHOD,
          HTTP2_HEADER_PATH,
          HTTP2_HEADER_STATUS
        } = http2.constants;
        const http2Headers = {
          [HTTP2_HEADER_SCHEME]: options.protocol.replace(":", ""),
          [HTTP2_HEADER_METHOD]: options.method,
          [HTTP2_HEADER_PATH]: options.path
        };
        utils$1.forEach(headers, (header, name) => {
          name.charAt(0) !== ":" && (http2Headers[name] = header);
        });
        const req = session.request(http2Headers);
        req.once("response", (responseHeaders) => {
          const response = req;
          responseHeaders = Object.assign({}, responseHeaders);
          const status = responseHeaders[HTTP2_HEADER_STATUS];
          delete responseHeaders[HTTP2_HEADER_STATUS];
          response.headers = responseHeaders;
          response.statusCode = +status;
          cb(response);
        });
        return req;
      }
    };
    var httpAdapter = isHttpAdapterSupported && function httpAdapter2(config2) {
      return wrapAsync(async function dispatchHttpRequest(resolve5, reject, onDone) {
        let {
          data,
          lookup,
          family,
          httpVersion = 1,
          http2Options
        } = config2;
        const {
          responseType,
          responseEncoding
        } = config2;
        const method = config2.method.toUpperCase();
        let isDone;
        let rejected = false;
        let req;
        httpVersion = +httpVersion;
        if (Number.isNaN(httpVersion)) {
          throw TypeError(`Invalid protocol version: '${config2.httpVersion}' is not a number`);
        }
        if (httpVersion !== 1 && httpVersion !== 2) {
          throw TypeError(`Unsupported protocol version '${httpVersion}'`);
        }
        const isHttp2 = httpVersion === 2;
        if (lookup) {
          const _lookup = callbackify(lookup, (value) => utils$1.isArray(value) ? value : [value]);
          lookup = (hostname, opt, cb) => {
            _lookup(hostname, opt, (err, arg0, arg1) => {
              if (err) {
                return cb(err);
              }
              const addresses = utils$1.isArray(arg0) ? arg0.map((addr) => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)];
              opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family);
            });
          };
        }
        const abortEmitter = new events.EventEmitter();
        function abort(reason) {
          try {
            abortEmitter.emit("abort", !reason || reason.type ? new CanceledError(null, config2, req) : reason);
          } catch (err) {
            console.warn("emit error", err);
          }
        }
        abortEmitter.once("abort", reject);
        const onFinished = () => {
          if (config2.cancelToken) {
            config2.cancelToken.unsubscribe(abort);
          }
          if (config2.signal) {
            config2.signal.removeEventListener("abort", abort);
          }
          abortEmitter.removeAllListeners();
        };
        if (config2.cancelToken || config2.signal) {
          config2.cancelToken && config2.cancelToken.subscribe(abort);
          if (config2.signal) {
            config2.signal.aborted ? abort() : config2.signal.addEventListener("abort", abort);
          }
        }
        onDone((response, isRejected) => {
          isDone = true;
          if (isRejected) {
            rejected = true;
            onFinished();
            return;
          }
          const {
            data: data2
          } = response;
          if (data2 instanceof stream.Readable || data2 instanceof stream.Duplex) {
            const offListeners = stream.finished(data2, () => {
              offListeners();
              onFinished();
            });
          } else {
            onFinished();
          }
        });
        const fullPath = buildFullPath(config2.baseURL, config2.url, config2.allowAbsoluteUrls);
        const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : void 0);
        const protocol = parsed.protocol || supportedProtocols[0];
        if (protocol === "data:") {
          if (config2.maxContentLength > -1) {
            const dataUrl = String(config2.url || fullPath || "");
            const estimated = estimateDataURLDecodedBytes(dataUrl);
            if (estimated > config2.maxContentLength) {
              return reject(new AxiosError("maxContentLength size of " + config2.maxContentLength + " exceeded", AxiosError.ERR_BAD_RESPONSE, config2));
            }
          }
          let convertedData;
          if (method !== "GET") {
            return settle(resolve5, reject, {
              status: 405,
              statusText: "method not allowed",
              headers: {},
              config: config2
            });
          }
          try {
            convertedData = fromDataURI(config2.url, responseType === "blob", {
              Blob: config2.env && config2.env.Blob
            });
          } catch (err) {
            throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config2);
          }
          if (responseType === "text") {
            convertedData = convertedData.toString(responseEncoding);
            if (!responseEncoding || responseEncoding === "utf8") {
              convertedData = utils$1.stripBOM(convertedData);
            }
          } else if (responseType === "stream") {
            convertedData = stream.Readable.from(convertedData);
          }
          return settle(resolve5, reject, {
            data: convertedData,
            status: 200,
            statusText: "OK",
            headers: new AxiosHeaders(),
            config: config2
          });
        }
        if (supportedProtocols.indexOf(protocol) === -1) {
          return reject(new AxiosError("Unsupported protocol " + protocol, AxiosError.ERR_BAD_REQUEST, config2));
        }
        const headers = AxiosHeaders.from(config2.headers).normalize();
        headers.set("User-Agent", "axios/" + VERSION, false);
        const {
          onUploadProgress,
          onDownloadProgress
        } = config2;
        const maxRate = config2.maxRate;
        let maxUploadRate = void 0;
        let maxDownloadRate = void 0;
        if (utils$1.isSpecCompliantForm(data)) {
          const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i);
          data = formDataToStream(data, (formHeaders) => {
            headers.set(formHeaders);
          }, {
            tag: `axios-${VERSION}-boundary`,
            boundary: userBoundary && userBoundary[1] || void 0
          });
        } else if (utils$1.isFormData(data) && utils$1.isFunction(data.getHeaders)) {
          headers.set(data.getHeaders());
          if (!headers.hasContentLength()) {
            try {
              const knownLength = await util.promisify(data.getLength).call(data);
              Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength);
            } catch (e) {
            }
          }
        } else if (utils$1.isBlob(data) || utils$1.isFile(data)) {
          data.size && headers.setContentType(data.type || "application/octet-stream");
          headers.setContentLength(data.size || 0);
          data = stream.Readable.from(readBlob(data));
        } else if (data && !utils$1.isStream(data)) {
          if (Buffer.isBuffer(data)) ;
          else if (utils$1.isArrayBuffer(data)) {
            data = Buffer.from(new Uint8Array(data));
          } else if (utils$1.isString(data)) {
            data = Buffer.from(data, "utf-8");
          } else {
            return reject(new AxiosError("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream", AxiosError.ERR_BAD_REQUEST, config2));
          }
          headers.setContentLength(data.length, false);
          if (config2.maxBodyLength > -1 && data.length > config2.maxBodyLength) {
            return reject(new AxiosError("Request body larger than maxBodyLength limit", AxiosError.ERR_BAD_REQUEST, config2));
          }
        }
        const contentLength = utils$1.toFiniteNumber(headers.getContentLength());
        if (utils$1.isArray(maxRate)) {
          maxUploadRate = maxRate[0];
          maxDownloadRate = maxRate[1];
        } else {
          maxUploadRate = maxDownloadRate = maxRate;
        }
        if (data && (onUploadProgress || maxUploadRate)) {
          if (!utils$1.isStream(data)) {
            data = stream.Readable.from(data, {
              objectMode: false
            });
          }
          data = stream.pipeline([data, new AxiosTransformStream({
            maxRate: utils$1.toFiniteNumber(maxUploadRate)
          })], utils$1.noop);
          onUploadProgress && data.on("progress", flushOnFinish(data, progressEventDecorator(contentLength, progressEventReducer(asyncDecorator(onUploadProgress), false, 3))));
        }
        let auth = void 0;
        if (config2.auth) {
          const username = config2.auth.username || "";
          const password = config2.auth.password || "";
          auth = username + ":" + password;
        }
        if (!auth && parsed.username) {
          const urlUsername = parsed.username;
          const urlPassword = parsed.password;
          auth = urlUsername + ":" + urlPassword;
        }
        auth && headers.delete("authorization");
        let path2;
        try {
          path2 = buildURL(parsed.pathname + parsed.search, config2.params, config2.paramsSerializer).replace(/^\?/, "");
        } catch (err) {
          const customErr = new Error(err.message);
          customErr.config = config2;
          customErr.url = config2.url;
          customErr.exists = true;
          return reject(customErr);
        }
        headers.set("Accept-Encoding", "gzip, compress, deflate" + (isBrotliSupported ? ", br" : ""), false);
        const options = {
          path: path2,
          method,
          headers: headers.toJSON(),
          agents: {
            http: config2.httpAgent,
            https: config2.httpsAgent
          },
          auth,
          protocol,
          family,
          beforeRedirect: dispatchBeforeRedirect,
          beforeRedirects: {},
          http2Options
        };
        !utils$1.isUndefined(lookup) && (options.lookup = lookup);
        if (config2.socketPath) {
          options.socketPath = config2.socketPath;
        } else {
          options.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname;
          options.port = parsed.port;
          setProxy(options, config2.proxy, protocol + "//" + parsed.hostname + (parsed.port ? ":" + parsed.port : "") + options.path);
        }
        let transport;
        const isHttpsRequest = isHttps.test(options.protocol);
        options.agent = isHttpsRequest ? config2.httpsAgent : config2.httpAgent;
        if (isHttp2) {
          transport = http2Transport;
        } else {
          if (config2.transport) {
            transport = config2.transport;
          } else if (config2.maxRedirects === 0) {
            transport = isHttpsRequest ? https : http;
          } else {
            if (config2.maxRedirects) {
              options.maxRedirects = config2.maxRedirects;
            }
            if (config2.beforeRedirect) {
              options.beforeRedirects.config = config2.beforeRedirect;
            }
            transport = isHttpsRequest ? httpsFollow : httpFollow;
          }
        }
        if (config2.maxBodyLength > -1) {
          options.maxBodyLength = config2.maxBodyLength;
        } else {
          options.maxBodyLength = Infinity;
        }
        if (config2.insecureHTTPParser) {
          options.insecureHTTPParser = config2.insecureHTTPParser;
        }
        req = transport.request(options, function handleResponse(res) {
          if (req.destroyed) return;
          const streams = [res];
          const responseLength = utils$1.toFiniteNumber(res.headers["content-length"]);
          if (onDownloadProgress || maxDownloadRate) {
            const transformStream = new AxiosTransformStream({
              maxRate: utils$1.toFiniteNumber(maxDownloadRate)
            });
            onDownloadProgress && transformStream.on("progress", flushOnFinish(transformStream, progressEventDecorator(responseLength, progressEventReducer(asyncDecorator(onDownloadProgress), true, 3))));
            streams.push(transformStream);
          }
          let responseStream = res;
          const lastRequest = res.req || req;
          if (config2.decompress !== false && res.headers["content-encoding"]) {
            if (method === "HEAD" || res.statusCode === 204) {
              delete res.headers["content-encoding"];
            }
            switch ((res.headers["content-encoding"] || "").toLowerCase()) {
              /*eslint default-case:0*/
              case "gzip":
              case "x-gzip":
              case "compress":
              case "x-compress":
                streams.push(zlib.createUnzip(zlibOptions));
                delete res.headers["content-encoding"];
                break;
              case "deflate":
                streams.push(new ZlibHeaderTransformStream());
                streams.push(zlib.createUnzip(zlibOptions));
                delete res.headers["content-encoding"];
                break;
              case "br":
                if (isBrotliSupported) {
                  streams.push(zlib.createBrotliDecompress(brotliOptions));
                  delete res.headers["content-encoding"];
                }
            }
          }
          responseStream = streams.length > 1 ? stream.pipeline(streams, utils$1.noop) : streams[0];
          const response = {
            status: res.statusCode,
            statusText: res.statusMessage,
            headers: new AxiosHeaders(res.headers),
            config: config2,
            request: lastRequest
          };
          if (responseType === "stream") {
            response.data = responseStream;
            settle(resolve5, reject, response);
          } else {
            const responseBuffer = [];
            let totalResponseBytes = 0;
            responseStream.on("data", function handleStreamData(chunk) {
              responseBuffer.push(chunk);
              totalResponseBytes += chunk.length;
              if (config2.maxContentLength > -1 && totalResponseBytes > config2.maxContentLength) {
                rejected = true;
                responseStream.destroy();
                abort(new AxiosError("maxContentLength size of " + config2.maxContentLength + " exceeded", AxiosError.ERR_BAD_RESPONSE, config2, lastRequest));
              }
            });
            responseStream.on("aborted", function handlerStreamAborted() {
              if (rejected) {
                return;
              }
              const err = new AxiosError("stream has been aborted", AxiosError.ERR_BAD_RESPONSE, config2, lastRequest);
              responseStream.destroy(err);
              reject(err);
            });
            responseStream.on("error", function handleStreamError(err) {
              if (req.destroyed) return;
              reject(AxiosError.from(err, null, config2, lastRequest));
            });
            responseStream.on("end", function handleStreamEnd() {
              try {
                let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
                if (responseType !== "arraybuffer") {
                  responseData = responseData.toString(responseEncoding);
                  if (!responseEncoding || responseEncoding === "utf8") {
                    responseData = utils$1.stripBOM(responseData);
                  }
                }
                response.data = responseData;
              } catch (err) {
                return reject(AxiosError.from(err, null, config2, response.request, response));
              }
              settle(resolve5, reject, response);
            });
          }
          abortEmitter.once("abort", (err) => {
            if (!responseStream.destroyed) {
              responseStream.emit("error", err);
              responseStream.destroy();
            }
          });
        });
        abortEmitter.once("abort", (err) => {
          if (req.close) {
            req.close();
          } else {
            req.destroy(err);
          }
        });
        req.on("error", function handleRequestError(err) {
          reject(AxiosError.from(err, null, config2, req));
        });
        req.on("socket", function handleRequestSocket(socket) {
          socket.setKeepAlive(true, 1e3 * 60);
        });
        if (config2.timeout) {
          const timeout = parseInt(config2.timeout, 10);
          if (Number.isNaN(timeout)) {
            abort(new AxiosError("error trying to parse `config.timeout` to int", AxiosError.ERR_BAD_OPTION_VALUE, config2, req));
            return;
          }
          req.setTimeout(timeout, function handleRequestTimeout() {
            if (isDone) return;
            let timeoutErrorMessage = config2.timeout ? "timeout of " + config2.timeout + "ms exceeded" : "timeout exceeded";
            const transitional = config2.transitional || transitionalDefaults;
            if (config2.timeoutErrorMessage) {
              timeoutErrorMessage = config2.timeoutErrorMessage;
            }
            abort(new AxiosError(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config2, req));
          });
        } else {
          req.setTimeout(0);
        }
        if (utils$1.isStream(data)) {
          let ended = false;
          let errored = false;
          data.on("end", () => {
            ended = true;
          });
          data.once("error", (err) => {
            errored = true;
            req.destroy(err);
          });
          data.on("close", () => {
            if (!ended && !errored) {
              abort(new CanceledError("Request stream has been aborted", config2, req));
            }
          });
          data.pipe(req);
        } else {
          data && req.write(data);
          req.end();
        }
      });
    };
    var isURLSameOrigin = platform.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin2, isMSIE) => (url2) => {
      url2 = new URL(url2, platform.origin);
      return origin2.protocol === url2.protocol && origin2.host === url2.host && (isMSIE || origin2.port === url2.port);
    })(new URL(platform.origin), platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)) : () => true;
    var cookies = platform.hasStandardBrowserEnv ? (
      // Standard browser envs support document.cookie
      {
        write(name, value, expires, path2, domain, secure, sameSite) {
          if (typeof document === "undefined") return;
          const cookie = [`${name}=${encodeURIComponent(value)}`];
          if (utils$1.isNumber(expires)) {
            cookie.push(`expires=${new Date(expires).toUTCString()}`);
          }
          if (utils$1.isString(path2)) {
            cookie.push(`path=${path2}`);
          }
          if (utils$1.isString(domain)) {
            cookie.push(`domain=${domain}`);
          }
          if (secure === true) {
            cookie.push("secure");
          }
          if (utils$1.isString(sameSite)) {
            cookie.push(`SameSite=${sameSite}`);
          }
          document.cookie = cookie.join("; ");
        },
        read(name) {
          if (typeof document === "undefined") return null;
          const match = document.cookie.match(new RegExp("(?:^|; )" + name + "=([^;]*)"));
          return match ? decodeURIComponent(match[1]) : null;
        },
        remove(name) {
          this.write(name, "", Date.now() - 864e5, "/");
        }
      }
    ) : (
      // Non-standard browser env (web workers, react-native) lack needed support.
      {
        write() {
        },
        read() {
          return null;
        },
        remove() {
        }
      }
    );
    var headersToObject = (thing) => thing instanceof AxiosHeaders ? {
      ...thing
    } : thing;
    function mergeConfig(config1, config2) {
      config2 = config2 || {};
      const config3 = {};
      function getMergedValue(target, source, prop, caseless) {
        if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
          return utils$1.merge.call({
            caseless
          }, target, source);
        } else if (utils$1.isPlainObject(source)) {
          return utils$1.merge({}, source);
        } else if (utils$1.isArray(source)) {
          return source.slice();
        }
        return source;
      }
      function mergeDeepProperties(a, b, prop, caseless) {
        if (!utils$1.isUndefined(b)) {
          return getMergedValue(a, b, prop, caseless);
        } else if (!utils$1.isUndefined(a)) {
          return getMergedValue(void 0, a, prop, caseless);
        }
      }
      function valueFromConfig2(a, b) {
        if (!utils$1.isUndefined(b)) {
          return getMergedValue(void 0, b);
        }
      }
      function defaultToConfig2(a, b) {
        if (!utils$1.isUndefined(b)) {
          return getMergedValue(void 0, b);
        } else if (!utils$1.isUndefined(a)) {
          return getMergedValue(void 0, a);
        }
      }
      function mergeDirectKeys(a, b, prop) {
        if (prop in config2) {
          return getMergedValue(a, b);
        } else if (prop in config1) {
          return getMergedValue(void 0, a);
        }
      }
      const mergeMap = {
        url: valueFromConfig2,
        method: valueFromConfig2,
        data: valueFromConfig2,
        baseURL: defaultToConfig2,
        transformRequest: defaultToConfig2,
        transformResponse: defaultToConfig2,
        paramsSerializer: defaultToConfig2,
        timeout: defaultToConfig2,
        timeoutMessage: defaultToConfig2,
        withCredentials: defaultToConfig2,
        withXSRFToken: defaultToConfig2,
        adapter: defaultToConfig2,
        responseType: defaultToConfig2,
        xsrfCookieName: defaultToConfig2,
        xsrfHeaderName: defaultToConfig2,
        onUploadProgress: defaultToConfig2,
        onDownloadProgress: defaultToConfig2,
        decompress: defaultToConfig2,
        maxContentLength: defaultToConfig2,
        maxBodyLength: defaultToConfig2,
        beforeRedirect: defaultToConfig2,
        transport: defaultToConfig2,
        httpAgent: defaultToConfig2,
        httpsAgent: defaultToConfig2,
        cancelToken: defaultToConfig2,
        socketPath: defaultToConfig2,
        responseEncoding: defaultToConfig2,
        validateStatus: mergeDirectKeys,
        headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true)
      };
      utils$1.forEach(Object.keys({
        ...config1,
        ...config2
      }), function computeConfigValue(prop) {
        if (prop === "__proto__" || prop === "constructor" || prop === "prototype") return;
        const merge2 = utils$1.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties;
        const configValue = merge2(config1[prop], config2[prop], prop);
        utils$1.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config3[prop] = configValue);
      });
      return config3;
    }
    var resolveConfig = (config2) => {
      const newConfig = mergeConfig({}, config2);
      let {
        data,
        withXSRFToken,
        xsrfHeaderName,
        xsrfCookieName,
        headers,
        auth
      } = newConfig;
      newConfig.headers = headers = AxiosHeaders.from(headers);
      newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config2.params, config2.paramsSerializer);
      if (auth) {
        headers.set("Authorization", "Basic " + btoa((auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : "")));
      }
      if (utils$1.isFormData(data)) {
        if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
          headers.setContentType(void 0);
        } else if (utils$1.isFunction(data.getHeaders)) {
          const formHeaders = data.getHeaders();
          const allowedHeaders = ["content-type", "content-length"];
          Object.entries(formHeaders).forEach(([key, val]) => {
            if (allowedHeaders.includes(key.toLowerCase())) {
              headers.set(key, val);
            }
          });
        }
      }
      if (platform.hasStandardBrowserEnv) {
        withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
        if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin(newConfig.url)) {
          const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
          if (xsrfValue) {
            headers.set(xsrfHeaderName, xsrfValue);
          }
        }
      }
      return newConfig;
    };
    var isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined";
    var xhrAdapter = isXHRAdapterSupported && function(config2) {
      return new Promise(function dispatchXhrRequest(resolve5, reject) {
        const _config = resolveConfig(config2);
        let requestData = _config.data;
        const requestHeaders = AxiosHeaders.from(_config.headers).normalize();
        let {
          responseType,
          onUploadProgress,
          onDownloadProgress
        } = _config;
        let onCanceled;
        let uploadThrottled, downloadThrottled;
        let flushUpload, flushDownload;
        function done() {
          flushUpload && flushUpload();
          flushDownload && flushDownload();
          _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
          _config.signal && _config.signal.removeEventListener("abort", onCanceled);
        }
        let request = new XMLHttpRequest();
        request.open(_config.method.toUpperCase(), _config.url, true);
        request.timeout = _config.timeout;
        function onloadend() {
          if (!request) {
            return;
          }
          const responseHeaders = AxiosHeaders.from("getAllResponseHeaders" in request && request.getAllResponseHeaders());
          const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response;
          const response = {
            data: responseData,
            status: request.status,
            statusText: request.statusText,
            headers: responseHeaders,
            config: config2,
            request
          };
          settle(function _resolve(value) {
            resolve5(value);
            done();
          }, function _reject(err) {
            reject(err);
            done();
          }, response);
          request = null;
        }
        if ("onloadend" in request) {
          request.onloadend = onloadend;
        } else {
          request.onreadystatechange = function handleLoad() {
            if (!request || request.readyState !== 4) {
              return;
            }
            if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) {
              return;
            }
            setTimeout(onloadend);
          };
        }
        request.onabort = function handleAbort() {
          if (!request) {
            return;
          }
          reject(new AxiosError("Request aborted", AxiosError.ECONNABORTED, config2, request));
          request = null;
        };
        request.onerror = function handleError(event) {
          const msg = event && event.message ? event.message : "Network Error";
          const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config2, request);
          err.event = event || null;
          reject(err);
          request = null;
        };
        request.ontimeout = function handleTimeout() {
          let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded";
          const transitional = _config.transitional || transitionalDefaults;
          if (_config.timeoutErrorMessage) {
            timeoutErrorMessage = _config.timeoutErrorMessage;
          }
          reject(new AxiosError(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config2, request));
          request = null;
        };
        requestData === void 0 && requestHeaders.setContentType(null);
        if ("setRequestHeader" in request) {
          utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
            request.setRequestHeader(key, val);
          });
        }
        if (!utils$1.isUndefined(_config.withCredentials)) {
          request.withCredentials = !!_config.withCredentials;
        }
        if (responseType && responseType !== "json") {
          request.responseType = _config.responseType;
        }
        if (onDownloadProgress) {
          [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
          request.addEventListener("progress", downloadThrottled);
        }
        if (onUploadProgress && request.upload) {
          [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
          request.upload.addEventListener("progress", uploadThrottled);
          request.upload.addEventListener("loadend", flushUpload);
        }
        if (_config.cancelToken || _config.signal) {
          onCanceled = (cancel) => {
            if (!request) {
              return;
            }
            reject(!cancel || cancel.type ? new CanceledError(null, config2, request) : cancel);
            request.abort();
            request = null;
          };
          _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
          if (_config.signal) {
            _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled);
          }
        }
        const protocol = parseProtocol(_config.url);
        if (protocol && platform.protocols.indexOf(protocol) === -1) {
          reject(new AxiosError("Unsupported protocol " + protocol + ":", AxiosError.ERR_BAD_REQUEST, config2));
          return;
        }
        request.send(requestData || null);
      });
    };
    var composeSignals = (signals, timeout) => {
      const {
        length
      } = signals = signals ? signals.filter(Boolean) : [];
      if (timeout || length) {
        let controller = new AbortController();
        let aborted;
        const onabort = function(reason) {
          if (!aborted) {
            aborted = true;
            unsubscribe();
            const err = reason instanceof Error ? reason : this.reason;
            controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
          }
        };
        let timer = timeout && setTimeout(() => {
          timer = null;
          onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT));
        }, timeout);
        const unsubscribe = () => {
          if (signals) {
            timer && clearTimeout(timer);
            timer = null;
            signals.forEach((signal2) => {
              signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort);
            });
            signals = null;
          }
        };
        signals.forEach((signal2) => signal2.addEventListener("abort", onabort));
        const {
          signal
        } = controller;
        signal.unsubscribe = () => utils$1.asap(unsubscribe);
        return signal;
      }
    };
    var streamChunk = function* (chunk, chunkSize) {
      let len = chunk.byteLength;
      if (len < chunkSize) {
        yield chunk;
        return;
      }
      let pos = 0;
      let end;
      while (pos < len) {
        end = pos + chunkSize;
        yield chunk.slice(pos, end);
        pos = end;
      }
    };
    var readBytes = async function* (iterable, chunkSize) {
      for await (const chunk of readStream(iterable)) {
        yield* streamChunk(chunk, chunkSize);
      }
    };
    var readStream = async function* (stream2) {
      if (stream2[Symbol.asyncIterator]) {
        yield* stream2;
        return;
      }
      const reader = stream2.getReader();
      try {
        for (; ; ) {
          const {
            done,
            value
          } = await reader.read();
          if (done) {
            break;
          }
          yield value;
        }
      } finally {
        await reader.cancel();
      }
    };
    var trackStream = (stream2, chunkSize, onProgress, onFinish) => {
      const iterator2 = readBytes(stream2, chunkSize);
      let bytes = 0;
      let done;
      let _onFinish = (e) => {
        if (!done) {
          done = true;
          onFinish && onFinish(e);
        }
      };
      return new ReadableStream({
        async pull(controller) {
          try {
            const {
              done: done2,
              value
            } = await iterator2.next();
            if (done2) {
              _onFinish();
              controller.close();
              return;
            }
            let len = value.byteLength;
            if (onProgress) {
              let loadedBytes = bytes += len;
              onProgress(loadedBytes);
            }
            controller.enqueue(new Uint8Array(value));
          } catch (err) {
            _onFinish(err);
            throw err;
          }
        },
        cancel(reason) {
          _onFinish(reason);
          return iterator2.return();
        }
      }, {
        highWaterMark: 2
      });
    };
    var DEFAULT_CHUNK_SIZE = 64 * 1024;
    var {
      isFunction: isFunction2
    } = utils$1;
    var globalFetchAPI = (({
      Request,
      Response
    }) => ({
      Request,
      Response
    }))(utils$1.global);
    var {
      ReadableStream: ReadableStream$1,
      TextEncoder: TextEncoder$1
    } = utils$1.global;
    var test = (fn, ...args2) => {
      try {
        return !!fn(...args2);
      } catch (e) {
        return false;
      }
    };
    var factory = (env2) => {
      env2 = utils$1.merge.call({
        skipUndefined: true
      }, globalFetchAPI, env2);
      const {
        fetch: envFetch,
        Request,
        Response
      } = env2;
      const isFetchSupported = envFetch ? isFunction2(envFetch) : typeof fetch === "function";
      const isRequestSupported = isFunction2(Request);
      const isResponseSupported = isFunction2(Response);
      if (!isFetchSupported) {
        return false;
      }
      const isReadableStreamSupported = isFetchSupported && isFunction2(ReadableStream$1);
      const encodeText = isFetchSupported && (typeof TextEncoder$1 === "function" ? /* @__PURE__ */ ((encoder) => (str) => encoder.encode(str))(new TextEncoder$1()) : async (str) => new Uint8Array(await new Request(str).arrayBuffer()));
      const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
        let duplexAccessed = false;
        const body = new ReadableStream$1();
        const hasContentType = new Request(platform.origin, {
          body,
          method: "POST",
          get duplex() {
            duplexAccessed = true;
            return "half";
          }
        }).headers.has("Content-Type");
        body.cancel();
        return duplexAccessed && !hasContentType;
      });
      const supportsResponseStream = isResponseSupported && isReadableStreamSupported && test(() => utils$1.isReadableStream(new Response("").body));
      const resolvers = {
        stream: supportsResponseStream && ((res) => res.body)
      };
      isFetchSupported && (() => {
        ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type) => {
          !resolvers[type] && (resolvers[type] = (res, config2) => {
            let method = res && res[type];
            if (method) {
              return method.call(res);
            }
            throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config2);
          });
        });
      })();
      const getBodyLength = async (body) => {
        if (body == null) {
          return 0;
        }
        if (utils$1.isBlob(body)) {
          return body.size;
        }
        if (utils$1.isSpecCompliantForm(body)) {
          const _request = new Request(platform.origin, {
            method: "POST",
            body
          });
          return (await _request.arrayBuffer()).byteLength;
        }
        if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
          return body.byteLength;
        }
        if (utils$1.isURLSearchParams(body)) {
          body = body + "";
        }
        if (utils$1.isString(body)) {
          return (await encodeText(body)).byteLength;
        }
      };
      const resolveBodyLength = async (headers, body) => {
        const length = utils$1.toFiniteNumber(headers.getContentLength());
        return length == null ? getBodyLength(body) : length;
      };
      return async (config2) => {
        let {
          url: url2,
          method,
          data,
          signal,
          cancelToken,
          timeout,
          onDownloadProgress,
          onUploadProgress,
          responseType,
          headers,
          withCredentials = "same-origin",
          fetchOptions
        } = resolveConfig(config2);
        let _fetch = envFetch || fetch;
        responseType = responseType ? (responseType + "").toLowerCase() : "text";
        let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
        let request = null;
        const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
          composedSignal.unsubscribe();
        });
        let requestContentLength;
        try {
          if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) {
            let _request = new Request(url2, {
              method: "POST",
              body: data,
              duplex: "half"
            });
            let contentTypeHeader;
            if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) {
              headers.setContentType(contentTypeHeader);
            }
            if (_request.body) {
              const [onProgress, flush] = progressEventDecorator(requestContentLength, progressEventReducer(asyncDecorator(onUploadProgress)));
              data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
            }
          }
          if (!utils$1.isString(withCredentials)) {
            withCredentials = withCredentials ? "include" : "omit";
          }
          const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype;
          const resolvedOptions = {
            ...fetchOptions,
            signal: composedSignal,
            method: method.toUpperCase(),
            headers: headers.normalize().toJSON(),
            body: data,
            duplex: "half",
            credentials: isCredentialsSupported ? withCredentials : void 0
          };
          request = isRequestSupported && new Request(url2, resolvedOptions);
          let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url2, resolvedOptions));
          const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response");
          if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) {
            const options = {};
            ["status", "statusText", "headers"].forEach((prop) => {
              options[prop] = response[prop];
            });
            const responseContentLength = utils$1.toFiniteNumber(response.headers.get("content-length"));
            const [onProgress, flush] = onDownloadProgress && progressEventDecorator(responseContentLength, progressEventReducer(asyncDecorator(onDownloadProgress), true)) || [];
            response = new Response(trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
              flush && flush();
              unsubscribe && unsubscribe();
            }), options);
          }
          responseType = responseType || "text";
          let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || "text"](response, config2);
          !isStreamResponse && unsubscribe && unsubscribe();
          return await new Promise((resolve5, reject) => {
            settle(resolve5, reject, {
              data: responseData,
              headers: AxiosHeaders.from(response.headers),
              status: response.status,
              statusText: response.statusText,
              config: config2,
              request
            });
          });
        } catch (err) {
          unsubscribe && unsubscribe();
          if (err && err.name === "TypeError" && /Load failed|fetch/i.test(err.message)) {
            throw Object.assign(new AxiosError("Network Error", AxiosError.ERR_NETWORK, config2, request, err && err.response), {
              cause: err.cause || err
            });
          }
          throw AxiosError.from(err, err && err.code, config2, request, err && err.response);
        }
      };
    };
    var seedCache = /* @__PURE__ */ new Map();
    var getFetch = (config2) => {
      let env2 = config2 && config2.env || {};
      const {
        fetch: fetch2,
        Request,
        Response
      } = env2;
      const seeds = [Request, Response, fetch2];
      let len = seeds.length, i = len, seed, target, map = seedCache;
      while (i--) {
        seed = seeds[i];
        target = map.get(seed);
        target === void 0 && map.set(seed, target = i ? /* @__PURE__ */ new Map() : factory(env2));
        map = target;
      }
      return target;
    };
    getFetch();
    var knownAdapters = {
      http: httpAdapter,
      xhr: xhrAdapter,
      fetch: {
        get: getFetch
      }
    };
    utils$1.forEach(knownAdapters, (fn, value) => {
      if (fn) {
        try {
          Object.defineProperty(fn, "name", {
            value
          });
        } catch (e) {
        }
        Object.defineProperty(fn, "adapterName", {
          value
        });
      }
    });
    var renderReason = (reason) => `- ${reason}`;
    var isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
    function getAdapter(adapters2, config2) {
      adapters2 = utils$1.isArray(adapters2) ? adapters2 : [adapters2];
      const {
        length
      } = adapters2;
      let nameOrAdapter;
      let adapter;
      const rejectedReasons = {};
      for (let i = 0; i < length; i++) {
        nameOrAdapter = adapters2[i];
        let id;
        adapter = nameOrAdapter;
        if (!isResolvedHandle(nameOrAdapter)) {
          adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
          if (adapter === void 0) {
            throw new AxiosError(`Unknown adapter '${id}'`);
          }
        }
        if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config2)))) {
          break;
        }
        rejectedReasons[id || "#" + i] = adapter;
      }
      if (!adapter) {
        const reasons = Object.entries(rejectedReasons).map(([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build"));
        let s = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified";
        throw new AxiosError(`There is no suitable adapter to dispatch the request ` + s, "ERR_NOT_SUPPORT");
      }
      return adapter;
    }
    var adapters = {
      /**
       * Resolve an adapter from a list of adapter names or functions.
       * @type {Function}
       */
      getAdapter,
      /**
       * Exposes all known adapters
       * @type {Object<string, Function|Object>}
       */
      adapters: knownAdapters
    };
    function throwIfCancellationRequested(config2) {
      if (config2.cancelToken) {
        config2.cancelToken.throwIfRequested();
      }
      if (config2.signal && config2.signal.aborted) {
        throw new CanceledError(null, config2);
      }
    }
    function dispatchRequest(config2) {
      throwIfCancellationRequested(config2);
      config2.headers = AxiosHeaders.from(config2.headers);
      config2.data = transformData.call(config2, config2.transformRequest);
      if (["post", "put", "patch"].indexOf(config2.method) !== -1) {
        config2.headers.setContentType("application/x-www-form-urlencoded", false);
      }
      const adapter = adapters.getAdapter(config2.adapter || defaults.adapter, config2);
      return adapter(config2).then(function onAdapterResolution(response) {
        throwIfCancellationRequested(config2);
        response.data = transformData.call(config2, config2.transformResponse, response);
        response.headers = AxiosHeaders.from(response.headers);
        return response;
      }, function onAdapterRejection(reason) {
        if (!isCancel(reason)) {
          throwIfCancellationRequested(config2);
          if (reason && reason.response) {
            reason.response.data = transformData.call(config2, config2.transformResponse, reason.response);
            reason.response.headers = AxiosHeaders.from(reason.response.headers);
          }
        }
        return Promise.reject(reason);
      });
    }
    var validators$1 = {};
    ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => {
      validators$1[type] = function validator2(thing) {
        return typeof thing === type || "a" + (i < 1 ? "n " : " ") + type;
      };
    });
    var deprecatedWarnings = {};
    validators$1.transitional = function transitional(validator2, version, message) {
      function formatMessage(opt, desc) {
        return "[Axios v" + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : "");
      }
      return (value, opt, opts) => {
        if (validator2 === false) {
          throw new AxiosError(formatMessage(opt, " has been removed" + (version ? " in " + version : "")), AxiosError.ERR_DEPRECATED);
        }
        if (version && !deprecatedWarnings[opt]) {
          deprecatedWarnings[opt] = true;
          console.warn(formatMessage(opt, " has been deprecated since v" + version + " and will be removed in the near future"));
        }
        return validator2 ? validator2(value, opt, opts) : true;
      };
    };
    validators$1.spelling = function spelling(correctSpelling) {
      return (value, opt) => {
        console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
        return true;
      };
    };
    function assertOptions(options, schema, allowUnknown) {
      if (typeof options !== "object") {
        throw new AxiosError("options must be an object", AxiosError.ERR_BAD_OPTION_VALUE);
      }
      const keys = Object.keys(options);
      let i = keys.length;
      while (i-- > 0) {
        const opt = keys[i];
        const validator2 = schema[opt];
        if (validator2) {
          const value = options[opt];
          const result = value === void 0 || validator2(value, opt, options);
          if (result !== true) {
            throw new AxiosError("option " + opt + " must be " + result, AxiosError.ERR_BAD_OPTION_VALUE);
          }
          continue;
        }
        if (allowUnknown !== true) {
          throw new AxiosError("Unknown option " + opt, AxiosError.ERR_BAD_OPTION);
        }
      }
    }
    var validator = {
      assertOptions,
      validators: validators$1
    };
    var validators = validator.validators;
    var Axios = class {
      constructor(instanceConfig) {
        this.defaults = instanceConfig || {};
        this.interceptors = {
          request: new InterceptorManager(),
          response: new InterceptorManager()
        };
      }
      /**
       * Dispatch a request
       *
       * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
       * @param {?Object} config
       *
       * @returns {Promise} The Promise to be fulfilled
       */
      async request(configOrUrl, config2) {
        try {
          return await this._request(configOrUrl, config2);
        } catch (err) {
          if (err instanceof Error) {
            let dummy = {};
            Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
            const stack = (() => {
              if (!dummy.stack) {
                return "";
              }
              const firstNewlineIndex = dummy.stack.indexOf("\n");
              return firstNewlineIndex === -1 ? "" : dummy.stack.slice(firstNewlineIndex + 1);
            })();
            try {
              if (!err.stack) {
                err.stack = stack;
              } else if (stack) {
                const firstNewlineIndex = stack.indexOf("\n");
                const secondNewlineIndex = firstNewlineIndex === -1 ? -1 : stack.indexOf("\n", firstNewlineIndex + 1);
                const stackWithoutTwoTopLines = secondNewlineIndex === -1 ? "" : stack.slice(secondNewlineIndex + 1);
                if (!String(err.stack).endsWith(stackWithoutTwoTopLines)) {
                  err.stack += "\n" + stack;
                }
              }
            } catch (e) {
            }
          }
          throw err;
        }
      }
      _request(configOrUrl, config2) {
        if (typeof configOrUrl === "string") {
          config2 = config2 || {};
          config2.url = configOrUrl;
        } else {
          config2 = configOrUrl || {};
        }
        config2 = mergeConfig(this.defaults, config2);
        const {
          transitional,
          paramsSerializer,
          headers
        } = config2;
        if (transitional !== void 0) {
          validator.assertOptions(transitional, {
            silentJSONParsing: validators.transitional(validators.boolean),
            forcedJSONParsing: validators.transitional(validators.boolean),
            clarifyTimeoutError: validators.transitional(validators.boolean),
            legacyInterceptorReqResOrdering: validators.transitional(validators.boolean)
          }, false);
        }
        if (paramsSerializer != null) {
          if (utils$1.isFunction(paramsSerializer)) {
            config2.paramsSerializer = {
              serialize: paramsSerializer
            };
          } else {
            validator.assertOptions(paramsSerializer, {
              encode: validators.function,
              serialize: validators.function
            }, true);
          }
        }
        if (config2.allowAbsoluteUrls !== void 0) ;
        else if (this.defaults.allowAbsoluteUrls !== void 0) {
          config2.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
        } else {
          config2.allowAbsoluteUrls = true;
        }
        validator.assertOptions(config2, {
          baseUrl: validators.spelling("baseURL"),
          withXsrfToken: validators.spelling("withXSRFToken")
        }, true);
        config2.method = (config2.method || this.defaults.method || "get").toLowerCase();
        let contextHeaders = headers && utils$1.merge(headers.common, headers[config2.method]);
        headers && utils$1.forEach(["delete", "get", "head", "post", "put", "patch", "common"], (method) => {
          delete headers[method];
        });
        config2.headers = AxiosHeaders.concat(contextHeaders, headers);
        const requestInterceptorChain = [];
        let synchronousRequestInterceptors = true;
        this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
          if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config2) === false) {
            return;
          }
          synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
          const transitional2 = config2.transitional || transitionalDefaults;
          const legacyInterceptorReqResOrdering = transitional2 && transitional2.legacyInterceptorReqResOrdering;
          if (legacyInterceptorReqResOrdering) {
            requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
          } else {
            requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
          }
        });
        const responseInterceptorChain = [];
        this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
          responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
        });
        let promise;
        let i = 0;
        let len;
        if (!synchronousRequestInterceptors) {
          const chain = [dispatchRequest.bind(this), void 0];
          chain.unshift(...requestInterceptorChain);
          chain.push(...responseInterceptorChain);
          len = chain.length;
          promise = Promise.resolve(config2);
          while (i < len) {
            promise = promise.then(chain[i++], chain[i++]);
          }
          return promise;
        }
        len = requestInterceptorChain.length;
        let newConfig = config2;
        while (i < len) {
          const onFulfilled = requestInterceptorChain[i++];
          const onRejected = requestInterceptorChain[i++];
          try {
            newConfig = onFulfilled(newConfig);
          } catch (error) {
            onRejected.call(this, error);
            break;
          }
        }
        try {
          promise = dispatchRequest.call(this, newConfig);
        } catch (error) {
          return Promise.reject(error);
        }
        i = 0;
        len = responseInterceptorChain.length;
        while (i < len) {
          promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
        }
        return promise;
      }
      getUri(config2) {
        config2 = mergeConfig(this.defaults, config2);
        const fullPath = buildFullPath(config2.baseURL, config2.url, config2.allowAbsoluteUrls);
        return buildURL(fullPath, config2.params, config2.paramsSerializer);
      }
    };
    utils$1.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) {
      Axios.prototype[method] = function(url2, config2) {
        return this.request(mergeConfig(config2 || {}, {
          method,
          url: url2,
          data: (config2 || {}).data
        }));
      };
    });
    utils$1.forEach(["post", "put", "patch"], function forEachMethodWithData(method) {
      function generateHTTPMethod(isForm) {
        return function httpMethod(url2, data, config2) {
          return this.request(mergeConfig(config2 || {}, {
            method,
            headers: isForm ? {
              "Content-Type": "multipart/form-data"
            } : {},
            url: url2,
            data
          }));
        };
      }
      Axios.prototype[method] = generateHTTPMethod();
      Axios.prototype[method + "Form"] = generateHTTPMethod(true);
    });
    var CancelToken = class _CancelToken {
      constructor(executor) {
        if (typeof executor !== "function") {
          throw new TypeError("executor must be a function.");
        }
        let resolvePromise;
        this.promise = new Promise(function promiseExecutor(resolve5) {
          resolvePromise = resolve5;
        });
        const token = this;
        this.promise.then((cancel) => {
          if (!token._listeners) return;
          let i = token._listeners.length;
          while (i-- > 0) {
            token._listeners[i](cancel);
          }
          token._listeners = null;
        });
        this.promise.then = (onfulfilled) => {
          let _resolve;
          const promise = new Promise((resolve5) => {
            token.subscribe(resolve5);
            _resolve = resolve5;
          }).then(onfulfilled);
          promise.cancel = function reject() {
            token.unsubscribe(_resolve);
          };
          return promise;
        };
        executor(function cancel(message, config2, request) {
          if (token.reason) {
            return;
          }
          token.reason = new CanceledError(message, config2, request);
          resolvePromise(token.reason);
        });
      }
      /**
       * Throws a `CanceledError` if cancellation has been requested.
       */
      throwIfRequested() {
        if (this.reason) {
          throw this.reason;
        }
      }
      /**
       * Subscribe to the cancel signal
       */
      subscribe(listener) {
        if (this.reason) {
          listener(this.reason);
          return;
        }
        if (this._listeners) {
          this._listeners.push(listener);
        } else {
          this._listeners = [listener];
        }
      }
      /**
       * Unsubscribe from the cancel signal
       */
      unsubscribe(listener) {
        if (!this._listeners) {
          return;
        }
        const index = this._listeners.indexOf(listener);
        if (index !== -1) {
          this._listeners.splice(index, 1);
        }
      }
      toAbortSignal() {
        const controller = new AbortController();
        const abort = (err) => {
          controller.abort(err);
        };
        this.subscribe(abort);
        controller.signal.unsubscribe = () => this.unsubscribe(abort);
        return controller.signal;
      }
      /**
       * Returns an object that contains a new `CancelToken` and a function that, when called,
       * cancels the `CancelToken`.
       */
      static source() {
        let cancel;
        const token = new _CancelToken(function executor(c) {
          cancel = c;
        });
        return {
          token,
          cancel
        };
      }
    };
    function spread(callback) {
      return function wrap2(arr) {
        return callback.apply(null, arr);
      };
    }
    function isAxiosError(payload) {
      return utils$1.isObject(payload) && payload.isAxiosError === true;
    }
    var HttpStatusCode = {
      Continue: 100,
      SwitchingProtocols: 101,
      Processing: 102,
      EarlyHints: 103,
      Ok: 200,
      Created: 201,
      Accepted: 202,
      NonAuthoritativeInformation: 203,
      NoContent: 204,
      ResetContent: 205,
      PartialContent: 206,
      MultiStatus: 207,
      AlreadyReported: 208,
      ImUsed: 226,
      MultipleChoices: 300,
      MovedPermanently: 301,
      Found: 302,
      SeeOther: 303,
      NotModified: 304,
      UseProxy: 305,
      Unused: 306,
      TemporaryRedirect: 307,
      PermanentRedirect: 308,
      BadRequest: 400,
      Unauthorized: 401,
      PaymentRequired: 402,
      Forbidden: 403,
      NotFound: 404,
      MethodNotAllowed: 405,
      NotAcceptable: 406,
      ProxyAuthenticationRequired: 407,
      RequestTimeout: 408,
      Conflict: 409,
      Gone: 410,
      LengthRequired: 411,
      PreconditionFailed: 412,
      PayloadTooLarge: 413,
      UriTooLong: 414,
      UnsupportedMediaType: 415,
      RangeNotSatisfiable: 416,
      ExpectationFailed: 417,
      ImATeapot: 418,
      MisdirectedRequest: 421,
      UnprocessableEntity: 422,
      Locked: 423,
      FailedDependency: 424,
      TooEarly: 425,
      UpgradeRequired: 426,
      PreconditionRequired: 428,
      TooManyRequests: 429,
      RequestHeaderFieldsTooLarge: 431,
      UnavailableForLegalReasons: 451,
      InternalServerError: 500,
      NotImplemented: 501,
      BadGateway: 502,
      ServiceUnavailable: 503,
      GatewayTimeout: 504,
      HttpVersionNotSupported: 505,
      VariantAlsoNegotiates: 506,
      InsufficientStorage: 507,
      LoopDetected: 508,
      NotExtended: 510,
      NetworkAuthenticationRequired: 511,
      WebServerIsDown: 521,
      ConnectionTimedOut: 522,
      OriginIsUnreachable: 523,
      TimeoutOccurred: 524,
      SslHandshakeFailed: 525,
      InvalidSslCertificate: 526
    };
    Object.entries(HttpStatusCode).forEach(([key, value]) => {
      HttpStatusCode[value] = key;
    });
    function createInstance(defaultConfig) {
      const context = new Axios(defaultConfig);
      const instance = bind(Axios.prototype.request, context);
      utils$1.extend(instance, Axios.prototype, context, {
        allOwnKeys: true
      });
      utils$1.extend(instance, context, null, {
        allOwnKeys: true
      });
      instance.create = function create(instanceConfig) {
        return createInstance(mergeConfig(defaultConfig, instanceConfig));
      };
      return instance;
    }
    var axios = createInstance(defaults);
    axios.Axios = Axios;
    axios.CanceledError = CanceledError;
    axios.CancelToken = CancelToken;
    axios.isCancel = isCancel;
    axios.VERSION = VERSION;
    axios.toFormData = toFormData;
    axios.AxiosError = AxiosError;
    axios.Cancel = axios.CanceledError;
    axios.all = function all(promises) {
      return Promise.all(promises);
    };
    axios.spread = spread;
    axios.isAxiosError = isAxiosError;
    axios.mergeConfig = mergeConfig;
    axios.AxiosHeaders = AxiosHeaders;
    axios.formToJSON = (thing) => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
    axios.getAdapter = adapters.getAdapter;
    axios.HttpStatusCode = HttpStatusCode;
    axios.default = axios;
    module2.exports = axios;
  }
});

// services/DouyinAPI.js
var require_DouyinAPI = __commonJS({
  "services/DouyinAPI.js"(exports2, module2) {
    init_prefix();
    var fs2 = require("fs");
    var path2 = require("path");
    var axios = require_axios();
    var DouyinAPI2 = class {
      constructor(config2, mode2) {
        this.baseUrl = config2.server?.baseUrl || "http://127.0.0.1:8000";
        this.mode = mode2 || null;
        this.clientIdFile = path2.join(global.__original_dirname, `client_id_${mode2 || "default"}.txt`);
        this.clientId = this._loadOrCreateClientId();
        this.stats = {
          videosChecked: 0,
          commentsFetched: 0,
          tasksCompleted: 0,
          tasksFailed: 0
        };
        this.http = axios.create({
          baseURL: this.baseUrl,
          timeout: 3e4,
          headers: { "Content-Type": "application/json" }
        });
      }
      _loadOrCreateClientId() {
        try {
          if (fs2.existsSync(this.clientIdFile)) {
            const id2 = fs2.readFileSync(this.clientIdFile, "utf-8").trim();
            if (id2) {
              console.log(`[API] \u52A0\u8F7D client_id: ${id2}`);
              return id2;
            }
          }
        } catch (e) {
        }
        const id = `client_${Date.now()}_${Math.floor(Math.random() * 9e3 + 1e3)}`;
        try {
          fs2.writeFileSync(this.clientIdFile, id, "utf-8");
        } catch (e) {
        }
        console.log(`[API] \u521B\u5EFA client_id: ${id}`);
        return id;
      }
      async get_next_task() {
        try {
          const params = { client_id: this.clientId };
          if (this.mode) {
            params.task_type = this.mode === "video" ? "check_account" : "fetch_comments";
          }
          const { data } = await this.http.get("/api/client/task/next", {
            params
          });
          const task = data?.task;
          if (task) {
            console.log(`[API] \u62C9\u53D6\u5230\u4EFB\u52A1: ${task.task_type} - ${task.target_id}`);
          }
          return task || null;
        } catch (e) {
          console.log(`[API] \u62C9\u53D6\u4EFB\u52A1\u5931\u8D25: ${e.message}`);
          return null;
        }
      }
      async report_videos(accountId, videos) {
        try {
          const { data } = await this.http.post("/api/client/videos/report", {
            client_id: this.clientId,
            account_id: accountId,
            videos
          });
          const sample = videos[0];
          console.log(`[API] \u4E0A\u62A5\u89C6\u9891\u6210\u529F: \u65B0\u589E${data?.new_count || 0}\u4E2A\uFF0C\u5171${data?.total || 0}\u4E2A | ai_result=${JSON.stringify(sample?.ai_result || "missing")}`);
          this.stats.videosChecked += videos.length;
          return true;
        } catch (e) {
          console.log(`[API] \u4E0A\u62A5\u89C6\u9891\u5931\u8D25: ${e.message}`);
          return false;
        }
      }
      async report_comments(videoDbId, comments) {
        try {
          const { data } = await this.http.post("/api/client/comments/report", {
            client_id: this.clientId,
            video_db_id: videoDbId,
            comments
          });
          console.log(`[API] \u4E0A\u62A5\u8BC4\u8BBA\u6210\u529F: \u65B0\u589E${data?.new_count || 0}\u6761\uFF0C\u5171${data?.total || 0}\u6761`);
          this.stats.commentsFetched += comments.length;
          return true;
        } catch (e) {
          console.log(`[API] \u4E0A\u62A5\u8BC4\u8BBA\u5931\u8D25: ${e.message}`);
          return false;
        }
      }
      async update_account_profile(accountId, profile) {
        try {
          await this.http.post("/api/client/account/profile", {
            client_id: this.clientId,
            account_id: accountId,
            nickname: profile.nickname || "",
            douyin_id: profile.douyin_id || "",
            signature: profile.signature || "",
            gender: profile.gender,
            follower_count: profile.follower_count || 0,
            following_count: profile.following_count || 0,
            aweme_count: profile.aweme_count || 0,
            favoriting_count: profile.favoriting_count || 0,
            total_favorited: profile.total_favorited || 0,
            ip_location: profile.ip_location || "",
            avatar_url: profile.avatar_url || "",
            province: profile.province || "",
            city: profile.city || "",
            custom_verify: profile.custom_verify || "",
            enterprise_verify_reason: profile.enterprise_verify_reason || "",
            short_id: profile.short_id || ""
          });
          console.log(`[API] \u66F4\u65B0\u8D26\u53F7\u4FE1\u606F\u6210\u529F: ${profile.nickname || ""}`);
          return true;
        } catch (e) {
          console.log(`[API] \u66F4\u65B0\u8D26\u53F7\u4FE1\u606F\u5931\u8D25: ${e.message}`);
          return false;
        }
      }
      async get_known_videos(accountId) {
        try {
          const { data } = await this.http.get(`/api/client/account/${accountId}/known-videos`);
          return data?.video_ids || [];
        } catch (e) {
          console.log(`[API] \u83B7\u53D6\u5DF2\u77E5\u89C6\u9891\u5931\u8D25: ${e.message}`);
          return [];
        }
      }
      async complete_task(taskId, result = {}) {
        try {
          await this.http.post("/api/client/task/complete", {
            client_id: this.clientId,
            task_id: taskId,
            result
          });
          console.log(`[API] \u4EFB\u52A1\u5B8C\u6210: ${taskId}`);
          this.stats.tasksCompleted++;
          if (this.stats.tasksCompleted % 50 === 0) {
            this.http.post("/api/client/task/cleanup", {
              client_id: this.clientId,
              status: "online",
              description: "cleanup"
            }).catch(() => {
            });
          }
          return true;
        } catch (e) {
          console.log(`[API] \u4EFB\u52A1\u5B8C\u6210\u4E0A\u62A5\u5931\u8D25: ${e.message}`);
          return false;
        }
      }
      async fail_task(taskId, error) {
        try {
          await this.http.post("/api/client/task/fail", {
            client_id: this.clientId,
            task_id: taskId,
            error
          });
          console.log(`[API] \u4EFB\u52A1\u5931\u8D25\u5DF2\u4E0A\u62A5: ${taskId} - ${error}`);
          this.stats.tasksFailed++;
          return true;
        } catch (e) {
          console.log(`[API] \u4EFB\u52A1\u5931\u8D25\u4E0A\u62A5\u5931\u8D25: ${e.message}`);
          return false;
        }
      }
      async heartbeat(description = "\u6B63\u5E38\u8FD0\u884C\u4E2D") {
        try {
          await this.http.post("/api/client/heartbeat", {
            client_id: this.clientId,
            status: "online",
            description,
            stats: this.stats
          });
          console.log(`[\u5FC3\u8DF3] ${description}`);
          return true;
        } catch (e) {
          console.log(`[\u5FC3\u8DF3] \u5931\u8D25: ${e.message}`);
          return false;
        }
      }
      /**
       * 获取黑名单昵称列表
       */
      async get_blacklist() {
        try {
          const { data } = await this.http.get("/api/client/blacklist");
          return data?.nicknames || [];
        } catch (e) {
          console.log(`[API] \u83B7\u53D6\u9ED1\u540D\u5355\u5931\u8D25: ${e.message}`);
          return [];
        }
      }
      async fetch_settings() {
        try {
          const { data } = await this.http.get("/api/client/settings");
          console.log(`[API] \u83B7\u53D6\u8BBE\u7F6E: comment_max_age_hours=${data.comment_max_age_hours}`);
          return data;
        } catch (e) {
          console.log(`[API] \u83B7\u53D6\u8BBE\u7F6E\u5931\u8D25: ${e.message}`);
          return null;
        }
      }
      /**
       * 上报评论用户抖音号
       */
      async report_douyin_id(commentId, douyinId) {
        try {
          const { data } = await this.http.post("/api/client/douyin-id/report", {
            client_id: this.clientId,
            comment_id: commentId,
            douyin_id: douyinId
          });
          return data && data.success;
        } catch (e) {
          console.error("[api] report_douyin_id failed:", e.message);
          return false;
        }
      }
      /**
       * 上报视频详情统计信息（从视频详情页 Fiber 提取）
       */
      async update_video_stats(videoDbId, videoInfo) {
        try {
          const { data } = await this.http.post("/api/client/videos/update-stats", {
            client_id: this.clientId,
            video_db_id: videoDbId,
            video_info: videoInfo
          });
          if (data && data.success) {
            console.log(`[API] \u89C6\u9891\u7EDF\u8BA1\u5DF2\u66F4\u65B0: \u8BC4\u8BBA${videoInfo.comment_count || 0} \u70B9\u8D5E${videoInfo.likes || 0}`);
          }
          return data && data.success;
        } catch (e) {
          console.log(`[API] \u66F4\u65B0\u89C6\u9891\u7EDF\u8BA1\u5931\u8D25: ${e.message}`);
          return false;
        }
      }
      /**
       * 上报搜索结果
       */
      async report_search_results(keyword, videos) {
        try {
          const { data } = await this.http.post("/api/client/search/report", {
            client_id: this.clientId,
            keyword,
            videos
          });
          console.log(`[API] \u641C\u7D22\u4E0A\u62A5\u6210\u529F: \u65B0\u589E${data?.new_videos || 0}\u4E2A\u89C6\u9891\uFF0C${data?.new_accounts || 0}\u4E2A\u8D26\u53F7`);
          return data;
        } catch (e) {
          console.error("[API] \u641C\u7D22\u4E0A\u62A5\u5931\u8D25:", e.message);
          return null;
        }
      }
    };
    module2.exports = DouyinAPI2;
  }
});

// services/DouyinCommentService.js
var require_DouyinCommentService = __commonJS({
  "services/DouyinCommentService.js"(exports2, module2) {
    init_prefix();
    var fs2 = require("fs");
    var path2 = require("path");
    function _isWithinAge(publishTime, maxAgeHours) {
      if (!publishTime || !maxAgeHours || maxAgeHours <= 0) return true;
      const now = Date.now();
      let m = publishTime.match(/(\d+)\u5c0f\u65f6\u524d/);
      if (m) return parseInt(m[1]) * 36e5 < maxAgeHours * 36e5;
      m = publishTime.match(/(\d+)\u5206\u949f\u524d/);
      if (m) return true;
      if (/\u521a\u521a|\d+\u79d2\u524d/.test(publishTime)) return true;
      if (/\u6628\u5929/.test(publishTime)) return maxAgeHours >= 24;
      m = publishTime.match(/(\d+)\u5929\u524d/);
      if (m) {
        const days = parseInt(m[1]);
        if (days === 0) return true;
        if (days === 1) return maxAgeHours >= 24;
        return days * 24 <= maxAgeHours;
      }
      m = publishTime.match(/(\d+)\u5468\u524d/);
      if (m) {
        const weeks = parseInt(m[1]);
        return weeks * 24 * 7 <= maxAgeHours;
      }
      m = publishTime.match(/(\d+)\u6708\u524d/);
      if (m) return false;
      m = publishTime.match(/(\d+)\u5e74\u524d/);
      if (m) return false;
      return true;
    }
    var DouyinCommentService2 = class {
      constructor(config2, browser, api) {
        this.config = config2;
        this.browser = browser;
        this.page = browser.page;
        this.api = api;
        const douyin = config2.douyin || {};
        this.maxScrollRounds = douyin.maxScrollRounds || 5;
        this.commentMaxScrollRounds = douyin.commentMaxScrollRounds || 20;
        this.commentUserDelay = douyin.commentUserDelay || 2500;
        this.maxExpandRounds = douyin.maxExpandRounds || 10;
        this.stats = { totalComments: 0, totalDouyinIds: 0, totalFailed: 0 };
        this.blacklistSet = /* @__PURE__ */ new Set();
        this.blacklistLastFetch = 0;
        this.logPath = path2.join(global.__original_dirname, "..", "client.log");
        this._log("=== \u5BA2\u6237\u7AEF\u542F\u52A8 ===");
      }
      _log(msg) {
        const ts = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
        const line = `[${ts}] ${msg}
`;
        try {
          fs2.appendFileSync(this.logPath, line);
        } catch (e) {
        }
      }
      async getUserVideos(uid) {
        const page2 = this.page;
        try {
          const currentUrl = page2.url();
          if (!currentUrl.includes(uid)) {
            this._log(`[video] \u5BFC\u822A\u5230\u7528\u6237\u9875: uid=${uid}`);
            console.log(`[video] \u5BFC\u822A\u5230\u7528\u6237\u9875: uid=${uid}`);
            await page2.goto(`https://www.douyin.com/user/${uid}`, {
              waitUntil: "domcontentloaded",
              timeout: 6e4
            });
            await this.sleep(8e3);
          }
          const debugInfo = await page2.evaluate(() => {
            return {
              url: location.href,
              hasPostList: !!document.querySelector('[data-e2e="user-post-list"]'),
              hasUserDetail: !!document.querySelector("#user_detail_element"),
              hasUlInDetail: !!document.querySelector("#user_detail_element ul"),
              allLinksCount: document.querySelectorAll('a[href*="/video/"], a[href*="/note/"]').length,
              bodyLength: document.body?.innerHTML?.length || 0,
              title: document.title || ""
            };
          });
          this._log(`[video] \u9875\u9762\u8C03\u8BD5: ${JSON.stringify(debugInfo)}`);
          console.log(`[video] \u9875\u9762\u8C03\u8BD5:`, JSON.stringify(debugInfo));
          const profile = await page2.evaluate(() => {
            const result = { nickname: "", douyin_id: "" };
            const h1 = document.querySelector("h1");
            if (!h1) return result;
            const fiberKey = Object.keys(h1).find((k) => k.startsWith("__reactFiber"));
            if (fiberKey) {
              let fiber = h1[fiberKey];
              let depth = 0;
              while (fiber && depth < 10) {
                const ui2 = fiber.memoizedProps?.userInfo;
                if (ui2) {
                  result.nickname = ui2.nickname || "";
                  result.douyin_id = ui2.uniqueId || "";
                  result.signature = ui2.desc || "";
                  result.gender = ui2.gender;
                  result.follower_count = ui2.followerCount || 0;
                  result.following_count = ui2.followingCount || 0;
                  result.aweme_count = ui2.awemeCount || 0;
                  result.favoriting_count = ui2.favoritingCount || 0;
                  result.total_favorited = ui2.totalFavorited || 0;
                  result.ip_location = ui2.ipLocation || "";
                  result.avatar_url = ui2.avatarUrl || "";
                  result.province = ui2.province || "";
                  result.city = ui2.city || "";
                  result.custom_verify = ui2.customVerify || "";
                  result.enterprise_verify_reason = ui2.enterpriseVerifyReason || "";
                  result.short_id = ui2.shortId || "";
                  break;
                }
                fiber = fiber.return;
                depth++;
              }
            }
            if (!result.nickname && h1) {
              result.nickname = (h1.textContent || "").trim().substring(0, 30) || "";
            }
            return result;
          });
          const videos = [];
          const seenIds = /* @__PURE__ */ new Set();
          let prevCount = 0;
          for (let scroll = 0; scroll < this.maxScrollRounds; scroll++) {
            const newVideos = await page2.evaluate(() => {
              const results = [];
              const listUl = document.querySelector('[data-e2e="user-post-list"]') || document.querySelector("#user_detail_element ul");
              if (!listUl) return results;
              const links = listUl.querySelectorAll('a[href*="/note/"], a[href*="/video/"]');
              links.forEach((link) => {
                const href = link.getAttribute("href") || "";
                const idMatch = href.match(/\/(note|video)\/(\d+)/);
                if (!idMatch) return;
                const videoId = idMatch[2];
                const videoType = idMatch[1];
                const p = link.querySelector("p");
                if (!p) return;
                let title = (p.textContent || "").trim();
                if (!title) return;
                const tags = [];
                const tagRegex = /#([^#\s]+)/g;
                let tagMatch;
                while ((tagMatch = tagRegex.exec(title)) !== null) {
                  tags.push(tagMatch[1]);
                }
                let createTime = null;
                let diggCount = 0;
                let commentCount = 0;
                let shareCount = 0;
                let collectCount = 0;
                const fiberKey = Object.keys(link).find((k) => k.startsWith("__reactFiber"));
                if (fiberKey) {
                  let fiber = link[fiberKey];
                  let depth = 0;
                  while (fiber && depth < 10) {
                    const ai = fiber.memoizedProps?.awemeInfo;
                    if (ai) {
                      createTime = ai.createTime || null;
                      if (ai.stats) {
                        diggCount = ai.stats.diggCount || 0;
                        commentCount = ai.stats.commentCount || 0;
                        shareCount = ai.stats.shareCount || 0;
                        collectCount = ai.stats.collectCount || 0;
                      }
                      break;
                    }
                    fiber = fiber.return;
                    depth++;
                  }
                }
                results.push({
                  video_id: videoId,
                  url: `https://www.douyin.com/${videoType}/${videoId}`,
                  title: title.substring(0, 200),
                  tags,
                  video_type: videoType,
                  create_time: createTime,
                  likes: diggCount,
                  comment_count: commentCount,
                  share_count: shareCount,
                  collect_count: collectCount
                });
              });
              return results;
            });
            for (const v of newVideos) {
              if (!seenIds.has(v.video_id)) {
                seenIds.add(v.video_id);
                try {
                  const coverBase64 = await page2.evaluate((vid) => {
                    const listUl = document.querySelector('[data-e2e="user-post-list"]') || document.querySelector("#user_detail_element ul");
                    if (!listUl) return null;
                    const links = listUl.querySelectorAll('a[href*="/note/"], a[href*="/video/"]');
                    for (const link of links) {
                      const href = link.getAttribute("href") || "";
                      const idMatch = href.match(/\/(note|video)\/(\d+)/);
                      if (idMatch && idMatch[2] === vid) {
                        const img = link.querySelector("img");
                        if (img && img.src) {
                          const canvas = document.createElement("canvas");
                          canvas.width = Math.min(img.naturalWidth || 320, 320);
                          canvas.height = Math.min(img.naturalHeight || 180, 180);
                          const ctx = canvas.getContext("2d");
                          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                          return canvas.toDataURL("image/jpeg", 0.6).split(",")[1] || null;
                        }
                      }
                    }
                    return null;
                  }, v.video_id);
                  if (coverBase64) v.cover_base64 = coverBase64;
                } catch (e) {
                }
                videos.push(v);
              }
            }
            console.log(`[video] scroll ${scroll + 1}, total ${videos.length}`);
            if (videos.length === prevCount) break;
            prevCount = videos.length;
            await page2.evaluate(() => window.scrollBy(0, 800));
            await this.sleep(4e3);
          }
          return { videos, profile };
        } catch (e) {
          console.error(`[video] getUserVideos failed: ${e.message}`);
          return { videos: [], profile: { nickname: "", douyin_id: "" } };
        }
      }
      async refreshBlacklist() {
        const now = Date.now();
        if (this.blacklistSet.size > 0 && now - this.blacklistLastFetch < 5 * 60 * 1e3) return;
        if (!this.api) return;
        try {
          const names = await this.api.get_blacklist();
          this.blacklistSet = new Set(names);
          this.blacklistLastFetch = now;
          console.log(`[blacklist] \u5DF2\u52A0\u8F7D ${this.blacklistSet.size} \u4E2A\u9ED1\u540D\u5355\u7528\u6237`);
        } catch (e) {
          console.warn(`[blacklist] \u52A0\u8F7D\u5931\u8D25: ${e.message}`);
        }
      }
      async getUserProfile(uid) {
        const page2 = this.page;
        try {
          await page2.goto(`https://www.douyin.com/user/${uid}`, {
            waitUntil: "domcontentloaded",
            timeout: 3e4
          }).catch(() => {
          });
          await this.sleep(8e3);
          const pageOk = await page2.evaluate(() => {
            return !!(document.querySelector("h1") || document.querySelector('[data-e2e="user-info"]') || document.querySelector('[data-e2e="user-tab"]') || document.body.innerText.length > 1e3);
          });
          if (!pageOk) {
            console.log(`[profile] user ${uid} page did not load properly`);
            return { nickname: "", douyin_id: "" };
          }
          const profile = await page2.evaluate(() => {
            const result = { nickname: "", douyin_id: "" };
            const h1 = document.querySelector("h1");
            if (h1) {
              const fiberKey = Object.keys(h1).find((k) => k.startsWith("__reactFiber"));
              if (fiberKey) {
                let fiber = h1[fiberKey];
                let depth = 0;
                while (fiber && depth < 10) {
                  const ui2 = fiber.memoizedProps?.userInfo;
                  if (ui2) {
                    result.nickname = ui2.nickname || "";
                    result.douyin_id = ui2.uniqueId || "";
                    result.signature = ui2.desc || "";
                    result.gender = ui2.gender;
                    result.follower_count = ui2.followerCount || 0;
                    result.following_count = ui2.followingCount || 0;
                    result.aweme_count = ui2.awemeCount || 0;
                    result.favoriting_count = ui2.favoritingCount || 0;
                    result.total_favorited = ui2.totalFavorited || 0;
                    result.ip_location = ui2.ipLocation || "";
                    result.avatar_url = ui2.avatarUrl || "";
                    result.province = ui2.province || "";
                    result.city = ui2.city || "";
                    result.custom_verify = ui2.customVerify || "";
                    result.enterprise_verify_reason = ui2.enterpriseVerifyReason || "";
                    result.short_id = ui2.shortId || "";
                    break;
                  }
                  fiber = fiber.return;
                  depth++;
                }
              }
            }
            if (!result.nickname && h1) {
              result.nickname = (h1.textContent || "").trim().substring(0, 30) || "";
            }
            return result;
          });
          return profile;
        } catch (e) {
          console.error(`[profile] getUserProfile failed: ${e.message}`);
          return { nickname: "", douyin_id: "" };
        }
      }
      async getCommentUserDouyinId(uid) {
        if (!uid) return "";
        const profile = await this.getUserProfile(uid);
        const did = profile.douyin_id || "";
        if (did) this.stats.totalDouyinIds++;
        return did;
      }
      async getVideoComments(videoId) {
        const page2 = this.page;
        try {
          try {
            await page2.goto(`https://www.douyin.com/video/${videoId}`, {
              waitUntil: "domcontentloaded",
              timeout: 3e4
            });
          } catch (e) {
            this._log(`[comment] page load timeout, continuing...`);
            console.log(`[comment] page load timeout, continuing...`);
          }
          const waitTime = 8e3 + Math.floor(Math.random() * 5e3);
          this._log(`[comment] \u7B49\u5F85\u9875\u9762\u52A0\u8F7D ${waitTime}ms...`);
          console.log(`[comment] \u7B49\u5F85\u9875\u9762\u52A0\u8F7D ${waitTime}ms...`);
          await this.sleep(waitTime);
          let videoInfo = null;
          try {
            videoInfo = await page2.evaluate(() => {
              const player = document.querySelector('[data-e2e="feed-active-video"]');
              if (!player) return null;
              const fiberKey = Object.keys(player).find((k) => k.startsWith("__reactFiber"));
              if (!fiberKey) return null;
              let fiber = player[fiberKey];
              let depth = 0;
              while (fiber && depth < 10) {
                const ai = fiber.memoizedProps?.awemeInfo;
                if (ai) {
                  let hashtags = [];
                  try {
                    const extras = typeof ai.textExtra === "string" ? JSON.parse(ai.textExtra) : ai.textExtra;
                    if (Array.isArray(extras)) {
                      hashtags = extras.filter((e) => e.hashtagName).map((e) => ({
                        id: e.hashtagId || "",
                        name: e.hashtagName
                      }));
                    }
                  } catch (e) {
                  }
                  let videoTags = [];
                  try {
                    const tags = typeof ai.videoTag === "string" ? JSON.parse(ai.videoTag) : ai.videoTag;
                    if (Array.isArray(tags)) {
                      videoTags = tags.map((t) => ({ id: t.tagId, name: t.tagName }));
                    }
                  } catch (e) {
                  }
                  let imageUrls = [];
                  try {
                    const imgs = typeof ai.images === "string" ? JSON.parse(ai.images) : ai.images;
                    if (Array.isArray(imgs)) {
                      imageUrls = imgs.map((img) => {
                        const urls = img.urlList || [];
                        return urls[0] || "";
                      }).filter((u) => u);
                    }
                  } catch (e) {
                  }
                  let musicTitle = "";
                  let musicAuthor = "";
                  try {
                    const m = typeof ai.music === "string" ? JSON.parse(ai.music) : ai.music;
                    if (m) {
                      musicTitle = m.title || "";
                      musicAuthor = m.author || "";
                    }
                  } catch (e) {
                  }
                  let shareUrl = "";
                  try {
                    const s = typeof ai.shareInfo === "string" ? JSON.parse(ai.shareInfo) : ai.shareInfo;
                    shareUrl = s?.shareUrl || "";
                  } catch (e) {
                  }
                  return {
                    comment_count: ai.stats?.commentCount || 0,
                    likes: ai.stats?.diggCount || 0,
                    share_count: ai.stats?.shareCount || 0,
                    collect_count: ai.stats?.collectCount || 0,
                    play_count: ai.stats?.playCount || 0,
                    title: (ai.desc || "").substring(0, 500),
                    create_time: ai.createTime || null,
                    author_nickname: ai.authorInfo?.nickname || null,
                    author_sec_uid: ai.authorInfo?.secUid || null,
                    author_follower_count: ai.authorInfo?.followerCount || 0,
                    media_type: ai.mediaType || null,
                    hashtags,
                    video_tags: videoTags,
                    image_urls: imageUrls,
                    share_url: shareUrl,
                    music_title: musicTitle,
                    music_author: musicAuthor
                  };
                }
                fiber = fiber.return;
                depth++;
              }
              return null;
            });
            if (videoInfo) {
              this._log(`[comment] \u89C6\u9891\u4FE1\u606F: \u8BC4\u8BBA${videoInfo.comment_count} \u70B9\u8D5E${videoInfo.likes} \u5206\u4EAB${videoInfo.share_count} \u6536\u85CF${videoInfo.collect_count}`);
              console.log(`[comment] \u89C6\u9891\u4FE1\u606F: \u8BC4\u8BBA${videoInfo.comment_count} \u70B9\u8D5E${videoInfo.likes} \u64AD\u653E${videoInfo.play_count}`);
            }
          } catch (e) {
            this._log(`[comment] WARN: \u63D0\u53D6\u89C6\u9891\u4FE1\u606F\u5931\u8D25: ${e.message}`);
          }
          try {
            for (let i = 0; i < 2; i++) {
              const x = Math.floor(Math.random() * 800 + 100);
              const y = Math.floor(Math.random() * 600 + 100);
              await page2.mouse.move(x, y, { steps: 10 + Math.floor(Math.random() * 10) });
              await this.sleep(500 + Math.floor(Math.random() * 1e3));
            }
          } catch (e) {
          }
          for (let round = 0; round < this.commentMaxScrollRounds; round++) {
            const prevLen = await page2.evaluate(() => document.body?.innerHTML?.length || 0);
            const scrollAmount = 300 + Math.floor(Math.random() * 500);
            await page2.evaluate((amount) => {
              window.scrollBy({ top: amount, behavior: "smooth" });
            }, scrollAmount);
            const delay = 1500 + Math.floor(Math.random() * 1500);
            await this.sleep(delay);
            const currLen = await page2.evaluate(() => document.body?.innerHTML?.length || 0);
            if (currLen === prevLen) break;
            this._log(`[comment] scroll ${round + 1}`);
            console.log(`[comment] scroll ${round + 1}`);
          }
          if (Math.random() > 0.5) {
            await page2.evaluate(() => window.scrollBy({ top: -200, behavior: "smooth" }));
            await this.sleep(800 + Math.floor(Math.random() * 1200));
            await page2.evaluate(() => window.scrollBy({ top: 300, behavior: "smooth" }));
            await this.sleep(1e3 + Math.floor(Math.random() * 1e3));
          }
          await this._expandAllReplies();
          await this.refreshBlacklist();
          const result = await this._extractCommentsJs(videoId);
          const comments = (result.comments || result).filter((c) => {
            if (this.blacklistSet.has(c.nickname || c.raw_nickname)) {
              console.log(`  \u2298 \u9ED1\u540D\u5355\u8FC7\u6EE4: ${c.nickname || c.raw_nickname}`);
              return false;
            }
            return true;
          });
          const timeFiltered = result.timeFiltered || 0;
          const dupFiltered = result.dupFiltered || 0;
          if (timeFiltered > 0) console.log(`[comment] \u8D85\u65F6\u8FC7\u6EE4 ${timeFiltered} \u6761 (max age: ${this.config.douyin?.commentMaxAgeHours || 24}h)`);
          if (dupFiltered > 0) console.log(`[comment] \u53BB\u91CD\u8FC7\u6EE4 ${dupFiltered} \u6761`);
          console.log(`[comment] total ${comments.length} (\u539F\u59CB + \u63D0\u53D6, \u53BB\u91CD\u548C\u8D85\u65F6\u540E)`);
          this.stats.totalComments += comments.length;
          return { comments, videoInfo };
        } catch (e) {
          this._log(`[comment] ERROR: getVideoComments failed: ${e.message}`);
          console.error(`[comment] getVideoComments failed: ${e.message}`);
          return { comments: [], videoInfo: null };
        }
      }
      async _expandAllReplies() {
        const page2 = this.page;
        try {
          for (let round = 0; round < this.maxExpandRounds; round++) {
            const expanded = await page2.evaluate(() => {
              let count = 0;
              document.querySelectorAll("span").forEach((sp) => {
                const t = (sp.textContent || "").trim();
                if (t.includes("\u5C55\u5F00") && t.includes("\u56DE\u590D")) {
                  sp.click();
                  count++;
                }
              });
              return count;
            });
            if (expanded === 0) break;
            this._log(`[comment] expanded ${expanded} replies`);
            console.log(`[comment] expanded ${expanded} replies`);
            await this.sleep(1e3);
          }
        } catch (e) {
          this._log(`[comment] WARN: expandReplies failed: ${e.message}`);
          console.warn(`[comment] expandReplies failed: ${e.message}`);
        }
      }
      async _extractCommentsJs(videoId) {
        const page2 = this.page;
        try {
          const json = await page2.evaluate((vid) => {
            const items = document.querySelectorAll('div[data-e2e="comment-item"]');
            const results = [];
            items.forEach((item) => {
              let nickname = "";
              let userUid = "";
              const infoWrap = item.querySelector('[class*="comment-item-info"]');
              if (infoWrap) {
                const links = infoWrap.querySelectorAll("a");
                for (const a of links) {
                  const href = a.getAttribute("href") || "";
                  if (!href.includes("/user/")) continue;
                  if ((a.innerHTML || "").includes("semi-avatar") || (a.innerHTML || "").includes("live-avatar")) continue;
                  const text = (a.textContent || "").trim();
                  if (text === "\u56DE\u590D") continue;
                  if (!text) continue;
                  nickname = text;
                  const m = href.match(/\/user\/([\w-]+)/);
                  if (m) userUid = m[1];
                  if (nickname) {
                    nickname = nickname.replace(/\s*\u4F5C\u8005\s*$/, "").replace(/\s*[Aa]uthor\s*$/, "").trim();
                  }
                  if (nickname) break;
                }
              } else {
                const itemLinks = item.querySelectorAll("a");
                for (const a of itemLinks) {
                  const href = a.getAttribute("href") || "";
                  if (!href.includes("/user/")) continue;
                  if ((a.innerHTML || "").includes("semi-avatar") || (a.innerHTML || "").includes("live-avatar")) continue;
                  const text = (a.textContent || "").trim();
                  if (text === "\u56DE\u590D") continue;
                  if (!text) continue;
                  nickname = text;
                  const m = href.match(/\/user\/([\w-]+)/);
                  if (m) userUid = m[1];
                  if (nickname) {
                    nickname = nickname.replace(/\s*\u4F5C\u8005\s*$/, "").replace(/\s*[Aa]uthor\s*$/, "").trim();
                  }
                  if (nickname) break;
                }
              }
              let content = "";
              const sp = item.querySelector("span.WFJiGxr7");
              if (sp) content = (sp.textContent || "").trim();
              if (!content || content.length < 2) return;
              let likes = 0;
              const p = item.querySelector("p.xZhLomAs");
              if (p) likes = parseInt(p.textContent || "0") || 0;
              let publishTime = "";
              const fullText = item.textContent || "";
              const tm = fullText.match(/(\d+[天周月年小时分钟秒前]+·\S+)/);
              if (tm) publishTime = tm[1];
              else {
                const tm2 = fullText.match(/(\d+[天周月年]前|\d+小时前|\d+分钟前|\d+秒前|刚刚|昨天)/);
                if (tm2) publishTime = tm2[1];
              }
              results.push({ nickname, user_uid: userUid, content, likes, publishTime });
            });
            return JSON.stringify(results);
          }, videoId);
          if (!json) return { comments: [], timeFiltered: 0, dupFiltered: 0 };
          const raw = JSON.parse(json);
          const seen = /* @__PURE__ */ new Set();
          const maxAgeHours = this.config.douyin?.commentMaxAgeHours || 24;
          let filtered = 0;
          let dupCount = 0;
          const result = raw.filter((c) => {
            const key = `${c.nickname}:${c.content}`;
            if (seen.has(key)) {
              dupCount++;
              return false;
            }
            seen.add(key);
            if (c.publishTime && maxAgeHours > 0) {
              if (!_isWithinAge(c.publishTime, maxAgeHours)) {
                filtered++;
                console.log(`  \u2298 \u8D85\u65F6\u8FC7\u6EE4: [${c.nickname || "\u533F\u540D"}] ${c.publishTime} - ${(c.content || "").substring(0, 30)}`);
                return false;
              }
            }
            return true;
          }).map((c) => ({
            raw_text: c.content,
            nickname: c.nickname || "",
            user_uid: c.user_uid || "",
            likes: c.likes || 0,
            publish_time: c.publishTime || "",
            comment_url: `https://www.douyin.com/video/${videoId}`,
            video_id: videoId
          }));
          return { comments: result, timeFiltered: filtered, dupFiltered: dupCount };
        } catch (e) {
          this._log(`[comment] ERROR: extractCommentsJs failed: ${e.message}`);
          console.error(`[comment] extractCommentsJs failed: ${e.message}`);
          return { comments: [], timeFiltered: 0, dupFiltered: 0 };
        }
      }
      /**
       * 搜索关键词，提取搜索结果中的视频和作者信息
       * 方案：直接从 DOM + React Fiber 提取 docId/标题/作者，无需点击卡片
       * 卡片选择器：div.search-result-card，数据在 React Fiber 的 memoizedProps.data 中
       */
      async searchKeyword(keyword, config2 = {}) {
        const page2 = this.page;
        const maxResults = config2.max_results || 20;
        const maxScrolls = config2.scroll_rounds || 3;
        try {
          console.log(`[search] \u641C\u7D22\u5173\u952E\u8BCD: ${keyword}`);
          await page2.goto(`https://www.douyin.com/search/${encodeURIComponent(keyword)}`, {
            waitUntil: "domcontentloaded",
            timeout: 3e4
          });
          await this.sleep(6e3);
          const allResults = [];
          const seenIds = /* @__PURE__ */ new Set();
          for (let scroll = 0; scroll < maxScrolls; scroll++) {
            const extracted = await page2.evaluate(() => {
              const cards = document.querySelectorAll("div.search-result-card");
              const results = [];
              cards.forEach((card) => {
                const text = card.innerText || "";
                if (text.startsWith("\u76F8\u5173\u641C\u7D22")) return;
                const fiberKey = Object.keys(card).find((k) => k.startsWith("__reactFiber"));
                if (!fiberKey) return;
                let fiber = card[fiberKey];
                let docId = null;
                let authorSecUid = "";
                let authorUid = "";
                let createTime = null;
                let diggCount = 0;
                let commentCount = 0;
                let shareCount = 0;
                let collectCount = 0;
                let depth = 0;
                while (fiber && depth < 8) {
                  const d = fiber.memoizedProps?.data;
                  if (d) {
                    if (!docId && d.docId) docId = d.docId;
                    if (d.awemeInfo) {
                      const ai = d.awemeInfo;
                      if (ai.authorInfo) {
                        if (ai.authorInfo.secUid) authorSecUid = ai.authorInfo.secUid;
                        if (ai.authorInfo.uid) authorUid = String(ai.authorInfo.uid);
                      }
                      if (ai.createTime && !createTime) createTime = ai.createTime;
                      if (ai.stats) {
                        diggCount = ai.stats.diggCount || 0;
                        commentCount = ai.stats.commentCount || 0;
                        shareCount = ai.stats.shareCount || 0;
                        collectCount = ai.stats.collectCount || 0;
                      }
                    }
                  }
                  fiber = fiber.return;
                  depth++;
                }
                if (!docId) return;
                const textParts = text.split("\n").map((p) => p.trim()).filter((p) => p);
                let type = "\u56FE\u6587";
                let author = "";
                let titleParts = [];
                for (const part of textParts) {
                  if (/^\d{1,2}:\d{2}$/.test(part)) type = "\u89C6\u9891";
                  else if (part === "\u56FE\u6587") type = "\u56FE\u6587";
                  else if (part.startsWith("@")) author = part.substring(1);
                  else if (part.length > 5 && !/^·/.test(part)) titleParts.push(part);
                }
                const title = titleParts.join(" ").substring(0, 300);
                const url = type === "\u89C6\u9891" ? `https://www.douyin.com/video/${docId}` : `https://www.douyin.com/note/${docId}`;
                let coverBase64 = null;
                try {
                  const img = card.querySelector('img[class*="FWkvEMo5"], div.LFQCShEn img, img');
                  if (img && img.src && !img.src.startsWith("data:")) {
                    const canvas = document.createElement("canvas");
                    canvas.width = Math.min(img.naturalWidth || 320, 320);
                    canvas.height = Math.min(img.naturalHeight || 180, 180);
                    const ctx = canvas.getContext("2d");
                    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                    const dataUrl = canvas.toDataURL("image/jpeg", 0.6);
                    if (dataUrl && dataUrl.length > 100) {
                      coverBase64 = dataUrl.split(",")[1];
                    }
                  }
                } catch (e) {
                }
                results.push({
                  docId,
                  type,
                  author,
                  title,
                  url,
                  coverBase64,
                  authorSecUid,
                  authorUid,
                  createTime,
                  // Unix时间戳
                  diggCount,
                  // 点赞数（从stats，比文本解析更准）
                  commentCount,
                  // 评论数
                  shareCount,
                  // 分享数
                  collectCount
                  // 收藏数
                });
              });
              return results;
            });
            let newCount = 0;
            for (const item of extracted) {
              if (seenIds.has(item.docId)) continue;
              seenIds.add(item.docId);
              allResults.push({
                video_id: item.docId,
                title: item.title || "",
                author: item.author || "",
                author_uid: item.authorSecUid || "",
                url: item.url,
                cover_base64: item.coverBase64 || null,
                video_type: item.type === "\u89C6\u9891" ? "video" : "note",
                likes: item.diggCount || 0,
                create_time: item.createTime || null,
                comment_count: item.commentCount || 0,
                share_count: item.shareCount || 0,
                collect_count: item.collectCount || 0
              });
              newCount++;
            }
            console.log(`[search] scroll ${scroll + 1}, \u65B0\u589E ${newCount}, \u7D2F\u8BA1 ${allResults.length}`);
            if (allResults.length >= maxResults) break;
            await page2.evaluate(() => window.scrollBy(0, 1500));
            await this.sleep(3e3);
          }
          console.log(`[search] \u641C\u7D22\u5B8C\u6210: \u5171\u63D0\u53D6 ${allResults.length} \u4E2A\u7ED3\u679C`);
          return { videos: allResults.slice(0, maxResults) };
        } catch (e) {
          console.error(`[search] searchKeyword failed: ${e.message}`);
          this._log(`[search] ERROR: searchKeyword failed: ${e.message}`);
          return { videos: [] };
        }
      }
      /**
       * 关闭搜索模态窗（按 ESC 或点击关闭按钮）
       */
      async _closeSearchModal() {
        try {
          const page2 = this.page;
          const closed = await page2.evaluate(() => {
            const closeBtn = document.querySelector('button[aria-label="\u5173\u95ED"], div[class*="close"] button, svg[class*="close"]');
            if (closeBtn) {
              closeBtn.click();
              return true;
            }
            return false;
          });
          if (!closed) {
            await page2.keyboard.press("Escape");
          }
        } catch (e) {
          try {
            await page.keyboard.press("Escape");
          } catch (e2) {
          }
        }
      }
      getStats() {
        return { ...this.stats };
      }
      sleep(ms) {
        return new Promise((r) => setTimeout(r, ms));
      }
    };
    module2.exports = DouyinCommentService2;
  }
});

// index.js
init_prefix();
var fs = require("fs");
var path = require("path");
var readline = require("readline");
var BrowserAutomation = require_BrowserAutomation();
var DouyinAPI = require_DouyinAPI();
var DouyinCommentService = require_DouyinCommentService();
var DouyinMonitorClient = class {
  constructor(config2, mode2) {
    this.config = config2;
    this.mode = mode2;
    this.isRunning = false;
    this.isOffline = false;
    process.env.CLIENT_TYPE = `douyin-monitor${mode2 ? "-" + mode2 : ""}`;
    this.browser = new BrowserAutomation(config2);
    this.service = null;
    this.api = null;
    this.heartbeatFailCount = 0;
    this.maxHeartbeatFail = 3;
    this.startTime = Date.now();
    this.taskStats = { video: { total: 0, success: 0, fail: 0 }, comment: { total: 0, success: 0, fail: 0 }, douyinId: { total: 0, success: 0, fail: 0 }, search: { total: 0, success: 0, fail: 0 } };
    this.lastTaskType = null;
    this.rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    this._setupInputListener();
  }
  _setupInputListener() {
    this.rl.on("line", (input) => {
      const cmd = input.trim().toLowerCase();
      if (cmd === "y" && this.isOffline) {
        console.log("\n\u{1F504} \u6B63\u5728\u6062\u590D...");
        this.isOffline = false;
        console.log("\u2705 \u5DF2\u6062\u590D\u5728\u7EBF\uFF0C\u7EE7\u7EED\u6267\u884C\u4EFB\u52A1\n");
      }
    });
  }
  async start() {
    this._printHeader();
    try {
      await this._startBrowser();
      await this._startService();
      this._printSeparator();
      console.log("\u2705 \u5BA2\u6237\u7AEF\u542F\u52A8\u5B8C\u6210");
      this._printSeparator();
      console.log("");
      console.log("\u{1F504} \u6B63\u5728\u62C9\u53D6\u4EFB\u52A1...");
      console.log("\u{1F4A1} \u6309 Ctrl+C \u505C\u6B62\u8FD0\u884C");
      console.log("");
      this.isRunning = true;
      this._taskLoopPromise = this._taskLoop();
      this._heartbeatPromise = this._heartbeatLoop();
      await Promise.all([this._taskLoopPromise, this._heartbeatPromise]);
    } catch (error) {
      await this._cleanup(1, error.message);
    }
  }
  _printHeader() {
    console.log("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557");
    console.log("\u2551   \u6296\u97F3\u8BC4\u8BBA\u91C7\u96C6\u5BA2\u6237\u7AEF v1.0 (Puppeteer)                \u2551");
    console.log("\u2551   Douyin Comment Monitor Client                      \u2551");
    console.log("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D");
    console.log("");
  }
  _printSeparator() {
    console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");
  }
  /**
   * 启动浏览器 + 登录检测
   */
  async _startBrowser() {
    console.log("\u2501\u2501\u2501 \u7B2C\u4E00\u6B65: \u542F\u52A8\u6D4F\u89C8\u5668 \u2501\u2501\u2501");
    await this.browser.launch();
    console.log("\u2705 \u6D4F\u89C8\u5668\u5DF2\u542F\u52A8");
    try {
      await this.browser.page.goto("https://www.douyin.com", {
        waitUntil: "domcontentloaded",
        timeout: 15e3
      });
      await this.sleep(2e3);
    } catch (e) {
      console.warn(`\u26A0\uFE0F \u6253\u5F00\u6296\u97F3\u5931\u8D25: ${e.message}`);
    }
    console.log("");
    console.log("\u2501\u2501\u2501 \u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u767B\u5F55 \u2501\u2501\u2501");
    console.log("1. \u5728\u5F39\u51FA\u7684\u6D4F\u89C8\u5668\u4E2D\u767B\u5F55\u6296\u97F3");
    console.log("2. \u767B\u5F55\u6210\u529F\u540E\u7CFB\u7EDF\u5C06\u81EA\u52A8\u68C0\u6D4B");
    console.log("");
    const loginOk = await this._waitForDouyinLogin();
    if (!loginOk) {
      throw new Error("\u767B\u5F55\u8D85\u65F6\uFF0C\u8BF7\u767B\u5F55\u540E\u91CD\u65B0\u542F\u52A8\u5BA2\u6237\u7AEF");
    }
  }
  /**
   * 等待抖音登录
   */
  async _waitForDouyinLogin(maxWaitMs = 3e5, checkIntervalMs = 5e3) {
    const startTime = Date.now();
    while (Date.now() - startTime < maxWaitMs) {
      const elapsed = Math.floor((Date.now() - startTime) / 1e3);
      try {
        const loggedIn = await this._checkDouyinLogin();
        if (loggedIn) {
          console.log(`
\u2705 \u767B\u5F55\u9A8C\u8BC1\u901A\u8FC7\uFF01\uFF08\u8017\u65F6 ${elapsed} \u79D2\uFF09`);
          return true;
        }
        process.stdout.write(`\r\u23F3 \u7B49\u5F85\u767B\u5F55... (${elapsed}s)   `);
        process.stdout.flush?.();
      } catch (e) {
        process.stdout.write(`\r\u23F3 \u68C0\u6D4B\u4E2D... (${elapsed}s) [${e.message}]   `);
        process.stdout.flush?.();
      }
      await this.sleep(checkIntervalMs);
    }
    console.log("\n\u274C \u767B\u5F55\u8D85\u65F6");
    return false;
  }
  /**
   * 检测抖音登录状态
   */
  async _checkDouyinLogin() {
    const page2 = this.browser.page;
    if (!page2 || page2.isClosed()) return false;
    try {
      const url = page2.url();
      if (url.includes("login") || url.includes("passport") || url.includes("sso")) {
        return false;
      }
      const hasLoginBtn = await page2.evaluate(() => {
        const btn = document.querySelector('div[data-e2e="login-guide-button"]');
        return !!btn;
      });
      if (hasLoginBtn) return false;
      const cookies = await page2.cookies();
      const sessionCookie = cookies.find((c) => c.name === "sessionid");
      const sidTtCookie = cookies.find((c) => c.name === "sid_tt");
      if (!sessionCookie && !sidTtCookie) {
        return false;
      }
      if (sessionCookie && sessionCookie.value.length < 20) {
        return false;
      }
      if (sidTtCookie && sidTtCookie.value.length < 20) {
        return false;
      }
      const pageText = await page2.evaluate(() => {
        return document.body ? document.body.innerText.substring(0, 500) : "";
      });
      if (pageText.includes("\u767B\u5F55\u540E") && pageText.includes("\u7545\u4EAB")) {
        return false;
      }
      return true;
    } catch (e) {
      return false;
    }
  }
  /**
   * 初始化采集服务
   */
  async _startService() {
    console.log("");
    console.log("\u2501\u2501\u2501 \u7B2C\u4E8C\u6B65: \u521D\u59CB\u5316\u670D\u52A1 \u2501\u2501\u2501");
    this.api = new DouyinAPI(this.config, this.mode);
    this.service = new DouyinCommentService(this.config, this.browser, this.api);
    const settings = await this.api.fetch_settings();
    if (settings) {
      if (!this.config.douyin) this.config.douyin = {};
      if (settings.comment_max_age_hours != null) {
        this.config.douyin.commentMaxAgeHours = settings.comment_max_age_hours;
      }
    }
    console.log("\u2705 \u91C7\u96C6\u670D\u52A1\u5DF2\u521D\u59CB\u5316");
  }
  /**
   * 任务主循环
   */
  async _taskLoop() {
    const fetchInterval = this.config.task?.fetchInterval || 3e4;
    while (this.isRunning) {
      try {
        if (this.isOffline) {
          await this.sleep(5e3);
          continue;
        }
        const task = await this.api.get_next_task();
        if (task) {
          const typeMap = { check_account: "\u89C6\u9891", fetch_comments: "\u8BC4\u8BBA", fetch_douyin_id: "\u6296\u97F3\u53F7", search_keyword: "\u641C\u7D22" };
          const typeKeyMap = { check_account: "video", fetch_comments: "comment", fetch_douyin_id: "douyinId", search_keyword: "search" };
          const typeLabel = typeMap[task.task_type] || task.task_type;
          const typeKey = typeKeyMap[task.task_type] || "video";
          console.log(`
\u2501\u2501\u2501 \u62C9\u53D6\u5230\u4EFB\u52A1: ${typeLabel} \u2501\u2501\u2501`);
          this.lastTaskType = typeLabel;
          this.taskStats[typeKey].total++;
          await this._executeTask(task, typeKey, typeLabel);
          console.log(`\u2501\u2501\u2501 \u4EFB\u52A1\u5B8C\u6210 \u2501\u2501\u2501
`);
          this._printStatsBrief();
          await this.sleep(2e3);
        } else {
          await this.sleep(fetchInterval);
        }
      } catch (e) {
        console.error(`[\u4E3B\u5FAA\u73AF] \u5F02\u5E38: ${e.message}`);
        await this.sleep(5e3);
      }
    }
  }
  /**
   * 执行单个任务
   */
  async _executeTask(task, typeKey, typeLabel) {
    const taskType = task.task_type;
    const taskId = task.task_id || task._id;
    try {
      if (taskType === "check_account") {
        await this._handleCheckAccount(task, taskId);
      } else if (taskType === "fetch_comments") {
        await this._handleFetchComments(task, taskId);
      } else if (taskType === "fetch_douyin_id") {
        await this._handleFetchDouyinId(task, taskId);
      } else if (taskType === "search_keyword") {
        await this._handleSearchKeyword(task, taskId);
      } else {
        await this.api.fail_task(taskId, `\u672A\u77E5\u4EFB\u52A1\u7C7B\u578B: ${taskType}`);
      }
      this.taskStats[typeKey].success++;
    } catch (e) {
      this.taskStats[typeKey].fail++;
      await this.api.fail_task(taskId, `\u6267\u884C\u5F02\u5E38: ${e.message}`);
    }
  }
  /**
   * 处理 search_keyword 任务
   */
  async _handleSearchKeyword(task, taskId) {
    const keyword = task.keyword;
    if (!keyword) {
      await this.api.fail_task(taskId, "\u7F3A\u5C11\u641C\u7D22\u5173\u952E\u8BCD");
      return;
    }
    console.log(`[\u4EFB\u52A1] \u641C\u7D22\u5173\u952E\u8BCD: ${keyword}`);
    const { videos } = await this.service.searchKeyword(keyword, {
      max_results: 20,
      scroll_rounds: 3
    });
    if (videos.length === 0) {
      await this.api.complete_task(taskId, { video_count: 0, message: "\u65E0\u641C\u7D22\u7ED3\u679C" });
      return;
    }
    console.log(`[\u641C\u7D22] \u53D1\u73B0 ${videos.length} \u4E2A\u89C6\u9891\uFF0C\u4E0A\u62A5\u4E2D...`);
    const result = await this.api.report_search_results(keyword, videos);
    if (result) {
      console.log(`[\u4EFB\u52A1] \u2705 \u641C\u7D22\u4E0A\u62A5\u6210\u529F: ${result.message}`);
    }
    await this.api.complete_task(taskId, {
      video_count: videos.length,
      new_videos: result?.new_videos || 0,
      new_accounts: result?.new_accounts || 0
    });
  }
  /**
   * 处理 check_account 任务
   */
  async _handleCheckAccount(task, taskId) {
    const accountId = task.target_id;
    const uid = task.target_uid;
    if (!uid) {
      await this.api.fail_task(taskId, "\u7F3A\u5C11 target_uid");
      return;
    }
    console.log(`[\u4EFB\u52A1] \u83B7\u53D6\u7528\u6237\u89C6\u9891: ${uid}`);
    const { videos, profile } = await this.service.getUserVideos(uid);
    if (profile.nickname || profile.douyin_id) {
      await this.api.update_account_profile(accountId, profile);
      console.log(`[\u4EFB\u52A1] \u66F4\u65B0\u8D26\u53F7\u4FE1\u606F: ${profile.nickname} (douyin_id=${profile.douyin_id})`);
    }
    const authorName = profile.nickname || "";
    if (authorName) {
      for (const v of videos) {
        v.author = authorName;
      }
    }
    if (videos.length === 0) {
      await this.api.complete_task(taskId, { video_count: 0, message: "\u65E0\u89C6\u9891\u6216\u83B7\u53D6\u5931\u8D25" });
      return;
    }
    const knownIds = await this.api.get_known_videos(accountId);
    const knownSet = new Set(knownIds);
    if (knownSet.size > 0) {
      console.log(`[\u89C6\u9891] \u5DF2\u77E5\u89C6\u9891 ${knownSet.size} \u4E2A\uFF0C\u5C06\u8DF3\u8FC7`);
    }
    const newVideos = videos.filter((v) => {
      if (!v.title) return false;
      if (knownSet.has(v.video_id)) return false;
      return true;
    });
    console.log(`[\u89C6\u9891] \u65B0\u89C6\u9891 ${newVideos.length} \u4E2A\uFF0C\u6279\u91CF\u4E0A\u62A5...`);
    if (newVideos.length > 0) {
      const ok = await this.api.report_videos(accountId, newVideos);
      if (ok) {
        console.log(`[\u4EFB\u52A1] \u2705 \u4E0A\u62A5 ${newVideos.length} \u4E2A\u65B0\u89C6\u9891`);
      }
    }
    await this.api.complete_task(taskId, { video_count: newVideos.length, skipped_count: knownSet.size });
  }
  /**
   * 处理 fetch_comments 任务
   */
  async _handleFetchComments(task, taskId) {
    const videoDbId = task.target_id;
    const videoId = task.target_video_id;
    if (!videoId) {
      await this.api.fail_task(taskId, "\u7F3A\u5C11 target_video_id");
      return;
    }
    const videoTitle = task.video_title || "";
    console.log(`
[\u4EFB\u52A1] \u83B7\u53D6\u89C6\u9891\u8BC4\u8BBA: ${videoId}`);
    console.log(`  \u89C6\u9891\u6807\u9898: ${videoTitle || "\u672A\u77E5"}`);
    const { comments, videoInfo } = await this.service.getVideoComments(videoId);
    if (videoInfo) {
      await this.api.update_video_stats(videoDbId, videoInfo);
    }
    if (comments.length === 0) {
      console.log(`[\u4EFB\u52A1] \u8BE5\u89C6\u9891\u65E0\u8BC4\u8BBA\u6216\u672A\u6293\u5230\u8BC4\u8BBA
`);
      await this.api.complete_task(taskId, { comment_count: 0, message: "\u65E0\u8BC4\u8BBA\u6216\u83B7\u53D6\u5931\u8D25" });
      return;
    }
    console.log(`[\u4EFB\u52A1] \u6293\u53D6\u5230 ${comments.length} \u6761\u8BC4\u8BBA\uFF0C\u6279\u91CF\u4E0A\u62A5...`);
    const ok = await this.api.report_comments(videoDbId, comments);
    if (ok) {
      console.log(`[\u4EFB\u52A1] \u2705 \u4E0A\u62A5 ${comments.length} \u6761\u8BC4\u8BBA`);
    } else {
      console.log("[\u4EFB\u52A1] \u8BC4\u8BBA\u4E0A\u62A5\u5931\u8D25");
    }
    await this.api.complete_task(taskId, { comment_count: comments.length });
  }
  /**
   * 处理 fetch_douyin_id 任务
   * 服务端已 AI 匹配的评论，客户端去取用户抖音号
   */
  async _handleFetchDouyinId(task, taskId) {
    const commentId = task.target_id;
    const userUid = task.target_uid;
    if (!userUid) {
      await this.api.fail_task(taskId, "\u7F3A\u5C11 target_uid");
      return;
    }
    console.log(`[\u4EFB\u52A1] \u83B7\u53D6\u8BC4\u8BBA\u7528\u6237\u6296\u97F3\u53F7: uid=${userUid}`);
    const douyinId = await this.service.getCommentUserDouyinId(userUid);
    if (douyinId) {
      console.log(`[\u4EFB\u52A1] \u2705 \u83B7\u53D6\u5230\u6296\u97F3\u53F7: ${douyinId}`);
      const ok = await this.api.report_douyin_id(commentId, douyinId);
      if (ok) {
        console.log("[\u4EFB\u52A1] \u6296\u97F3\u53F7\u5DF2\u4E0A\u62A5");
      }
    } else {
      console.log("[\u4EFB\u52A1] \u2298 \u672A\u83B7\u53D6\u5230\u6296\u97F3\u53F7");
    }
    await this.api.complete_task(taskId, { douyin_id: douyinId || null });
  }
  /**
   * 心跳循环
   */
  async _heartbeatLoop() {
    const interval = this.config.heartbeat?.interval || 6e4;
    let heartbeatCount = 0;
    while (this.isRunning) {
      try {
        const ok = await this.api.heartbeat("\u6B63\u5E38\u8FD0\u884C\u4E2D");
        if (ok) {
          this.heartbeatFailCount = 0;
          heartbeatCount++;
          this._printStatsBrief();
          if (heartbeatCount % 10 === 0) {
            const settings = await this.api.fetch_settings();
            if (settings && settings.comment_max_age_hours != null) {
              if (!this.config.douyin) this.config.douyin = {};
              this.config.douyin.commentMaxAgeHours = settings.comment_max_age_hours;
            }
          }
        } else {
          this.heartbeatFailCount++;
          if (this.heartbeatFailCount >= this.maxHeartbeatFail) {
            console.log(`[\u8B66\u544A] \u8FDE\u7EED ${this.heartbeatFailCount} \u6B21\u5FC3\u8DF3\u5931\u8D25\uFF0C\u53EF\u80FD\u5DF2\u6389\u7EBF`);
            const loggedIn = await this._checkDouyinLogin();
            if (!loggedIn) {
              this.isOffline = true;
              console.log("[\u6389\u7EBF] \u6296\u97F3\u767B\u5F55\u5DF2\u5931\u6548");
              console.log("[\u63D0\u793A] \u91CD\u65B0\u767B\u5F55\u540E\uFF0C\u8F93\u5165 y \u6062\u590D");
            }
          }
        }
        await this.sleep(interval);
      } catch (e) {
        console.error(`[\u5FC3\u8DF3] \u5F02\u5E38: ${e.message}`);
        await this.sleep(5e3);
      }
    }
  }
  /**
   * 优雅退出
   */
  async _cleanup(code = 0, reason = "") {
    console.log("\n\u23F9\uFE0F  \u6B63\u5728\u6E05\u7406\u8D44\u6E90...");
    this.isRunning = false;
    try {
      if (this.browser) await this.browser.close();
    } catch (e) {
    }
    if (this.rl) this.rl.close();
    if (reason) {
      console.log(`\u274C \u9000\u51FA\u539F\u56E0: ${reason}`);
    } else {
      console.log("\u2705 \u5BA2\u6237\u7AEF\u5DF2\u505C\u6B62");
    }
    this._printStats();
    process.exit(code);
  }
  _printStatsBrief() {
    const s = this.taskStats;
    const total = s.video.total + s.comment.total + s.douyinId.total;
    const runMin = Math.floor((Date.now() - this.startTime) / 6e4);
    const runStr = runMin < 60 ? `${runMin}\u5206\u949F` : `${Math.floor(runMin / 60)}h${runMin % 60}m`;
    const parts = [];
    if (s.video.total > 0) parts.push(`\u89C6\u9891${s.video.total}(\u2705${s.video.success}\u274C${s.video.fail})`);
    if (s.comment.total > 0) parts.push(`\u8BC4\u8BBA${s.comment.total}(\u2705${s.comment.success}\u274C${s.comment.fail})`);
    if (s.douyinId.total > 0) parts.push(`\u6296\u97F3\u53F7${s.douyinId.total}(\u2705${s.douyinId.success}\u274C${s.douyinId.fail})`);
    if (s.search.total > 0) parts.push(`\u641C\u7D22${s.search.total}(\u2705${s.search.success}\u274C${s.search.fail})`);
    console.log(`\u{1F4CA} [\u7EDF\u8BA1] \u8FD0\u884C${runStr} | \u5171${total}\u4E2A: ${parts.join(", ")}${this.lastTaskType ? " | \u5F53\u524D\u4EFB\u52A1\u7C7B\u578B: " + this.lastTaskType : ""}`);
  }
  _printStats() {
    const apiStats = this.api?.stats || {};
    const serviceStats = this.service?.getStats() || {};
    console.log("");
    console.log("\u{1F4C8} \u8FD0\u884C\u7EDF\u8BA1:");
    console.log(`   - \u89C6\u9891: ${apiStats.videosChecked || 0} | \u8BC4\u8BBA: ${apiStats.commentsFetched || 0}`);
    console.log(`   - \u4EFB\u52A1\u5B8C\u6210: ${apiStats.tasksCompleted || 0} | \u5931\u8D25: ${apiStats.tasksFailed || 0}`);
    console.log(`   - \u6296\u97F3\u53F7\u83B7\u53D6: ${serviceStats.totalDouyinIds || 0}`);
  }
  sleep(ms) {
    return new Promise((resolve5) => setTimeout(resolve5, ms));
  }
};
var args = process.argv.slice(2);
var mode = null;
for (let i = 0; i < args.length; i++) {
  if (args[i] === "--mode" && args[i + 1]) {
    mode = args[i + 1];
    if (!["video", "comment"].includes(mode)) {
      console.error(`\u274C \u65E0\u6548\u7684 mode: ${mode}\uFF0C\u53EF\u9009: video, comment`);
      process.exit(1);
    }
    i++;
  }
}
var configPath = path.join(global.__original_dirname, "config.json");
var config;
try {
  config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
} catch (e) {
  console.error(`\u274C \u52A0\u8F7D\u914D\u7F6E\u5931\u8D25: ${e.message}`);
  process.exit(1);
}
var modeLabel = mode ? ` [${mode}]` : "";
var banner = `\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`;
console.log(`
${banner}`);
console.log(`  \u6296\u97F3\u76D1\u63A7\u5BA2\u6237\u7AEF${modeLabel}`);
console.log(`  \u6A21\u5F0F: ${mode || "\u5168\u90E8\u4EFB\u52A1"}`);
console.log(`${banner}
`);
var client = new DouyinMonitorClient(config, mode);
process.on("SIGINT", async () => {
  await client._cleanup(0);
});
process.on("SIGTERM", async () => {
  await client._cleanup(0);
});
process.on("uncaughtException", (error) => {
  console.error("\u274C \u672A\u6355\u83B7\u5F02\u5E38 (uncaughtException):", error?.message || error);
  console.error("   Stack:", error?.stack?.substring(0, 500) || "N/A");
});
process.on("unhandledRejection", (reason) => {
  console.error("\u274C \u672A\u5904\u7406\u7684Promise\u62D2\u7EDD (unhandledRejection):", reason?.message || reason);
});
client.start().catch((error) => {
  console.error("\u274C \u542F\u52A8\u5931\u8D25:", error);
  process.exit(1);
});
/*! Bundled license information:

puppeteer-core/lib/cjs/puppeteer/util/disposable.js:
puppeteer-core/lib/cjs/puppeteer/api/ElementHandleSymbol.js:
puppeteer-core/lib/cjs/puppeteer/util/Function.js:
puppeteer-core/lib/cjs/puppeteer/common/HandleIterator.js:
puppeteer-core/lib/cjs/puppeteer/common/QueryHandler.js:
puppeteer-core/lib/cjs/puppeteer/common/CSSQueryHandler.js:
puppeteer-core/lib/cjs/puppeteer/common/CustomQueryHandler.js:
puppeteer-core/lib/cjs/puppeteer/common/PierceQueryHandler.js:
puppeteer-core/lib/cjs/puppeteer/common/PQueryHandler.js:
puppeteer-core/lib/cjs/puppeteer/common/PSelectorParser.js:
puppeteer-core/lib/cjs/puppeteer/common/TextQueryHandler.js:
puppeteer-core/lib/cjs/puppeteer/common/XPathQueryHandler.js:
puppeteer-core/lib/cjs/puppeteer/common/GetQueryHandler.js:
puppeteer-core/lib/cjs/puppeteer/util/decorators.js:
puppeteer-core/lib/cjs/puppeteer/api/JSHandle.js:
puppeteer-core/lib/cjs/puppeteer/api/ElementHandle.js:
puppeteer-core/lib/cjs/puppeteer/api/Frame.js:
puppeteer-core/lib/cjs/puppeteer/api/HTTPResponse.js:
puppeteer-core/lib/cjs/puppeteer/api/Realm.js:
puppeteer-core/lib/cjs/puppeteer/api/Target.js:
puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js:
puppeteer-core/lib/cjs/puppeteer/cdp/FrameManagerEvents.js:
puppeteer-core/lib/cjs/puppeteer/cdp/cdp.js:
puppeteer-core/lib/cjs/puppeteer/bidi/BidiOverCdp.js:
puppeteer-core/lib/cjs/puppeteer/bidi/Deserializer.js:
puppeteer-core/lib/cjs/puppeteer/bidi/JSHandle.js:
puppeteer-core/lib/cjs/puppeteer/bidi/ElementHandle.js:
puppeteer-core/lib/cjs/puppeteer/bidi/ExposedFunction.js:
puppeteer-core/lib/cjs/puppeteer/bidi/Serializer.js:
puppeteer-core/lib/cjs/puppeteer/bidi/util.js:
puppeteer-core/lib/cjs/puppeteer/bidi/Frame.js:
puppeteer-core/lib/cjs/puppeteer/bidi/Target.js:
puppeteer-core/lib/cjs/puppeteer/bidi/BrowserConnector.js:
@puppeteer/browsers/lib/cjs/browser-data/types.js:
@puppeteer/browsers/lib/cjs/httpUtil.js:
@puppeteer/browsers/lib/cjs/browser-data/chrome.js:
@puppeteer/browsers/lib/cjs/browser-data/chrome-headless-shell.js:
@puppeteer/browsers/lib/cjs/browser-data/chromedriver.js:
@puppeteer/browsers/lib/cjs/browser-data/chromium.js:
@puppeteer/browsers/lib/cjs/browser-data/firefox.js:
@puppeteer/browsers/lib/cjs/browser-data/browser-data.js:
@puppeteer/browsers/lib/cjs/detectPlatform.js:
@puppeteer/browsers/lib/cjs/Cache.js:
@puppeteer/browsers/lib/cjs/debug.js:
@puppeteer/browsers/lib/cjs/launch.js:
@puppeteer/browsers/lib/cjs/fileUtil.js:
@puppeteer/browsers/lib/cjs/CLI.js:
@puppeteer/browsers/lib/cjs/main.js:
puppeteer-core/lib/cjs/puppeteer/common/BrowserConnector.js:
puppeteer-core/lib/cjs/puppeteer/node/util/fs.js:
puppeteer-core/lib/cjs/puppeteer/node/ChromeLauncher.js:
puppeteer-core/lib/cjs/puppeteer/node/FirefoxLauncher.js:
puppeteer-core/lib/cjs/puppeteer/node/ScreenRecorder.js:
  (**
   * @license
   * Copyright 2023 Google Inc.
   * SPDX-License-Identifier: Apache-2.0
   *)

puppeteer-core/lib/cjs/puppeteer/common/EventEmitter.js:
puppeteer-core/lib/cjs/puppeteer/util/ErrorLike.js:
puppeteer-core/lib/cjs/puppeteer/common/LazyArg.js:
puppeteer-core/lib/cjs/puppeteer/common/WaitTask.js:
puppeteer-core/lib/cjs/puppeteer/api/api.js:
puppeteer-core/lib/cjs/puppeteer/common/NetworkManagerEvents.js:
puppeteer-core/lib/cjs/puppeteer/cdp/DeviceRequestPrompt.js:
puppeteer-core/lib/cjs/puppeteer/cdp/IsolatedWorlds.js:
puppeteer-core/lib/cjs/puppeteer/cdp/FrameTree.js:
puppeteer-core/lib/cjs/puppeteer/cdp/NetworkEventManager.js:
puppeteer-core/lib/cjs/puppeteer/cdp/TargetManager.js:
puppeteer-core/lib/cjs/puppeteer/bidi/Page.js:
puppeteer-core/lib/cjs/puppeteer/bidi/BrowserContext.js:
puppeteer-core/lib/cjs/puppeteer/bidi/Browser.js:
puppeteer-core/lib/cjs/puppeteer/bidi/bidi.js:
puppeteer-core/lib/cjs/puppeteer/common/common.js:
puppeteer-core/lib/cjs/puppeteer/util/util.js:
puppeteer-core/lib/cjs/puppeteer/node/node.js:
  (**
   * @license
   * Copyright 2022 Google Inc.
   * SPDX-License-Identifier: Apache-2.0
   *)

puppeteer-core/lib/cjs/puppeteer/environment.js:
puppeteer-core/lib/cjs/puppeteer/util/assert.js:
puppeteer-core/lib/cjs/puppeteer/common/Debug.js:
puppeteer-core/lib/cjs/puppeteer/common/PDFOptions.js:
puppeteer-core/lib/cjs/puppeteer/common/AriaQueryHandler.js:
puppeteer-core/lib/cjs/puppeteer/common/ConsoleMessage.js:
puppeteer-core/lib/cjs/puppeteer/common/FileChooser.js:
puppeteer-core/lib/cjs/puppeteer/common/SecurityDetails.js:
puppeteer-core/lib/cjs/puppeteer/cdp/BrowserConnector.js:
puppeteer-core/lib/cjs/puppeteer/node/LaunchOptions.js:
puppeteer-core/lib/cjs/puppeteer/common/TaskQueue.js:
puppeteer-core/lib/cjs/puppeteer/revisions.js:
puppeteer-core/lib/cjs/puppeteer/node/PuppeteerNode.js:
  (**
   * @license
   * Copyright 2020 Google Inc.
   * SPDX-License-Identifier: Apache-2.0
   *)

puppeteer-core/lib/cjs/puppeteer/util/encoding.js:
puppeteer-core/lib/cjs/puppeteer/util/Deferred.js:
puppeteer-core/lib/cjs/puppeteer/util/Mutex.js:
puppeteer-core/lib/cjs/puppeteer/common/ScriptInjector.js:
puppeteer-core/lib/cjs/puppeteer/util/incremental-id-generator.js:
puppeteer-core/lib/cjs/puppeteer/cdp/Binding.js:
puppeteer-core/lib/cjs/puppeteer/cdp/CdpPreloadScript.js:
puppeteer-core/lib/cjs/puppeteer/cdp/BrowserContext.js:
puppeteer-core/lib/cjs/puppeteer/cdp/TargetManageEvents.js:
puppeteer-core/lib/cjs/puppeteer/bidi/core/Navigation.js:
puppeteer-core/lib/cjs/puppeteer/bidi/core/Realm.js:
puppeteer-core/lib/cjs/puppeteer/bidi/core/Request.js:
puppeteer-core/lib/cjs/puppeteer/bidi/core/UserPrompt.js:
puppeteer-core/lib/cjs/puppeteer/bidi/core/BrowsingContext.js:
puppeteer-core/lib/cjs/puppeteer/bidi/core/UserContext.js:
puppeteer-core/lib/cjs/puppeteer/bidi/WebWorker.js:
puppeteer-core/lib/cjs/puppeteer/bidi/core/Browser.js:
puppeteer-core/lib/cjs/puppeteer/bidi/core/Session.js:
  (**
   * @license
   * Copyright 2024 Google Inc.
   * SPDX-License-Identifier: Apache-2.0
   *)

puppeteer-core/lib/cjs/puppeteer/util/version.js:
puppeteer-core/lib/cjs/puppeteer/api/DeviceRequestPrompt.js:
puppeteer-core/lib/cjs/puppeteer/bidi/BluetoothEmulation.js:
puppeteer-core/lib/cjs/puppeteer/bidi/DeviceRequestPrompt.js:
  (**
   * @license
   * Copyright 2025 Google Inc.
   * SPDX-License-Identifier: Apache-2.0
   *)

puppeteer-core/lib/cjs/puppeteer/common/Errors.js:
puppeteer-core/lib/cjs/puppeteer/api/WebWorker.js:
puppeteer-core/lib/cjs/puppeteer/cdp/Accessibility.js:
puppeteer-core/lib/cjs/puppeteer/node/NodeWebSocketTransport.js:
  (**
   * @license
   * Copyright 2018 Google Inc.
   * SPDX-License-Identifier: Apache-2.0
   *)

puppeteer-core/lib/cjs/puppeteer/common/util.js:
puppeteer-core/lib/cjs/puppeteer/api/BrowserContext.js:
puppeteer-core/lib/cjs/puppeteer/api/Dialog.js:
puppeteer-core/lib/cjs/puppeteer/api/Input.js:
puppeteer-core/lib/cjs/puppeteer/api/Page.js:
puppeteer-core/lib/cjs/puppeteer/cdp/CdpSession.js:
puppeteer-core/lib/cjs/puppeteer/cdp/Connection.js:
puppeteer-core/lib/cjs/puppeteer/cdp/Coverage.js:
puppeteer-core/lib/cjs/puppeteer/cdp/Dialog.js:
puppeteer-core/lib/cjs/puppeteer/cdp/utils.js:
puppeteer-core/lib/cjs/puppeteer/cdp/ExecutionContext.js:
puppeteer-core/lib/cjs/puppeteer/cdp/Frame.js:
puppeteer-core/lib/cjs/puppeteer/cdp/NetworkManager.js:
puppeteer-core/lib/cjs/puppeteer/cdp/FrameManager.js:
puppeteer-core/lib/cjs/puppeteer/common/USKeyboardLayout.js:
puppeteer-core/lib/cjs/puppeteer/cdp/Input.js:
puppeteer-core/lib/cjs/puppeteer/cdp/Page.js:
puppeteer-core/lib/cjs/puppeteer/cdp/Browser.js:
puppeteer-core/lib/cjs/puppeteer/common/Device.js:
puppeteer-core/lib/cjs/puppeteer/bidi/Connection.js:
puppeteer-core/lib/cjs/puppeteer/bidi/Dialog.js:
puppeteer-core/lib/cjs/puppeteer/bidi/Input.js:
@puppeteer/browsers/lib/cjs/install.js:
puppeteer-core/lib/cjs/puppeteer/common/Puppeteer.js:
puppeteer-core/lib/cjs/puppeteer/index-browser.js:
puppeteer-core/lib/cjs/puppeteer/node/BrowserLauncher.js:
puppeteer-core/lib/cjs/puppeteer/index.js:
puppeteer-core/lib/cjs/puppeteer/puppeteer-core.js:
  (**
   * @license
   * Copyright 2017 Google Inc.
   * SPDX-License-Identifier: Apache-2.0
   *)

puppeteer-core/lib/cjs/puppeteer/common/TimeoutSettings.js:
puppeteer-core/lib/cjs/puppeteer/cdp/JSHandle.js:
puppeteer-core/lib/cjs/puppeteer/cdp/ElementHandle.js:
puppeteer-core/lib/cjs/puppeteer/cdp/IsolatedWorld.js:
puppeteer-core/lib/cjs/puppeteer/cdp/LifecycleWatcher.js:
puppeteer-core/lib/cjs/puppeteer/cdp/Target.js:
  (**
   * @license
   * Copyright 2019 Google Inc.
   * SPDX-License-Identifier: Apache-2.0
   *)

puppeteer-core/lib/cjs/puppeteer/cdp/PredefinedNetworkConditions.js:
  (**
   * @license
   * Copyright 2021 Google Inc.
   * SPDX-License-Identifier: Apache-2.0
   *)

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

@puppeteer/browsers/lib/cjs/DefaultProvider.js:
@puppeteer/browsers/lib/cjs/provider.js:
  (**
   * @license
   * Copyright 2026 Google Inc.
   * SPDX-License-Identifier: Apache-2.0
   *)

yargs-parser/build/lib/string-utils.js:
yargs-parser/build/lib/tokenize-arg-string.js:
yargs-parser/build/lib/yargs-parser-types.js:
yargs-parser/build/lib/yargs-parser.js:
  (**
   * @license
   * Copyright (c) 2016, Contributors
   * SPDX-License-Identifier: ISC
   *)

yargs-parser/build/lib/index.js:
  (**
   * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
   * CJS and ESM environments.
   *
   * @license
   * Copyright (c) 2016, Contributors
   * SPDX-License-Identifier: ISC
   *)

puppeteer-extra/dist/index.cjs.js:
  (*!
   * puppeteer-extra v3.3.5 by berstend
   * https://github.com/berstend/puppeteer-extra
   * @license MIT
   *)

for-in/index.js:
  (*!
   * for-in <https://github.com/jonschlinkert/for-in>
   *
   * Copyright (c) 2014-2017, Jon Schlinkert.
   * Released under the MIT License.
   *)

for-own/index.js:
  (*!
   * for-own <https://github.com/jonschlinkert/for-own>
   *
   * Copyright (c) 2014-2017, Jon Schlinkert.
   * Released under the MIT License.
   *)

is-buffer/index.js:
  (*!
   * Determine if an object is a Buffer
   *
   * @author   Feross Aboukhadijeh <https://feross.org>
   * @license  MIT
   *)

merge-deep/index.js:
  (*!
   * merge-deep <https://github.com/jonschlinkert/merge-deep>
   *
   * Copyright (c) 2014-2015, Jon Schlinkert.
   * Licensed under the MIT License.
   *)

puppeteer-extra-plugin/dist/index.cjs.js:
  (*!
   * puppeteer-extra-plugin v3.2.2 by berstend
   * https://github.com/berstend/puppeteer-extra/tree/master/packages/puppeteer-extra-plugin
   * @license MIT
   *)

mime-db/index.js:
  (*!
   * mime-db
   * Copyright(c) 2014 Jonathan Ong
   * Copyright(c) 2015-2022 Douglas Christopher Wilson
   * MIT Licensed
   *)

mime-types/index.js:
  (*!
   * mime-types
   * Copyright(c) 2014 Jonathan Ong
   * Copyright(c) 2015 Douglas Christopher Wilson
   * MIT Licensed
   *)

axios/dist/node/axios.cjs:
  (*! Axios v1.15.0 Copyright (c) 2026 Matt Zabriskie and contributors *)
*/
