
import { createRequire as __createRequire } from 'node:module';
const require = __createRequire(import.meta.url);

// ----- polyfilling for module build command -----

import pathPolyfill123 from "node:path"
import { fileURLToPath as fileURLToPathPolyfill123 } from "node:url"
const __filename = fileURLToPathPolyfill123(import.meta.url)
const __dirname = pathPolyfill123.dirname(__filename)

// -------------------------------------------------

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 __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, {
  get: (a3, b) => (typeof require !== "undefined" ? require : a3)[b]
}) : x2)(function(x2) {
  if (typeof require !== "undefined")
    return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x2 + '" is not supported');
});
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require2() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, 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
));

// <define:ENV_DEFINED_IN_BUILD_STEP>
var define_ENV_DEFINED_IN_BUILD_STEP_default;
var init_define_ENV_DEFINED_IN_BUILD_STEP = __esm({
  "<define:ENV_DEFINED_IN_BUILD_STEP>"() {
    define_ENV_DEFINED_IN_BUILD_STEP_default = { IS_PRODUCTION: true };
  }
});

// ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/error.js
var require_error = __commonJS({
  "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/error.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var CommanderError2 = class extends Error {
      /**
       * Constructs the CommanderError class
       * @param {number} exitCode suggested exit code which could be used with process.exit
       * @param {string} code an id string representing the error
       * @param {string} message human-readable description of the error
       * @constructor
       */
      constructor(exitCode, code, message) {
        super(message);
        Error.captureStackTrace(this, this.constructor);
        this.name = this.constructor.name;
        this.code = code;
        this.exitCode = exitCode;
        this.nestedError = void 0;
      }
    };
    var InvalidArgumentError2 = class extends CommanderError2 {
      /**
       * Constructs the InvalidArgumentError class
       * @param {string} [message] explanation of why argument is invalid
       * @constructor
       */
      constructor(message) {
        super(1, "commander.invalidArgument", message);
        Error.captureStackTrace(this, this.constructor);
        this.name = this.constructor.name;
      }
    };
    exports.CommanderError = CommanderError2;
    exports.InvalidArgumentError = InvalidArgumentError2;
  }
});

// ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/argument.js
var require_argument = __commonJS({
  "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/argument.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
    var Argument2 = class {
      /**
       * Initialize a new command argument with the given name and description.
       * The default is that the argument is required, and you can explicitly
       * indicate this with <> around the name. Put [] around the name for an optional argument.
       *
       * @param {string} name
       * @param {string} [description]
       */
      constructor(name, description) {
        this.description = description || "";
        this.variadic = false;
        this.parseArg = void 0;
        this.defaultValue = void 0;
        this.defaultValueDescription = void 0;
        this.argChoices = void 0;
        switch (name[0]) {
          case "<":
            this.required = true;
            this._name = name.slice(1, -1);
            break;
          case "[":
            this.required = false;
            this._name = name.slice(1, -1);
            break;
          default:
            this.required = true;
            this._name = name;
            break;
        }
        if (this._name.length > 3 && this._name.slice(-3) === "...") {
          this.variadic = true;
          this._name = this._name.slice(0, -3);
        }
      }
      /**
       * Return argument name.
       *
       * @return {string}
       */
      name() {
        return this._name;
      }
      /**
       * @api private
       */
      _concatValue(value, previous) {
        if (previous === this.defaultValue || !Array.isArray(previous)) {
          return [value];
        }
        return previous.concat(value);
      }
      /**
       * Set the default value, and optionally supply the description to be displayed in the help.
       *
       * @param {*} value
       * @param {string} [description]
       * @return {Argument}
       */
      default(value, description) {
        this.defaultValue = value;
        this.defaultValueDescription = description;
        return this;
      }
      /**
       * Set the custom handler for processing CLI command arguments into argument values.
       *
       * @param {Function} [fn]
       * @return {Argument}
       */
      argParser(fn) {
        this.parseArg = fn;
        return this;
      }
      /**
       * Only allow argument value to be one of choices.
       *
       * @param {string[]} values
       * @return {Argument}
       */
      choices(values) {
        this.argChoices = values.slice();
        this.parseArg = (arg, previous) => {
          if (!this.argChoices.includes(arg)) {
            throw new InvalidArgumentError2(`Allowed choices are ${this.argChoices.join(", ")}.`);
          }
          if (this.variadic) {
            return this._concatValue(arg, previous);
          }
          return arg;
        };
        return this;
      }
      /**
       * Make argument required.
       */
      argRequired() {
        this.required = true;
        return this;
      }
      /**
       * Make argument optional.
       */
      argOptional() {
        this.required = false;
        return this;
      }
    };
    function humanReadableArgName(arg) {
      const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
      return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
    }
    exports.Argument = Argument2;
    exports.humanReadableArgName = humanReadableArgName;
  }
});

// ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/help.js
var require_help = __commonJS({
  "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/help.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var { humanReadableArgName } = require_argument();
    var Help2 = class {
      constructor() {
        this.helpWidth = void 0;
        this.sortSubcommands = false;
        this.sortOptions = false;
        this.showGlobalOptions = false;
      }
      /**
       * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
       *
       * @param {Command} cmd
       * @returns {Command[]}
       */
      visibleCommands(cmd) {
        const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
        if (cmd._hasImplicitHelpCommand()) {
          const [, helpName, helpArgs] = cmd._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/);
          const helpCommand = cmd.createCommand(helpName).helpOption(false);
          helpCommand.description(cmd._helpCommandDescription);
          if (helpArgs)
            helpCommand.arguments(helpArgs);
          visibleCommands.push(helpCommand);
        }
        if (this.sortSubcommands) {
          visibleCommands.sort((a3, b) => {
            return a3.name().localeCompare(b.name());
          });
        }
        return visibleCommands;
      }
      /**
       * Compare options for sort.
       *
       * @param {Option} a
       * @param {Option} b
       * @returns number
       */
      compareOptions(a3, b) {
        const getSortKey = (option) => {
          return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
        };
        return getSortKey(a3).localeCompare(getSortKey(b));
      }
      /**
       * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
       *
       * @param {Command} cmd
       * @returns {Option[]}
       */
      visibleOptions(cmd) {
        const visibleOptions = cmd.options.filter((option) => !option.hidden);
        const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag);
        const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag);
        if (showShortHelpFlag || showLongHelpFlag) {
          let helpOption;
          if (!showShortHelpFlag) {
            helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription);
          } else if (!showLongHelpFlag) {
            helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription);
          } else {
            helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription);
          }
          visibleOptions.push(helpOption);
        }
        if (this.sortOptions) {
          visibleOptions.sort(this.compareOptions);
        }
        return visibleOptions;
      }
      /**
       * Get an array of the visible global options. (Not including help.)
       *
       * @param {Command} cmd
       * @returns {Option[]}
       */
      visibleGlobalOptions(cmd) {
        if (!this.showGlobalOptions)
          return [];
        const globalOptions = [];
        for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
          const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
          globalOptions.push(...visibleOptions);
        }
        if (this.sortOptions) {
          globalOptions.sort(this.compareOptions);
        }
        return globalOptions;
      }
      /**
       * Get an array of the arguments if any have a description.
       *
       * @param {Command} cmd
       * @returns {Argument[]}
       */
      visibleArguments(cmd) {
        if (cmd._argsDescription) {
          cmd.registeredArguments.forEach((argument) => {
            argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
          });
        }
        if (cmd.registeredArguments.find((argument) => argument.description)) {
          return cmd.registeredArguments;
        }
        return [];
      }
      /**
       * Get the command term to show in the list of subcommands.
       *
       * @param {Command} cmd
       * @returns {string}
       */
      subcommandTerm(cmd) {
        const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
        return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
        (args ? " " + args : "");
      }
      /**
       * Get the option term to show in the list of options.
       *
       * @param {Option} option
       * @returns {string}
       */
      optionTerm(option) {
        return option.flags;
      }
      /**
       * Get the argument term to show in the list of arguments.
       *
       * @param {Argument} argument
       * @returns {string}
       */
      argumentTerm(argument) {
        return argument.name();
      }
      /**
       * Get the longest command term length.
       *
       * @param {Command} cmd
       * @param {Help} helper
       * @returns {number}
       */
      longestSubcommandTermLength(cmd, helper) {
        return helper.visibleCommands(cmd).reduce((max, command) => {
          return Math.max(max, helper.subcommandTerm(command).length);
        }, 0);
      }
      /**
       * Get the longest option term length.
       *
       * @param {Command} cmd
       * @param {Help} helper
       * @returns {number}
       */
      longestOptionTermLength(cmd, helper) {
        return helper.visibleOptions(cmd).reduce((max, option) => {
          return Math.max(max, helper.optionTerm(option).length);
        }, 0);
      }
      /**
       * Get the longest global option term length.
       *
       * @param {Command} cmd
       * @param {Help} helper
       * @returns {number}
       */
      longestGlobalOptionTermLength(cmd, helper) {
        return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
          return Math.max(max, helper.optionTerm(option).length);
        }, 0);
      }
      /**
       * Get the longest argument term length.
       *
       * @param {Command} cmd
       * @param {Help} helper
       * @returns {number}
       */
      longestArgumentTermLength(cmd, helper) {
        return helper.visibleArguments(cmd).reduce((max, argument) => {
          return Math.max(max, helper.argumentTerm(argument).length);
        }, 0);
      }
      /**
       * Get the command usage to be displayed at the top of the built-in help.
       *
       * @param {Command} cmd
       * @returns {string}
       */
      commandUsage(cmd) {
        let cmdName = cmd._name;
        if (cmd._aliases[0]) {
          cmdName = cmdName + "|" + cmd._aliases[0];
        }
        let ancestorCmdNames = "";
        for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
          ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
        }
        return ancestorCmdNames + cmdName + " " + cmd.usage();
      }
      /**
       * Get the description for the command.
       *
       * @param {Command} cmd
       * @returns {string}
       */
      commandDescription(cmd) {
        return cmd.description();
      }
      /**
       * Get the subcommand summary to show in the list of subcommands.
       * (Fallback to description for backwards compatibility.)
       *
       * @param {Command} cmd
       * @returns {string}
       */
      subcommandDescription(cmd) {
        return cmd.summary() || cmd.description();
      }
      /**
       * Get the option description to show in the list of options.
       *
       * @param {Option} option
       * @return {string}
       */
      optionDescription(option) {
        const extraInfo = [];
        if (option.argChoices) {
          extraInfo.push(
            // use stringify to match the display of the default value
            `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
          );
        }
        if (option.defaultValue !== void 0) {
          const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
          if (showDefault) {
            extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
          }
        }
        if (option.presetArg !== void 0 && option.optional) {
          extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
        }
        if (option.envVar !== void 0) {
          extraInfo.push(`env: ${option.envVar}`);
        }
        if (extraInfo.length > 0) {
          return `${option.description} (${extraInfo.join(", ")})`;
        }
        return option.description;
      }
      /**
       * Get the argument description to show in the list of arguments.
       *
       * @param {Argument} argument
       * @return {string}
       */
      argumentDescription(argument) {
        const extraInfo = [];
        if (argument.argChoices) {
          extraInfo.push(
            // use stringify to match the display of the default value
            `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
          );
        }
        if (argument.defaultValue !== void 0) {
          extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
        }
        if (extraInfo.length > 0) {
          const extraDescripton = `(${extraInfo.join(", ")})`;
          if (argument.description) {
            return `${argument.description} ${extraDescripton}`;
          }
          return extraDescripton;
        }
        return argument.description;
      }
      /**
       * Generate the built-in help text.
       *
       * @param {Command} cmd
       * @param {Help} helper
       * @returns {string}
       */
      formatHelp(cmd, helper) {
        const termWidth = helper.padWidth(cmd, helper);
        const helpWidth = helper.helpWidth || 80;
        const itemIndentWidth = 2;
        const itemSeparatorWidth = 2;
        function formatItem(term, description) {
          if (description) {
            const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
            return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
          }
          return term;
        }
        function formatList(textArray) {
          return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
        }
        let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
        const commandDescription = helper.commandDescription(cmd);
        if (commandDescription.length > 0) {
          output = output.concat([helper.wrap(commandDescription, helpWidth, 0), ""]);
        }
        const argumentList = helper.visibleArguments(cmd).map((argument) => {
          return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
        });
        if (argumentList.length > 0) {
          output = output.concat(["Arguments:", formatList(argumentList), ""]);
        }
        const optionList = helper.visibleOptions(cmd).map((option) => {
          return formatItem(helper.optionTerm(option), helper.optionDescription(option));
        });
        if (optionList.length > 0) {
          output = output.concat(["Options:", formatList(optionList), ""]);
        }
        if (this.showGlobalOptions) {
          const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
            return formatItem(helper.optionTerm(option), helper.optionDescription(option));
          });
          if (globalOptionList.length > 0) {
            output = output.concat(["Global Options:", formatList(globalOptionList), ""]);
          }
        }
        const commandList = helper.visibleCommands(cmd).map((cmd2) => {
          return formatItem(helper.subcommandTerm(cmd2), helper.subcommandDescription(cmd2));
        });
        if (commandList.length > 0) {
          output = output.concat(["Commands:", formatList(commandList), ""]);
        }
        return output.join("\n");
      }
      /**
       * Calculate the pad width from the maximum term length.
       *
       * @param {Command} cmd
       * @param {Help} helper
       * @returns {number}
       */
      padWidth(cmd, helper) {
        return Math.max(
          helper.longestOptionTermLength(cmd, helper),
          helper.longestGlobalOptionTermLength(cmd, helper),
          helper.longestSubcommandTermLength(cmd, helper),
          helper.longestArgumentTermLength(cmd, helper)
        );
      }
      /**
       * Wrap the given string to width characters per line, with lines after the first indented.
       * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
       *
       * @param {string} str
       * @param {number} width
       * @param {number} indent
       * @param {number} [minColumnWidth=40]
       * @return {string}
       *
       */
      wrap(str, width, indent, minColumnWidth = 40) {
        const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
        const manualIndent = new RegExp(`[\\n][${indents}]+`);
        if (str.match(manualIndent))
          return str;
        const columnWidth = width - indent;
        if (columnWidth < minColumnWidth)
          return str;
        const leadingStr = str.slice(0, indent);
        const columnText = str.slice(indent).replace("\r\n", "\n");
        const indentString = " ".repeat(indent);
        const zeroWidthSpace = "\u200B";
        const breaks = `\\s${zeroWidthSpace}`;
        const regex2 = new RegExp(`
|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, "g");
        const lines = columnText.match(regex2) || [];
        return leadingStr + lines.map((line, i2) => {
          if (line === "\n")
            return "";
          return (i2 > 0 ? indentString : "") + line.trimEnd();
        }).join("\n");
      }
    };
    exports.Help = Help2;
  }
});

// ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/option.js
var require_option = __commonJS({
  "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/option.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
    var Option2 = class {
      /**
       * Initialize a new `Option` with the given `flags` and `description`.
       *
       * @param {string} flags
       * @param {string} [description]
       */
      constructor(flags, description) {
        this.flags = flags;
        this.description = description || "";
        this.required = flags.includes("<");
        this.optional = flags.includes("[");
        this.variadic = /\w\.\.\.[>\]]$/.test(flags);
        this.mandatory = false;
        const optionFlags = splitOptionFlags(flags);
        this.short = optionFlags.shortFlag;
        this.long = optionFlags.longFlag;
        this.negate = false;
        if (this.long) {
          this.negate = this.long.startsWith("--no-");
        }
        this.defaultValue = void 0;
        this.defaultValueDescription = void 0;
        this.presetArg = void 0;
        this.envVar = void 0;
        this.parseArg = void 0;
        this.hidden = false;
        this.argChoices = void 0;
        this.conflictsWith = [];
        this.implied = void 0;
      }
      /**
       * Set the default value, and optionally supply the description to be displayed in the help.
       *
       * @param {*} value
       * @param {string} [description]
       * @return {Option}
       */
      default(value, description) {
        this.defaultValue = value;
        this.defaultValueDescription = description;
        return this;
      }
      /**
       * Preset to use when option used without option-argument, especially optional but also boolean and negated.
       * The custom processing (parseArg) is called.
       *
       * @example
       * new Option('--color').default('GREYSCALE').preset('RGB');
       * new Option('--donate [amount]').preset('20').argParser(parseFloat);
       *
       * @param {*} arg
       * @return {Option}
       */
      preset(arg) {
        this.presetArg = arg;
        return this;
      }
      /**
       * Add option name(s) that conflict with this option.
       * An error will be displayed if conflicting options are found during parsing.
       *
       * @example
       * new Option('--rgb').conflicts('cmyk');
       * new Option('--js').conflicts(['ts', 'jsx']);
       *
       * @param {string | string[]} names
       * @return {Option}
       */
      conflicts(names) {
        this.conflictsWith = this.conflictsWith.concat(names);
        return this;
      }
      /**
       * Specify implied option values for when this option is set and the implied options are not.
       *
       * The custom processing (parseArg) is not called on the implied values.
       *
       * @example
       * program
       *   .addOption(new Option('--log', 'write logging information to file'))
       *   .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
       *
       * @param {Object} impliedOptionValues
       * @return {Option}
       */
      implies(impliedOptionValues) {
        let newImplied = impliedOptionValues;
        if (typeof impliedOptionValues === "string") {
          newImplied = { [impliedOptionValues]: true };
        }
        this.implied = Object.assign(this.implied || {}, newImplied);
        return this;
      }
      /**
       * Set environment variable to check for option value.
       *
       * An environment variable is only used if when processed the current option value is
       * undefined, or the source of the current value is 'default' or 'config' or 'env'.
       *
       * @param {string} name
       * @return {Option}
       */
      env(name) {
        this.envVar = name;
        return this;
      }
      /**
       * Set the custom handler for processing CLI option arguments into option values.
       *
       * @param {Function} [fn]
       * @return {Option}
       */
      argParser(fn) {
        this.parseArg = fn;
        return this;
      }
      /**
       * Whether the option is mandatory and must have a value after parsing.
       *
       * @param {boolean} [mandatory=true]
       * @return {Option}
       */
      makeOptionMandatory(mandatory = true) {
        this.mandatory = !!mandatory;
        return this;
      }
      /**
       * Hide option in help.
       *
       * @param {boolean} [hide=true]
       * @return {Option}
       */
      hideHelp(hide = true) {
        this.hidden = !!hide;
        return this;
      }
      /**
       * @api private
       */
      _concatValue(value, previous) {
        if (previous === this.defaultValue || !Array.isArray(previous)) {
          return [value];
        }
        return previous.concat(value);
      }
      /**
       * Only allow option value to be one of choices.
       *
       * @param {string[]} values
       * @return {Option}
       */
      choices(values) {
        this.argChoices = values.slice();
        this.parseArg = (arg, previous) => {
          if (!this.argChoices.includes(arg)) {
            throw new InvalidArgumentError2(`Allowed choices are ${this.argChoices.join(", ")}.`);
          }
          if (this.variadic) {
            return this._concatValue(arg, previous);
          }
          return arg;
        };
        return this;
      }
      /**
       * Return option name.
       *
       * @return {string}
       */
      name() {
        if (this.long) {
          return this.long.replace(/^--/, "");
        }
        return this.short.replace(/^-/, "");
      }
      /**
       * Return option name, in a camelcase format that can be used
       * as a object attribute key.
       *
       * @return {string}
       * @api private
       */
      attributeName() {
        return camelcase(this.name().replace(/^no-/, ""));
      }
      /**
       * Check if `arg` matches the short or long flag.
       *
       * @param {string} arg
       * @return {boolean}
       * @api private
       */
      is(arg) {
        return this.short === arg || this.long === arg;
      }
      /**
       * Return whether a boolean option.
       *
       * Options are one of boolean, negated, required argument, or optional argument.
       *
       * @return {boolean}
       * @api private
       */
      isBoolean() {
        return !this.required && !this.optional && !this.negate;
      }
    };
    var DualOptions = class {
      /**
       * @param {Option[]} options
       */
      constructor(options) {
        this.positiveOptions = /* @__PURE__ */ new Map();
        this.negativeOptions = /* @__PURE__ */ new Map();
        this.dualOptions = /* @__PURE__ */ new Set();
        options.forEach((option) => {
          if (option.negate) {
            this.negativeOptions.set(option.attributeName(), option);
          } else {
            this.positiveOptions.set(option.attributeName(), option);
          }
        });
        this.negativeOptions.forEach((value, key) => {
          if (this.positiveOptions.has(key)) {
            this.dualOptions.add(key);
          }
        });
      }
      /**
       * Did the value come from the option, and not from possible matching dual option?
       *
       * @param {*} value
       * @param {Option} option
       * @returns {boolean}
       */
      valueFromOption(value, option) {
        const optionKey = option.attributeName();
        if (!this.dualOptions.has(optionKey))
          return true;
        const preset = this.negativeOptions.get(optionKey).presetArg;
        const negativeValue = preset !== void 0 ? preset : false;
        return option.negate === (negativeValue === value);
      }
    };
    function camelcase(str) {
      return str.split("-").reduce((str2, word) => {
        return str2 + word[0].toUpperCase() + word.slice(1);
      });
    }
    function splitOptionFlags(flags) {
      let shortFlag;
      let longFlag;
      const flagParts = flags.split(/[ |,]+/);
      if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
        shortFlag = flagParts.shift();
      longFlag = flagParts.shift();
      if (!shortFlag && /^-[^-]$/.test(longFlag)) {
        shortFlag = longFlag;
        longFlag = void 0;
      }
      return { shortFlag, longFlag };
    }
    exports.Option = Option2;
    exports.splitOptionFlags = splitOptionFlags;
    exports.DualOptions = DualOptions;
  }
});

// ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/suggestSimilar.js
var require_suggestSimilar = __commonJS({
  "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/suggestSimilar.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var maxDistance = 3;
    function editDistance(a3, b) {
      if (Math.abs(a3.length - b.length) > maxDistance)
        return Math.max(a3.length, b.length);
      const d2 = [];
      for (let i2 = 0; i2 <= a3.length; i2++) {
        d2[i2] = [i2];
      }
      for (let j2 = 0; j2 <= b.length; j2++) {
        d2[0][j2] = j2;
      }
      for (let j2 = 1; j2 <= b.length; j2++) {
        for (let i2 = 1; i2 <= a3.length; i2++) {
          let cost = 1;
          if (a3[i2 - 1] === b[j2 - 1]) {
            cost = 0;
          } else {
            cost = 1;
          }
          d2[i2][j2] = Math.min(
            d2[i2 - 1][j2] + 1,
            // deletion
            d2[i2][j2 - 1] + 1,
            // insertion
            d2[i2 - 1][j2 - 1] + cost
            // substitution
          );
          if (i2 > 1 && j2 > 1 && a3[i2 - 1] === b[j2 - 2] && a3[i2 - 2] === b[j2 - 1]) {
            d2[i2][j2] = Math.min(d2[i2][j2], d2[i2 - 2][j2 - 2] + 1);
          }
        }
      }
      return d2[a3.length][b.length];
    }
    function suggestSimilar(word, candidates) {
      if (!candidates || candidates.length === 0)
        return "";
      candidates = Array.from(new Set(candidates));
      const searchingOptions = word.startsWith("--");
      if (searchingOptions) {
        word = word.slice(2);
        candidates = candidates.map((candidate) => candidate.slice(2));
      }
      let similar = [];
      let bestDistance = maxDistance;
      const minSimilarity = 0.4;
      candidates.forEach((candidate) => {
        if (candidate.length <= 1)
          return;
        const distance = editDistance(word, candidate);
        const length = Math.max(word.length, candidate.length);
        const similarity = (length - distance) / length;
        if (similarity > minSimilarity) {
          if (distance < bestDistance) {
            bestDistance = distance;
            similar = [candidate];
          } else if (distance === bestDistance) {
            similar.push(candidate);
          }
        }
      });
      similar.sort((a3, b) => a3.localeCompare(b));
      if (searchingOptions) {
        similar = similar.map((candidate) => `--${candidate}`);
      }
      if (similar.length > 1) {
        return `
(Did you mean one of ${similar.join(", ")}?)`;
      }
      if (similar.length === 1) {
        return `
(Did you mean ${similar[0]}?)`;
      }
      return "";
    }
    exports.suggestSimilar = suggestSimilar;
  }
});

// ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/command.js
var require_command = __commonJS({
  "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/command.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var EventEmitter = __require("events").EventEmitter;
    var childProcess = __require("child_process");
    var path2 = __require("path");
    var fs3 = __require("fs");
    var process2 = __require("process");
    var { Argument: Argument2, humanReadableArgName } = require_argument();
    var { CommanderError: CommanderError2 } = require_error();
    var { Help: Help2 } = require_help();
    var { Option: Option2, splitOptionFlags, DualOptions } = require_option();
    var { suggestSimilar } = require_suggestSimilar();
    var Command3 = class _Command extends EventEmitter {
      /**
       * Initialize a new `Command`.
       *
       * @param {string} [name]
       */
      constructor(name) {
        super();
        this.commands = [];
        this.options = [];
        this.parent = null;
        this._allowUnknownOption = false;
        this._allowExcessArguments = true;
        this.registeredArguments = [];
        this._args = this.registeredArguments;
        this.args = [];
        this.rawArgs = [];
        this.processedArgs = [];
        this._scriptPath = null;
        this._name = name || "";
        this._optionValues = {};
        this._optionValueSources = {};
        this._storeOptionsAsProperties = false;
        this._actionHandler = null;
        this._executableHandler = false;
        this._executableFile = null;
        this._executableDir = null;
        this._defaultCommandName = null;
        this._exitCallback = null;
        this._aliases = [];
        this._combineFlagAndOptionalValue = true;
        this._description = "";
        this._summary = "";
        this._argsDescription = void 0;
        this._enablePositionalOptions = false;
        this._passThroughOptions = false;
        this._lifeCycleHooks = {};
        this._showHelpAfterError = false;
        this._showSuggestionAfterError = true;
        this._outputConfiguration = {
          writeOut: (str) => process2.stdout.write(str),
          writeErr: (str) => process2.stderr.write(str),
          getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
          getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
          outputError: (str, write) => write(str)
        };
        this._hidden = false;
        this._hasHelpOption = true;
        this._helpFlags = "-h, --help";
        this._helpDescription = "display help for command";
        this._helpShortFlag = "-h";
        this._helpLongFlag = "--help";
        this._addImplicitHelpCommand = void 0;
        this._helpCommandName = "help";
        this._helpCommandnameAndArgs = "help [command]";
        this._helpCommandDescription = "display help for command";
        this._helpConfiguration = {};
      }
      /**
       * Copy settings that are useful to have in common across root command and subcommands.
       *
       * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
       *
       * @param {Command} sourceCommand
       * @return {Command} `this` command for chaining
       */
      copyInheritedSettings(sourceCommand) {
        this._outputConfiguration = sourceCommand._outputConfiguration;
        this._hasHelpOption = sourceCommand._hasHelpOption;
        this._helpFlags = sourceCommand._helpFlags;
        this._helpDescription = sourceCommand._helpDescription;
        this._helpShortFlag = sourceCommand._helpShortFlag;
        this._helpLongFlag = sourceCommand._helpLongFlag;
        this._helpCommandName = sourceCommand._helpCommandName;
        this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs;
        this._helpCommandDescription = sourceCommand._helpCommandDescription;
        this._helpConfiguration = sourceCommand._helpConfiguration;
        this._exitCallback = sourceCommand._exitCallback;
        this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
        this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
        this._allowExcessArguments = sourceCommand._allowExcessArguments;
        this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
        this._showHelpAfterError = sourceCommand._showHelpAfterError;
        this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
        return this;
      }
      /**
       * @returns {Command[]}
       * @api private
       */
      _getCommandAndAncestors() {
        const result = [];
        for (let command = this; command; command = command.parent) {
          result.push(command);
        }
        return result;
      }
      /**
       * Define a command.
       *
       * There are two styles of command: pay attention to where to put the description.
       *
       * @example
       * // Command implemented using action handler (description is supplied separately to `.command`)
       * program
       *   .command('clone <source> [destination]')
       *   .description('clone a repository into a newly created directory')
       *   .action((source, destination) => {
       *     console.log('clone command called');
       *   });
       *
       * // Command implemented using separate executable file (description is second parameter to `.command`)
       * program
       *   .command('start <service>', 'start named service')
       *   .command('stop [service]', 'stop named service, or all if no name supplied');
       *
       * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
       * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
       * @param {Object} [execOpts] - configuration options (for executable)
       * @return {Command} returns new command for action handler, or `this` for executable command
       */
      command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
        let desc = actionOptsOrExecDesc;
        let opts = execOpts;
        if (typeof desc === "object" && desc !== null) {
          opts = desc;
          desc = null;
        }
        opts = opts || {};
        const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
        const cmd = this.createCommand(name);
        if (desc) {
          cmd.description(desc);
          cmd._executableHandler = true;
        }
        if (opts.isDefault)
          this._defaultCommandName = cmd._name;
        cmd._hidden = !!(opts.noHelp || opts.hidden);
        cmd._executableFile = opts.executableFile || null;
        if (args)
          cmd.arguments(args);
        this.commands.push(cmd);
        cmd.parent = this;
        cmd.copyInheritedSettings(this);
        if (desc)
          return this;
        return cmd;
      }
      /**
       * Factory routine to create a new unattached command.
       *
       * See .command() for creating an attached subcommand, which uses this routine to
       * create the command. You can override createCommand to customise subcommands.
       *
       * @param {string} [name]
       * @return {Command} new command
       */
      createCommand(name) {
        return new _Command(name);
      }
      /**
       * You can customise the help with a subclass of Help by overriding createHelp,
       * or by overriding Help properties using configureHelp().
       *
       * @return {Help}
       */
      createHelp() {
        return Object.assign(new Help2(), this.configureHelp());
      }
      /**
       * You can customise the help by overriding Help properties using configureHelp(),
       * or with a subclass of Help by overriding createHelp().
       *
       * @param {Object} [configuration] - configuration options
       * @return {Command|Object} `this` command for chaining, or stored configuration
       */
      configureHelp(configuration) {
        if (configuration === void 0)
          return this._helpConfiguration;
        this._helpConfiguration = configuration;
        return this;
      }
      /**
       * The default output goes to stdout and stderr. You can customise this for special
       * applications. You can also customise the display of errors by overriding outputError.
       *
       * The configuration properties are all functions:
       *
       *     // functions to change where being written, stdout and stderr
       *     writeOut(str)
       *     writeErr(str)
       *     // matching functions to specify width for wrapping help
       *     getOutHelpWidth()
       *     getErrHelpWidth()
       *     // functions based on what is being written out
       *     outputError(str, write) // used for displaying errors, and not used for displaying help
       *
       * @param {Object} [configuration] - configuration options
       * @return {Command|Object} `this` command for chaining, or stored configuration
       */
      configureOutput(configuration) {
        if (configuration === void 0)
          return this._outputConfiguration;
        Object.assign(this._outputConfiguration, configuration);
        return this;
      }
      /**
       * Display the help or a custom message after an error occurs.
       *
       * @param {boolean|string} [displayHelp]
       * @return {Command} `this` command for chaining
       */
      showHelpAfterError(displayHelp = true) {
        if (typeof displayHelp !== "string")
          displayHelp = !!displayHelp;
        this._showHelpAfterError = displayHelp;
        return this;
      }
      /**
       * Display suggestion of similar commands for unknown commands, or options for unknown options.
       *
       * @param {boolean} [displaySuggestion]
       * @return {Command} `this` command for chaining
       */
      showSuggestionAfterError(displaySuggestion = true) {
        this._showSuggestionAfterError = !!displaySuggestion;
        return this;
      }
      /**
       * Add a prepared subcommand.
       *
       * See .command() for creating an attached subcommand which inherits settings from its parent.
       *
       * @param {Command} cmd - new subcommand
       * @param {Object} [opts] - configuration options
       * @return {Command} `this` command for chaining
       */
      addCommand(cmd, opts) {
        if (!cmd._name) {
          throw new Error(`Command passed to .addCommand() must have a name
- specify the name in Command constructor or using .name()`);
        }
        opts = opts || {};
        if (opts.isDefault)
          this._defaultCommandName = cmd._name;
        if (opts.noHelp || opts.hidden)
          cmd._hidden = true;
        this.commands.push(cmd);
        cmd.parent = this;
        return this;
      }
      /**
       * Factory routine to create a new unattached argument.
       *
       * See .argument() for creating an attached argument, which uses this routine to
       * create the argument. You can override createArgument to return a custom argument.
       *
       * @param {string} name
       * @param {string} [description]
       * @return {Argument} new argument
       */
      createArgument(name, description) {
        return new Argument2(name, description);
      }
      /**
       * Define argument syntax for command.
       *
       * The default is that the argument is required, and you can explicitly
       * indicate this with <> around the name. Put [] around the name for an optional argument.
       *
       * @example
       * program.argument('<input-file>');
       * program.argument('[output-file]');
       *
       * @param {string} name
       * @param {string} [description]
       * @param {Function|*} [fn] - custom argument processing function
       * @param {*} [defaultValue]
       * @return {Command} `this` command for chaining
       */
      argument(name, description, fn, defaultValue) {
        const argument = this.createArgument(name, description);
        if (typeof fn === "function") {
          argument.default(defaultValue).argParser(fn);
        } else {
          argument.default(fn);
        }
        this.addArgument(argument);
        return this;
      }
      /**
       * Define argument syntax for command, adding multiple at once (without descriptions).
       *
       * See also .argument().
       *
       * @example
       * program.arguments('<cmd> [env]');
       *
       * @param {string} names
       * @return {Command} `this` command for chaining
       */
      arguments(names) {
        names.trim().split(/ +/).forEach((detail) => {
          this.argument(detail);
        });
        return this;
      }
      /**
       * Define argument syntax for command, adding a prepared argument.
       *
       * @param {Argument} argument
       * @return {Command} `this` command for chaining
       */
      addArgument(argument) {
        const previousArgument = this.registeredArguments.slice(-1)[0];
        if (previousArgument && previousArgument.variadic) {
          throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
        }
        if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
          throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
        }
        this.registeredArguments.push(argument);
        return this;
      }
      /**
       * Override default decision whether to add implicit help command.
       *
       *    addHelpCommand() // force on
       *    addHelpCommand(false); // force off
       *    addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
       *
       * @return {Command} `this` command for chaining
       */
      addHelpCommand(enableOrNameAndArgs, description) {
        if (enableOrNameAndArgs === false) {
          this._addImplicitHelpCommand = false;
        } else {
          this._addImplicitHelpCommand = true;
          if (typeof enableOrNameAndArgs === "string") {
            this._helpCommandName = enableOrNameAndArgs.split(" ")[0];
            this._helpCommandnameAndArgs = enableOrNameAndArgs;
          }
          this._helpCommandDescription = description || this._helpCommandDescription;
        }
        return this;
      }
      /**
       * @return {boolean}
       * @api private
       */
      _hasImplicitHelpCommand() {
        if (this._addImplicitHelpCommand === void 0) {
          return this.commands.length && !this._actionHandler && !this._findCommand("help");
        }
        return this._addImplicitHelpCommand;
      }
      /**
       * Add hook for life cycle event.
       *
       * @param {string} event
       * @param {Function} listener
       * @return {Command} `this` command for chaining
       */
      hook(event, listener) {
        const allowedValues = ["preSubcommand", "preAction", "postAction"];
        if (!allowedValues.includes(event)) {
          throw new Error(`Unexpected value for event passed to hook : '${event}'.
Expecting one of '${allowedValues.join("', '")}'`);
        }
        if (this._lifeCycleHooks[event]) {
          this._lifeCycleHooks[event].push(listener);
        } else {
          this._lifeCycleHooks[event] = [listener];
        }
        return this;
      }
      /**
       * Register callback to use as replacement for calling process.exit.
       *
       * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
       * @return {Command} `this` command for chaining
       */
      exitOverride(fn) {
        if (fn) {
          this._exitCallback = fn;
        } else {
          this._exitCallback = (err) => {
            if (err.code !== "commander.executeSubCommandAsync") {
              throw err;
            } else {
            }
          };
        }
        return this;
      }
      /**
       * Call process.exit, and _exitCallback if defined.
       *
       * @param {number} exitCode exit code for using with process.exit
       * @param {string} code an id string representing the error
       * @param {string} message human-readable description of the error
       * @return never
       * @api private
       */
      _exit(exitCode, code, message) {
        if (this._exitCallback) {
          this._exitCallback(new CommanderError2(exitCode, code, message));
        }
        process2.exit(exitCode);
      }
      /**
       * Register callback `fn` for the command.
       *
       * @example
       * program
       *   .command('serve')
       *   .description('start service')
       *   .action(function() {
       *      // do work here
       *   });
       *
       * @param {Function} fn
       * @return {Command} `this` command for chaining
       */
      action(fn) {
        const listener = (args) => {
          const expectedArgsCount = this.registeredArguments.length;
          const actionArgs = args.slice(0, expectedArgsCount);
          if (this._storeOptionsAsProperties) {
            actionArgs[expectedArgsCount] = this;
          } else {
            actionArgs[expectedArgsCount] = this.opts();
          }
          actionArgs.push(this);
          return fn.apply(this, actionArgs);
        };
        this._actionHandler = listener;
        return this;
      }
      /**
       * Factory routine to create a new unattached option.
       *
       * See .option() for creating an attached option, which uses this routine to
       * create the option. You can override createOption to return a custom option.
       *
       * @param {string} flags
       * @param {string} [description]
       * @return {Option} new option
       */
      createOption(flags, description) {
        return new Option2(flags, description);
      }
      /**
       * Wrap parseArgs to catch 'commander.invalidArgument'.
       *
       * @param {Option | Argument} target
       * @param {string} value
       * @param {*} previous
       * @param {string} invalidArgumentMessage
       * @api private
       */
      _callParseArg(target, value, previous, invalidArgumentMessage) {
        try {
          return target.parseArg(value, previous);
        } catch (err) {
          if (err.code === "commander.invalidArgument") {
            const message = `${invalidArgumentMessage} ${err.message}`;
            this.error(message, { exitCode: err.exitCode, code: err.code });
          }
          throw err;
        }
      }
      /**
       * Add an option.
       *
       * @param {Option} option
       * @return {Command} `this` command for chaining
       */
      addOption(option) {
        const oname = option.name();
        const name = option.attributeName();
        if (option.negate) {
          const positiveLongFlag = option.long.replace(/^--no-/, "--");
          if (!this._findOption(positiveLongFlag)) {
            this.setOptionValueWithSource(name, option.defaultValue === void 0 ? true : option.defaultValue, "default");
          }
        } else if (option.defaultValue !== void 0) {
          this.setOptionValueWithSource(name, option.defaultValue, "default");
        }
        this.options.push(option);
        const handleOptionValue = (val, invalidValueMessage, valueSource) => {
          if (val == null && option.presetArg !== void 0) {
            val = option.presetArg;
          }
          const oldValue = this.getOptionValue(name);
          if (val !== null && option.parseArg) {
            val = this._callParseArg(option, val, oldValue, invalidValueMessage);
          } else if (val !== null && option.variadic) {
            val = option._concatValue(val, oldValue);
          }
          if (val == null) {
            if (option.negate) {
              val = false;
            } else if (option.isBoolean() || option.optional) {
              val = true;
            } else {
              val = "";
            }
          }
          this.setOptionValueWithSource(name, val, valueSource);
        };
        this.on("option:" + oname, (val) => {
          const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
          handleOptionValue(val, invalidValueMessage, "cli");
        });
        if (option.envVar) {
          this.on("optionEnv:" + oname, (val) => {
            const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
            handleOptionValue(val, invalidValueMessage, "env");
          });
        }
        return this;
      }
      /**
       * Internal implementation shared by .option() and .requiredOption()
       *
       * @api private
       */
      _optionEx(config, flags, description, fn, defaultValue) {
        if (typeof flags === "object" && flags instanceof Option2) {
          throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
        }
        const option = this.createOption(flags, description);
        option.makeOptionMandatory(!!config.mandatory);
        if (typeof fn === "function") {
          option.default(defaultValue).argParser(fn);
        } else if (fn instanceof RegExp) {
          const regex2 = fn;
          fn = (val, def) => {
            const m2 = regex2.exec(val);
            return m2 ? m2[0] : def;
          };
          option.default(defaultValue).argParser(fn);
        } else {
          option.default(fn);
        }
        return this.addOption(option);
      }
      /**
       * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
       *
       * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
       * option-argument is indicated by `<>` and an optional option-argument by `[]`.
       *
       * See the README for more details, and see also addOption() and requiredOption().
       *
       * @example
       * program
       *     .option('-p, --pepper', 'add pepper')
       *     .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
       *     .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
       *     .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
       *
       * @param {string} flags
       * @param {string} [description]
       * @param {Function|*} [parseArg] - custom option processing function or default value
       * @param {*} [defaultValue]
       * @return {Command} `this` command for chaining
       */
      option(flags, description, parseArg, defaultValue) {
        return this._optionEx({}, flags, description, parseArg, defaultValue);
      }
      /**
      * Add a required option which must have a value after parsing. This usually means
      * the option must be specified on the command line. (Otherwise the same as .option().)
      *
      * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
      *
      * @param {string} flags
      * @param {string} [description]
      * @param {Function|*} [parseArg] - custom option processing function or default value
      * @param {*} [defaultValue]
      * @return {Command} `this` command for chaining
      */
      requiredOption(flags, description, parseArg, defaultValue) {
        return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
      }
      /**
       * Alter parsing of short flags with optional values.
       *
       * @example
       * // for `.option('-f,--flag [value]'):
       * program.combineFlagAndOptionalValue(true);  // `-f80` is treated like `--flag=80`, this is the default behaviour
       * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
       *
       * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.
       */
      combineFlagAndOptionalValue(combine = true) {
        this._combineFlagAndOptionalValue = !!combine;
        return this;
      }
      /**
       * Allow unknown options on the command line.
       *
       * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown
       * for unknown options.
       */
      allowUnknownOption(allowUnknown = true) {
        this._allowUnknownOption = !!allowUnknown;
        return this;
      }
      /**
       * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
       *
       * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown
       * for excess arguments.
       */
      allowExcessArguments(allowExcess = true) {
        this._allowExcessArguments = !!allowExcess;
        return this;
      }
      /**
       * Enable positional options. Positional means global options are specified before subcommands which lets
       * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
       * The default behaviour is non-positional and global options may appear anywhere on the command line.
       *
       * @param {Boolean} [positional=true]
       */
      enablePositionalOptions(positional = true) {
        this._enablePositionalOptions = !!positional;
        return this;
      }
      /**
       * Pass through options that come after command-arguments rather than treat them as command-options,
       * so actual command-options come before command-arguments. Turning this on for a subcommand requires
       * positional options to have been enabled on the program (parent commands).
       * The default behaviour is non-positional and options may appear before or after command-arguments.
       *
       * @param {Boolean} [passThrough=true]
       * for unknown options.
       */
      passThroughOptions(passThrough = true) {
        this._passThroughOptions = !!passThrough;
        if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {
          throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)");
        }
        return this;
      }
      /**
        * Whether to store option values as properties on command object,
        * or store separately (specify false). In both cases the option values can be accessed using .opts().
        *
        * @param {boolean} [storeAsProperties=true]
        * @return {Command} `this` command for chaining
        */
      storeOptionsAsProperties(storeAsProperties = true) {
        if (this.options.length) {
          throw new Error("call .storeOptionsAsProperties() before adding options");
        }
        this._storeOptionsAsProperties = !!storeAsProperties;
        return this;
      }
      /**
       * Retrieve option value.
       *
       * @param {string} key
       * @return {Object} value
       */
      getOptionValue(key) {
        if (this._storeOptionsAsProperties) {
          return this[key];
        }
        return this._optionValues[key];
      }
      /**
       * Store option value.
       *
       * @param {string} key
       * @param {Object} value
       * @return {Command} `this` command for chaining
       */
      setOptionValue(key, value) {
        return this.setOptionValueWithSource(key, value, void 0);
      }
      /**
        * Store option value and where the value came from.
        *
        * @param {string} key
        * @param {Object} value
        * @param {string} source - expected values are default/config/env/cli/implied
        * @return {Command} `this` command for chaining
        */
      setOptionValueWithSource(key, value, source) {
        if (this._storeOptionsAsProperties) {
          this[key] = value;
        } else {
          this._optionValues[key] = value;
        }
        this._optionValueSources[key] = source;
        return this;
      }
      /**
        * Get source of option value.
        * Expected values are default | config | env | cli | implied
        *
        * @param {string} key
        * @return {string}
        */
      getOptionValueSource(key) {
        return this._optionValueSources[key];
      }
      /**
        * Get source of option value. See also .optsWithGlobals().
        * Expected values are default | config | env | cli | implied
        *
        * @param {string} key
        * @return {string}
        */
      getOptionValueSourceWithGlobals(key) {
        let source;
        this._getCommandAndAncestors().forEach((cmd) => {
          if (cmd.getOptionValueSource(key) !== void 0) {
            source = cmd.getOptionValueSource(key);
          }
        });
        return source;
      }
      /**
       * Get user arguments from implied or explicit arguments.
       * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
       *
       * @api private
       */
      _prepareUserArgs(argv2, parseOptions) {
        if (argv2 !== void 0 && !Array.isArray(argv2)) {
          throw new Error("first parameter to parse must be array or undefined");
        }
        parseOptions = parseOptions || {};
        if (argv2 === void 0) {
          argv2 = process2.argv;
          if (process2.versions && process2.versions.electron) {
            parseOptions.from = "electron";
          }
        }
        this.rawArgs = argv2.slice();
        let userArgs;
        switch (parseOptions.from) {
          case void 0:
          case "node":
            this._scriptPath = argv2[1];
            userArgs = argv2.slice(2);
            break;
          case "electron":
            if (process2.defaultApp) {
              this._scriptPath = argv2[1];
              userArgs = argv2.slice(2);
            } else {
              userArgs = argv2.slice(1);
            }
            break;
          case "user":
            userArgs = argv2.slice(0);
            break;
          default:
            throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
        }
        if (!this._name && this._scriptPath)
          this.nameFromFilename(this._scriptPath);
        this._name = this._name || "program";
        return userArgs;
      }
      /**
       * Parse `argv`, setting options and invoking commands when defined.
       *
       * The default expectation is that the arguments are from node and have the application as argv[0]
       * and the script being run in argv[1], with user parameters after that.
       *
       * @example
       * program.parse(process.argv);
       * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
       * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
       *
       * @param {string[]} [argv] - optional, defaults to process.argv
       * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
       * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
       * @return {Command} `this` command for chaining
       */
      parse(argv2, parseOptions) {
        const userArgs = this._prepareUserArgs(argv2, parseOptions);
        this._parseCommand([], userArgs);
        return this;
      }
      /**
       * Parse `argv`, setting options and invoking commands when defined.
       *
       * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
       *
       * The default expectation is that the arguments are from node and have the application as argv[0]
       * and the script being run in argv[1], with user parameters after that.
       *
       * @example
       * await program.parseAsync(process.argv);
       * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
       * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
       *
       * @param {string[]} [argv]
       * @param {Object} [parseOptions]
       * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
       * @return {Promise}
       */
      async parseAsync(argv2, parseOptions) {
        const userArgs = this._prepareUserArgs(argv2, parseOptions);
        await this._parseCommand([], userArgs);
        return this;
      }
      /**
       * Execute a sub-command executable.
       *
       * @api private
       */
      _executeSubCommand(subcommand, args) {
        args = args.slice();
        let launchWithNode = false;
        const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
        function findFile(baseDir, baseName) {
          const localBin = path2.resolve(baseDir, baseName);
          if (fs3.existsSync(localBin))
            return localBin;
          if (sourceExt.includes(path2.extname(baseName)))
            return void 0;
          const foundExt = sourceExt.find((ext) => fs3.existsSync(`${localBin}${ext}`));
          if (foundExt)
            return `${localBin}${foundExt}`;
          return void 0;
        }
        this._checkForMissingMandatoryOptions();
        this._checkForConflictingOptions();
        let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
        let executableDir = this._executableDir || "";
        if (this._scriptPath) {
          let resolvedScriptPath;
          try {
            resolvedScriptPath = fs3.realpathSync(this._scriptPath);
          } catch (err) {
            resolvedScriptPath = this._scriptPath;
          }
          executableDir = path2.resolve(path2.dirname(resolvedScriptPath), executableDir);
        }
        if (executableDir) {
          let localFile = findFile(executableDir, executableFile);
          if (!localFile && !subcommand._executableFile && this._scriptPath) {
            const legacyName = path2.basename(this._scriptPath, path2.extname(this._scriptPath));
            if (legacyName !== this._name) {
              localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
            }
          }
          executableFile = localFile || executableFile;
        }
        launchWithNode = sourceExt.includes(path2.extname(executableFile));
        let proc;
        if (process2.platform !== "win32") {
          if (launchWithNode) {
            args.unshift(executableFile);
            args = incrementNodeInspectorPort(process2.execArgv).concat(args);
            proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
          } else {
            proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
          }
        } else {
          args.unshift(executableFile);
          args = incrementNodeInspectorPort(process2.execArgv).concat(args);
          proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
        }
        if (!proc.killed) {
          const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
          signals.forEach((signal) => {
            process2.on(signal, () => {
              if (proc.killed === false && proc.exitCode === null) {
                proc.kill(signal);
              }
            });
          });
        }
        const exitCallback = this._exitCallback;
        if (!exitCallback) {
          proc.on("close", process2.exit.bind(process2));
        } else {
          proc.on("close", () => {
            exitCallback(new CommanderError2(process2.exitCode || 0, "commander.executeSubCommandAsync", "(close)"));
          });
        }
        proc.on("error", (err) => {
          if (err.code === "ENOENT") {
            const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
            const executableMissing = `'${executableFile}' does not exist
 - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
 - ${executableDirMessage}`;
            throw new Error(executableMissing);
          } else if (err.code === "EACCES") {
            throw new Error(`'${executableFile}' not executable`);
          }
          if (!exitCallback) {
            process2.exit(1);
          } else {
            const wrappedError = new CommanderError2(1, "commander.executeSubCommandAsync", "(error)");
            wrappedError.nestedError = err;
            exitCallback(wrappedError);
          }
        });
        this.runningCommand = proc;
      }
      /**
       * @api private
       */
      _dispatchSubcommand(commandName, operands, unknown) {
        const subCommand = this._findCommand(commandName);
        if (!subCommand)
          this.help({ error: true });
        let promiseChain;
        promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
        promiseChain = this._chainOrCall(promiseChain, () => {
          if (subCommand._executableHandler) {
            this._executeSubCommand(subCommand, operands.concat(unknown));
          } else {
            return subCommand._parseCommand(operands, unknown);
          }
        });
        return promiseChain;
      }
      /**
       * Invoke help directly if possible, or dispatch if necessary.
       * e.g. help foo
       *
       * @api private
       */
      _dispatchHelpCommand(subcommandName) {
        if (!subcommandName) {
          this.help();
        }
        const subCommand = this._findCommand(subcommandName);
        if (subCommand && !subCommand._executableHandler) {
          subCommand.help();
        }
        return this._dispatchSubcommand(subcommandName, [], [
          this._helpLongFlag || this._helpShortFlag
        ]);
      }
      /**
       * Check this.args against expected this.registeredArguments.
       *
       * @api private
       */
      _checkNumberOfArguments() {
        this.registeredArguments.forEach((arg, i2) => {
          if (arg.required && this.args[i2] == null) {
            this.missingArgument(arg.name());
          }
        });
        if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
          return;
        }
        if (this.args.length > this.registeredArguments.length) {
          this._excessArguments(this.args);
        }
      }
      /**
       * Process this.args using this.registeredArguments and save as this.processedArgs!
       *
       * @api private
       */
      _processArguments() {
        const myParseArg = (argument, value, previous) => {
          let parsedValue = value;
          if (value !== null && argument.parseArg) {
            const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
            parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
          }
          return parsedValue;
        };
        this._checkNumberOfArguments();
        const processedArgs = [];
        this.registeredArguments.forEach((declaredArg, index) => {
          let value = declaredArg.defaultValue;
          if (declaredArg.variadic) {
            if (index < this.args.length) {
              value = this.args.slice(index);
              if (declaredArg.parseArg) {
                value = value.reduce((processed, v3) => {
                  return myParseArg(declaredArg, v3, processed);
                }, declaredArg.defaultValue);
              }
            } else if (value === void 0) {
              value = [];
            }
          } else if (index < this.args.length) {
            value = this.args[index];
            if (declaredArg.parseArg) {
              value = myParseArg(declaredArg, value, declaredArg.defaultValue);
            }
          }
          processedArgs[index] = value;
        });
        this.processedArgs = processedArgs;
      }
      /**
       * Once we have a promise we chain, but call synchronously until then.
       *
       * @param {Promise|undefined} promise
       * @param {Function} fn
       * @return {Promise|undefined}
       * @api private
       */
      _chainOrCall(promise, fn) {
        if (promise && promise.then && typeof promise.then === "function") {
          return promise.then(() => fn());
        }
        return fn();
      }
      /**
       *
       * @param {Promise|undefined} promise
       * @param {string} event
       * @return {Promise|undefined}
       * @api private
       */
      _chainOrCallHooks(promise, event) {
        let result = promise;
        const hooks = [];
        this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
          hookedCommand._lifeCycleHooks[event].forEach((callback) => {
            hooks.push({ hookedCommand, callback });
          });
        });
        if (event === "postAction") {
          hooks.reverse();
        }
        hooks.forEach((hookDetail) => {
          result = this._chainOrCall(result, () => {
            return hookDetail.callback(hookDetail.hookedCommand, this);
          });
        });
        return result;
      }
      /**
       *
       * @param {Promise|undefined} promise
       * @param {Command} subCommand
       * @param {string} event
       * @return {Promise|undefined}
       * @api private
       */
      _chainOrCallSubCommandHook(promise, subCommand, event) {
        let result = promise;
        if (this._lifeCycleHooks[event] !== void 0) {
          this._lifeCycleHooks[event].forEach((hook) => {
            result = this._chainOrCall(result, () => {
              return hook(this, subCommand);
            });
          });
        }
        return result;
      }
      /**
       * Process arguments in context of this command.
       * Returns action result, in case it is a promise.
       *
       * @api private
       */
      _parseCommand(operands, unknown) {
        const parsed = this.parseOptions(unknown);
        this._parseOptionsEnv();
        this._parseOptionsImplied();
        operands = operands.concat(parsed.operands);
        unknown = parsed.unknown;
        this.args = operands.concat(unknown);
        if (operands && this._findCommand(operands[0])) {
          return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
        }
        if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {
          return this._dispatchHelpCommand(operands[1]);
        }
        if (this._defaultCommandName) {
          outputHelpIfRequested(this, unknown);
          return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
        }
        if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
          this.help({ error: true });
        }
        outputHelpIfRequested(this, parsed.unknown);
        this._checkForMissingMandatoryOptions();
        this._checkForConflictingOptions();
        const checkForUnknownOptions = () => {
          if (parsed.unknown.length > 0) {
            this.unknownOption(parsed.unknown[0]);
          }
        };
        const commandEvent = `command:${this.name()}`;
        if (this._actionHandler) {
          checkForUnknownOptions();
          this._processArguments();
          let promiseChain;
          promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
          promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
          if (this.parent) {
            promiseChain = this._chainOrCall(promiseChain, () => {
              this.parent.emit(commandEvent, operands, unknown);
            });
          }
          promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
          return promiseChain;
        }
        if (this.parent && this.parent.listenerCount(commandEvent)) {
          checkForUnknownOptions();
          this._processArguments();
          this.parent.emit(commandEvent, operands, unknown);
        } else if (operands.length) {
          if (this._findCommand("*")) {
            return this._dispatchSubcommand("*", operands, unknown);
          }
          if (this.listenerCount("command:*")) {
            this.emit("command:*", operands, unknown);
          } else if (this.commands.length) {
            this.unknownCommand();
          } else {
            checkForUnknownOptions();
            this._processArguments();
          }
        } else if (this.commands.length) {
          checkForUnknownOptions();
          this.help({ error: true });
        } else {
          checkForUnknownOptions();
          this._processArguments();
        }
      }
      /**
       * Find matching command.
       *
       * @api private
       */
      _findCommand(name) {
        if (!name)
          return void 0;
        return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
      }
      /**
       * Return an option matching `arg` if any.
       *
       * @param {string} arg
       * @return {Option}
       * @api private
       */
      _findOption(arg) {
        return this.options.find((option) => option.is(arg));
      }
      /**
       * Display an error message if a mandatory option does not have a value.
       * Called after checking for help flags in leaf subcommand.
       *
       * @api private
       */
      _checkForMissingMandatoryOptions() {
        this._getCommandAndAncestors().forEach((cmd) => {
          cmd.options.forEach((anOption) => {
            if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
              cmd.missingMandatoryOptionValue(anOption);
            }
          });
        });
      }
      /**
       * Display an error message if conflicting options are used together in this.
       *
       * @api private
       */
      _checkForConflictingLocalOptions() {
        const definedNonDefaultOptions = this.options.filter(
          (option) => {
            const optionKey = option.attributeName();
            if (this.getOptionValue(optionKey) === void 0) {
              return false;
            }
            return this.getOptionValueSource(optionKey) !== "default";
          }
        );
        const optionsWithConflicting = definedNonDefaultOptions.filter(
          (option) => option.conflictsWith.length > 0
        );
        optionsWithConflicting.forEach((option) => {
          const conflictingAndDefined = definedNonDefaultOptions.find(
            (defined) => option.conflictsWith.includes(defined.attributeName())
          );
          if (conflictingAndDefined) {
            this._conflictingOption(option, conflictingAndDefined);
          }
        });
      }
      /**
       * Display an error message if conflicting options are used together.
       * Called after checking for help flags in leaf subcommand.
       *
       * @api private
       */
      _checkForConflictingOptions() {
        this._getCommandAndAncestors().forEach((cmd) => {
          cmd._checkForConflictingLocalOptions();
        });
      }
      /**
       * Parse options from `argv` removing known options,
       * and return argv split into operands and unknown arguments.
       *
       * Examples:
       *
       *     argv => operands, unknown
       *     --known kkk op => [op], []
       *     op --known kkk => [op], []
       *     sub --unknown uuu op => [sub], [--unknown uuu op]
       *     sub -- --unknown uuu op => [sub --unknown uuu op], []
       *
       * @param {String[]} argv
       * @return {{operands: String[], unknown: String[]}}
       */
      parseOptions(argv2) {
        const operands = [];
        const unknown = [];
        let dest = operands;
        const args = argv2.slice();
        function maybeOption(arg) {
          return arg.length > 1 && arg[0] === "-";
        }
        let activeVariadicOption = null;
        while (args.length) {
          const arg = args.shift();
          if (arg === "--") {
            if (dest === unknown)
              dest.push(arg);
            dest.push(...args);
            break;
          }
          if (activeVariadicOption && !maybeOption(arg)) {
            this.emit(`option:${activeVariadicOption.name()}`, arg);
            continue;
          }
          activeVariadicOption = null;
          if (maybeOption(arg)) {
            const option = this._findOption(arg);
            if (option) {
              if (option.required) {
                const value = args.shift();
                if (value === void 0)
                  this.optionMissingArgument(option);
                this.emit(`option:${option.name()}`, value);
              } else if (option.optional) {
                let value = null;
                if (args.length > 0 && !maybeOption(args[0])) {
                  value = args.shift();
                }
                this.emit(`option:${option.name()}`, value);
              } else {
                this.emit(`option:${option.name()}`);
              }
              activeVariadicOption = option.variadic ? option : null;
              continue;
            }
          }
          if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
            const option = this._findOption(`-${arg[1]}`);
            if (option) {
              if (option.required || option.optional && this._combineFlagAndOptionalValue) {
                this.emit(`option:${option.name()}`, arg.slice(2));
              } else {
                this.emit(`option:${option.name()}`);
                args.unshift(`-${arg.slice(2)}`);
              }
              continue;
            }
          }
          if (/^--[^=]+=/.test(arg)) {
            const index = arg.indexOf("=");
            const option = this._findOption(arg.slice(0, index));
            if (option && (option.required || option.optional)) {
              this.emit(`option:${option.name()}`, arg.slice(index + 1));
              continue;
            }
          }
          if (maybeOption(arg)) {
            dest = unknown;
          }
          if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
            if (this._findCommand(arg)) {
              operands.push(arg);
              if (args.length > 0)
                unknown.push(...args);
              break;
            } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {
              operands.push(arg);
              if (args.length > 0)
                operands.push(...args);
              break;
            } else if (this._defaultCommandName) {
              unknown.push(arg);
              if (args.length > 0)
                unknown.push(...args);
              break;
            }
          }
          if (this._passThroughOptions) {
            dest.push(arg);
            if (args.length > 0)
              dest.push(...args);
            break;
          }
          dest.push(arg);
        }
        return { operands, unknown };
      }
      /**
       * Return an object containing local option values as key-value pairs.
       *
       * @return {Object}
       */
      opts() {
        if (this._storeOptionsAsProperties) {
          const result = {};
          const len = this.options.length;
          for (let i2 = 0; i2 < len; i2++) {
            const key = this.options[i2].attributeName();
            result[key] = key === this._versionOptionName ? this._version : this[key];
          }
          return result;
        }
        return this._optionValues;
      }
      /**
       * Return an object containing merged local and global option values as key-value pairs.
       *
       * @return {Object}
       */
      optsWithGlobals() {
        return this._getCommandAndAncestors().reduce(
          (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
          {}
        );
      }
      /**
       * Display error message and exit (or call exitOverride).
       *
       * @param {string} message
       * @param {Object} [errorOptions]
       * @param {string} [errorOptions.code] - an id string representing the error
       * @param {number} [errorOptions.exitCode] - used with process.exit
       */
      error(message, errorOptions) {
        this._outputConfiguration.outputError(`${message}
`, this._outputConfiguration.writeErr);
        if (typeof this._showHelpAfterError === "string") {
          this._outputConfiguration.writeErr(`${this._showHelpAfterError}
`);
        } else if (this._showHelpAfterError) {
          this._outputConfiguration.writeErr("\n");
          this.outputHelp({ error: true });
        }
        const config = errorOptions || {};
        const exitCode = config.exitCode || 1;
        const code = config.code || "commander.error";
        this._exit(exitCode, code, message);
      }
      /**
       * Apply any option related environment variables, if option does
       * not have a value from cli or client code.
       *
       * @api private
       */
      _parseOptionsEnv() {
        this.options.forEach((option) => {
          if (option.envVar && option.envVar in process2.env) {
            const optionKey = option.attributeName();
            if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
              if (option.required || option.optional) {
                this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
              } else {
                this.emit(`optionEnv:${option.name()}`);
              }
            }
          }
        });
      }
      /**
       * Apply any implied option values, if option is undefined or default value.
       *
       * @api private
       */
      _parseOptionsImplied() {
        const dualHelper = new DualOptions(this.options);
        const hasCustomOptionValue = (optionKey) => {
          return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
        };
        this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
          Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
            this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
          });
        });
      }
      /**
       * Argument `name` is missing.
       *
       * @param {string} name
       * @api private
       */
      missingArgument(name) {
        const message = `error: missing required argument '${name}'`;
        this.error(message, { code: "commander.missingArgument" });
      }
      /**
       * `Option` is missing an argument.
       *
       * @param {Option} option
       * @api private
       */
      optionMissingArgument(option) {
        const message = `error: option '${option.flags}' argument missing`;
        this.error(message, { code: "commander.optionMissingArgument" });
      }
      /**
       * `Option` does not have a value, and is a mandatory option.
       *
       * @param {Option} option
       * @api private
       */
      missingMandatoryOptionValue(option) {
        const message = `error: required option '${option.flags}' not specified`;
        this.error(message, { code: "commander.missingMandatoryOptionValue" });
      }
      /**
       * `Option` conflicts with another option.
       *
       * @param {Option} option
       * @param {Option} conflictingOption
       * @api private
       */
      _conflictingOption(option, conflictingOption) {
        const findBestOptionFromValue = (option2) => {
          const optionKey = option2.attributeName();
          const optionValue = this.getOptionValue(optionKey);
          const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
          const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
          if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
            return negativeOption;
          }
          return positiveOption || option2;
        };
        const getErrorMessage = (option2) => {
          const bestOption = findBestOptionFromValue(option2);
          const optionKey = bestOption.attributeName();
          const source = this.getOptionValueSource(optionKey);
          if (source === "env") {
            return `environment variable '${bestOption.envVar}'`;
          }
          return `option '${bestOption.flags}'`;
        };
        const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
        this.error(message, { code: "commander.conflictingOption" });
      }
      /**
       * Unknown option `flag`.
       *
       * @param {string} flag
       * @api private
       */
      unknownOption(flag) {
        if (this._allowUnknownOption)
          return;
        let suggestion = "";
        if (flag.startsWith("--") && this._showSuggestionAfterError) {
          let candidateFlags = [];
          let command = this;
          do {
            const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
            candidateFlags = candidateFlags.concat(moreFlags);
            command = command.parent;
          } while (command && !command._enablePositionalOptions);
          suggestion = suggestSimilar(flag, candidateFlags);
        }
        const message = `error: unknown option '${flag}'${suggestion}`;
        this.error(message, { code: "commander.unknownOption" });
      }
      /**
       * Excess arguments, more than expected.
       *
       * @param {string[]} receivedArgs
       * @api private
       */
      _excessArguments(receivedArgs) {
        if (this._allowExcessArguments)
          return;
        const expected = this.registeredArguments.length;
        const s2 = expected === 1 ? "" : "s";
        const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
        const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s2} but got ${receivedArgs.length}.`;
        this.error(message, { code: "commander.excessArguments" });
      }
      /**
       * Unknown command.
       *
       * @api private
       */
      unknownCommand() {
        const unknownName = this.args[0];
        let suggestion = "";
        if (this._showSuggestionAfterError) {
          const candidateNames = [];
          this.createHelp().visibleCommands(this).forEach((command) => {
            candidateNames.push(command.name());
            if (command.alias())
              candidateNames.push(command.alias());
          });
          suggestion = suggestSimilar(unknownName, candidateNames);
        }
        const message = `error: unknown command '${unknownName}'${suggestion}`;
        this.error(message, { code: "commander.unknownCommand" });
      }
      /**
       * Get or set the program version.
       *
       * This method auto-registers the "-V, --version" option which will print the version number.
       *
       * You can optionally supply the flags and description to override the defaults.
       *
       * @param {string} [str]
       * @param {string} [flags]
       * @param {string} [description]
       * @return {this | string | undefined} `this` command for chaining, or version string if no arguments
       */
      version(str, flags, description) {
        if (str === void 0)
          return this._version;
        this._version = str;
        flags = flags || "-V, --version";
        description = description || "output the version number";
        const versionOption = this.createOption(flags, description);
        this._versionOptionName = versionOption.attributeName();
        this.options.push(versionOption);
        this.on("option:" + versionOption.name(), () => {
          this._outputConfiguration.writeOut(`${str}
`);
          this._exit(0, "commander.version", str);
        });
        return this;
      }
      /**
       * Set the description.
       *
       * @param {string} [str]
       * @param {Object} [argsDescription]
       * @return {string|Command}
       */
      description(str, argsDescription) {
        if (str === void 0 && argsDescription === void 0)
          return this._description;
        this._description = str;
        if (argsDescription) {
          this._argsDescription = argsDescription;
        }
        return this;
      }
      /**
       * Set the summary. Used when listed as subcommand of parent.
       *
       * @param {string} [str]
       * @return {string|Command}
       */
      summary(str) {
        if (str === void 0)
          return this._summary;
        this._summary = str;
        return this;
      }
      /**
       * Set an alias for the command.
       *
       * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
       *
       * @param {string} [alias]
       * @return {string|Command}
       */
      alias(alias) {
        if (alias === void 0)
          return this._aliases[0];
        let command = this;
        if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
          command = this.commands[this.commands.length - 1];
        }
        if (alias === command._name)
          throw new Error("Command alias can't be the same as its name");
        command._aliases.push(alias);
        return this;
      }
      /**
       * Set aliases for the command.
       *
       * Only the first alias is shown in the auto-generated help.
       *
       * @param {string[]} [aliases]
       * @return {string[]|Command}
       */
      aliases(aliases) {
        if (aliases === void 0)
          return this._aliases;
        aliases.forEach((alias) => this.alias(alias));
        return this;
      }
      /**
       * Set / get the command usage `str`.
       *
       * @param {string} [str]
       * @return {String|Command}
       */
      usage(str) {
        if (str === void 0) {
          if (this._usage)
            return this._usage;
          const args = this.registeredArguments.map((arg) => {
            return humanReadableArgName(arg);
          });
          return [].concat(
            this.options.length || this._hasHelpOption ? "[options]" : [],
            this.commands.length ? "[command]" : [],
            this.registeredArguments.length ? args : []
          ).join(" ");
        }
        this._usage = str;
        return this;
      }
      /**
       * Get or set the name of the command.
       *
       * @param {string} [str]
       * @return {string|Command}
       */
      name(str) {
        if (str === void 0)
          return this._name;
        this._name = str;
        return this;
      }
      /**
       * Set the name of the command from script filename, such as process.argv[1],
       * or require.main.filename, or __filename.
       *
       * (Used internally and public although not documented in README.)
       *
       * @example
       * program.nameFromFilename(require.main.filename);
       *
       * @param {string} filename
       * @return {Command}
       */
      nameFromFilename(filename) {
        this._name = path2.basename(filename, path2.extname(filename));
        return this;
      }
      /**
       * Get or set the directory for searching for executable subcommands of this command.
       *
       * @example
       * program.executableDir(__dirname);
       * // or
       * program.executableDir('subcommands');
       *
       * @param {string} [path]
       * @return {string|null|Command}
       */
      executableDir(path3) {
        if (path3 === void 0)
          return this._executableDir;
        this._executableDir = path3;
        return this;
      }
      /**
       * Return program help documentation.
       *
       * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
       * @return {string}
       */
      helpInformation(contextOptions) {
        const helper = this.createHelp();
        if (helper.helpWidth === void 0) {
          helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
        }
        return helper.formatHelp(this, helper);
      }
      /**
       * @api private
       */
      _getHelpContext(contextOptions) {
        contextOptions = contextOptions || {};
        const context2 = { error: !!contextOptions.error };
        let write;
        if (context2.error) {
          write = (arg) => this._outputConfiguration.writeErr(arg);
        } else {
          write = (arg) => this._outputConfiguration.writeOut(arg);
        }
        context2.write = contextOptions.write || write;
        context2.command = this;
        return context2;
      }
      /**
       * Output help information for this command.
       *
       * Outputs built-in help, and custom text added using `.addHelpText()`.
       *
       * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
       */
      outputHelp(contextOptions) {
        let deprecatedCallback;
        if (typeof contextOptions === "function") {
          deprecatedCallback = contextOptions;
          contextOptions = void 0;
        }
        const context2 = this._getHelpContext(contextOptions);
        this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context2));
        this.emit("beforeHelp", context2);
        let helpInformation = this.helpInformation(context2);
        if (deprecatedCallback) {
          helpInformation = deprecatedCallback(helpInformation);
          if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
            throw new Error("outputHelp callback must return a string or a Buffer");
          }
        }
        context2.write(helpInformation);
        if (this._helpLongFlag) {
          this.emit(this._helpLongFlag);
        }
        this.emit("afterHelp", context2);
        this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", context2));
      }
      /**
       * You can pass in flags and a description to override the help
       * flags and help description for your command. Pass in false to
       * disable the built-in help option.
       *
       * @param {string | boolean} [flags]
       * @param {string} [description]
       * @return {Command} `this` command for chaining
       */
      helpOption(flags, description) {
        if (typeof flags === "boolean") {
          this._hasHelpOption = flags;
          return this;
        }
        this._helpFlags = flags || this._helpFlags;
        this._helpDescription = description || this._helpDescription;
        const helpFlags = splitOptionFlags(this._helpFlags);
        this._helpShortFlag = helpFlags.shortFlag;
        this._helpLongFlag = helpFlags.longFlag;
        return this;
      }
      /**
       * Output help information and exit.
       *
       * Outputs built-in help, and custom text added using `.addHelpText()`.
       *
       * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
       */
      help(contextOptions) {
        this.outputHelp(contextOptions);
        let exitCode = process2.exitCode || 0;
        if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
          exitCode = 1;
        }
        this._exit(exitCode, "commander.help", "(outputHelp)");
      }
      /**
       * Add additional text to be displayed with the built-in help.
       *
       * Position is 'before' or 'after' to affect just this command,
       * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
       *
       * @param {string} position - before or after built-in help
       * @param {string | Function} text - string to add, or a function returning a string
       * @return {Command} `this` command for chaining
       */
      addHelpText(position, text) {
        const allowedValues = ["beforeAll", "before", "after", "afterAll"];
        if (!allowedValues.includes(position)) {
          throw new Error(`Unexpected value for position to addHelpText.
Expecting one of '${allowedValues.join("', '")}'`);
        }
        const helpEvent = `${position}Help`;
        this.on(helpEvent, (context2) => {
          let helpStr;
          if (typeof text === "function") {
            helpStr = text({ error: context2.error, command: context2.command });
          } else {
            helpStr = text;
          }
          if (helpStr) {
            context2.write(`${helpStr}
`);
          }
        });
        return this;
      }
    };
    function outputHelpIfRequested(cmd, args) {
      const helpOption = cmd._hasHelpOption && args.find((arg) => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);
      if (helpOption) {
        cmd.outputHelp();
        cmd._exit(0, "commander.helpDisplayed", "(outputHelp)");
      }
    }
    function incrementNodeInspectorPort(args) {
      return args.map((arg) => {
        if (!arg.startsWith("--inspect")) {
          return arg;
        }
        let debugOption;
        let debugHost = "127.0.0.1";
        let debugPort = "9229";
        let match;
        if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
          debugOption = match[1];
        } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
          debugOption = match[1];
          if (/^\d+$/.test(match[3])) {
            debugPort = match[3];
          } else {
            debugHost = match[3];
          }
        } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
          debugOption = match[1];
          debugHost = match[3];
          debugPort = match[4];
        }
        if (debugOption && debugPort !== "0") {
          return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
        }
        return arg;
      });
    }
    exports.Command = Command3;
  }
});

// ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/index.js
var require_commander = __commonJS({
  "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/index.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var { Argument: Argument2 } = require_argument();
    var { Command: Command3 } = require_command();
    var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
    var { Help: Help2 } = require_help();
    var { Option: Option2 } = require_option();
    exports = module.exports = new Command3();
    exports.program = exports;
    exports.Command = Command3;
    exports.Option = Option2;
    exports.Argument = Argument2;
    exports.Help = Help2;
    exports.CommanderError = CommanderError2;
    exports.InvalidArgumentError = InvalidArgumentError2;
    exports.InvalidOptionArgumentError = InvalidArgumentError2;
  }
});

// ../../node_modules/.pnpm/human-id@4.1.1/node_modules/human-id/dist/index.js
var require_dist = __commonJS({
  "../../node_modules/.pnpm/human-id@4.1.1/node_modules/human-id/dist/index.js"(exports) {
    "use strict";
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var __spreadArray = exports && exports.__spreadArray || function(to, from, pack) {
      if (pack || arguments.length === 2)
        for (var i2 = 0, l2 = from.length, ar; i2 < l2; i2++) {
          if (ar || !(i2 in from)) {
            if (!ar)
              ar = Array.prototype.slice.call(from, 0, i2);
            ar[i2] = from[i2];
          }
        }
      return to.concat(ar || Array.prototype.slice.call(from));
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.minLength = exports.maxLength = exports.poolSize = exports.humanId = exports.adverbs = exports.verbs = exports.nouns = exports.adjectives = void 0;
    exports.adjectives = ["afraid", "all", "angry", "beige", "big", "better", "bitter", "blue", "brave", "breezy", "bright", "brown", "bumpy", "busy", "calm", "chatty", "chilly", "chubby", "clean", "clear", "clever", "cold", "crazy", "cruel", "cuddly", "curly", "curvy", "cute", "common", "cold", "cool", "cyan", "dark", "deep", "dirty", "dry", "dull", "eager", "early", "easy", "eight", "eighty", "eleven", "empty", "every", "evil", "fair", "famous", "fast", "fancy", "few", "fine", "fifty", "five", "flat", "fluffy", "floppy", "forty", "four", "free", "fresh", "fruity", "full", "funny", "fuzzy", "gentle", "giant", "gold", "good", "great", "green", "grumpy", "happy", "heavy", "hip", "honest", "hot", "huge", "hungry", "icy", "itchy", "khaki", "kind", "large", "late", "lazy", "lemon", "legal", "light", "little", "long", "loose", "loud", "lovely", "lucky", "major", "many", "mean", "metal", "mighty", "modern", "moody", "nasty", "neat", "new", "nice", "nine", "ninety", "odd", "old", "olive", "open", "orange", "pink", "plain", "plenty", "polite", "poor", "pretty", "proud", "public", "puny", "petite", "purple", "quick", "quiet", "rare", "real", "ready", "red", "rich", "ripe", "rotten", "rude", "sad", "salty", "seven", "shaggy", "shaky", "sharp", "shiny", "short", "shy", "silent", "silly", "silver", "six", "sixty", "slick", "slimy", "slow", "small", "smart", "smooth", "social", "soft", "solid", "some", "sour", "spicy", "spotty", "stale", "strong", "stupid", "sweet", "swift", "tall", "tame", "tangy", "tasty", "ten", "tender", "thick", "thin", "thirty", "three", "tidy", "tiny", "tired", "tough", "tricky", "true", "twelve", "twenty", "two", "upset", "vast", "violet", "warm", "weak", "wet", "whole", "wicked", "wide", "wild", "wise", "witty", "yellow", "young", "yummy"];
    exports.nouns = ["apes", "animals", "areas", "bars", "banks", "baths", "breads", "bushes", "cloths", "clowns", "clubs", "hoops", "loops", "memes", "papers", "parks", "paths", "showers", "sides", "signs", "sites", "streets", "teeth", "tires", "webs", "actors", "ads", "adults", "aliens", "ants", "apples", "baboons", "badgers", "bags", "bananas", "bats", "beans", "bears", "beds", "beers", "bees", "berries", "bikes", "birds", "boats", "bobcats", "books", "bottles", "boxes", "brooms", "buckets", "bugs", "buses", "buttons", "camels", "cases", "cameras", "candies", "candles", "carpets", "carrots", "carrots", "cars", "cats", "chairs", "chefs", "chicken", "clocks", "clouds", "coats", "cobras", "coins", "corners", "colts", "comics", "cooks", "cougars", "regions", "results", "cows", "crabs", "crabs", "crews", "cups", "cities", "cycles", "dancers", "days", "deer", "dingos", "dodos", "dogs", "dolls", "donkeys", "donuts", "doodles", "doors", "dots", "dragons", "drinks", "dryers", "ducks", "ducks", "eagles", "ears", "eels", "eggs", "ends", "mammals", "emus", "experts", "eyes", "facts", "falcons", "fans", "feet", "files", "flies", "flowers", "forks", "foxes", "friends", "frogs", "games", "garlics", "geckos", "geese", "ghosts", "ghosts", "gifts", "glasses", "goats", "grapes", "groups", "guests", "hairs", "hands", "hats", "heads", "hornets", "horses", "hotels", "hounds", "houses", "humans", "icons", "ideas", "impalas", "insects", "islands", "items", "jars", "jeans", "jobs", "jokes", "keys", "kids", "kings", "kiwis", "knives", "lamps", "lands", "laws", "lemons", "lies", "lights", "lines", "lions", "lizards", "llamas", "mails", "mangos", "maps", "masks", "meals", "melons", "mice", "mirrors", "moments", "moles", "monkeys", "months", "moons", "moose", "mugs", "nails", "needles", "news", "nights", "numbers", "olives", "onions", "oranges", "otters", "owls", "pandas", "pans", "pants", "papayas", "parents", "parts", "parrots", "paws", "peaches", "pears", "peas", "pens", "pets", "phones", "pianos", "pigs", "pillows", "places", "planes", "planets", "plants", "plums", "poems", "poets", "points", "pots", "pugs", "pumas", "queens", "rabbits", "radios", "rats", "ravens", "readers", "rice", "rings", "rivers", "rockets", "rocks", "rooms", "roses", "rules", "schools", "bats", "seals", "seas", "sheep", "shirts", "shoes", "shrimps", "singers", "sloths", "snails", "snakes", "socks", "spiders", "spies", "spoons", "squids", "stars", "states", "steaks", "wings", "suits", "suns", "swans", "symbols", "tables", "taxes", "taxis", "teams", "terms", "things", "ties", "tigers", "times", "tips", "toes", "towns", "tools", "toys", "trains", "trams", "trees", "turkeys", "turtles", "vans", "views", "walls", "walls", "wasps", "waves", "ways", "weeks", "windows", "wolves", "women", "wombats", "words", "worlds", "worms", "yaks", "years", "zebras", "zoos"];
    exports.verbs = ["accept", "act", "add", "admire", "agree", "allow", "appear", "argue", "arrive", "ask", "attack", "attend", "bake", "bathe", "battle", "beam", "beg", "begin", "behave", "bet", "boil", "bow", "brake", "brush", "build", "burn", "buy", "call", "camp", "care", "carry", "change", "cheat", "check", "cheer", "chew", "clap", "clean", "cough", "count", "cover", "crash", "create", "cross", "cry", "cut", "dance", "decide", "deny", "design", "dig", "divide", "do", "double", "doubt", "draw", "dream", "dress", "drive", "drop", "drum", "eat", "end", "enter", "enjoy", "exist", "fail", "fall", "feel", "fetch", "film", "find", "fix", "flash", "float", "flow", "fly", "fold", "follow", "fry", "give", "glow", "go", "grab", "greet", "grin", "grow", "guess", "hammer", "hang", "happen", "heal", "hear", "help", "hide", "hope", "hug", "hunt", "invent", "invite", "itch", "jam", "jog", "join", "joke", "judge", "juggle", "jump", "kick", "kiss", "kneel", "knock", "know", "laugh", "lay", "lead", "learn", "leave", "lick", "like", "lie", "listen", "live", "look", "lose", "love", "make", "march", "marry", "mate", "matter", "melt", "mix", "move", "nail", "notice", "obey", "occur", "open", "own", "pay", "peel", "play", "poke", "post", "press", "prove", "pull", "pump", "pick", "punch", "push", "raise", "read", "refuse", "relate", "relax", "remain", "repair", "repeat", "reply", "report", "rescue", "rest", "retire", "return", "rhyme", "ring", "roll", "rule", "run", "rush", "say", "scream", "see", "search", "sell", "send", "serve", "shake", "share", "shave", "shine", "show", "shop", "shout", "sin", "sink", "sing", "sip", "sit", "sleep", "slide", "smash", "smell", "smile", "smoke", "sneeze", "sniff", "sort", "speak", "spend", "stand", "start", "stay", "stick", "stop", "stare", "study", "strive", "swim", "switch", "take", "talk", "tan", "tap", "taste", "teach", "tease", "tell", "thank", "think", "throw", "tickle", "tie", "trade", "train", "travel", "try", "turn", "type", "unite", "vanish", "visit", "wait", "walk", "warn", "wash", "watch", "wave", "wear", "win", "wink", "wish", "wonder", "work", "worry", "write", "yawn", "yell"];
    exports.adverbs = ["bravely", "brightly", "busily", "daily", "freely", "hungrily", "joyously", "knowlingly", "lazily", "oddly", "mysteriously", "noisily", "politely", "quickly", "quietly", "rapidly", "safely", "sleepily", "slowly", "truly", "yearly"];
    function random2(arr) {
      return arr[Math.floor(Math.random() * arr.length)];
    }
    function longest(arr) {
      return arr.reduce(function(a3, b) {
        return a3.length > b.length ? a3 : b;
      });
    }
    function shortest(arr) {
      return arr.reduce(function(a3, b) {
        return a3.length < b.length ? a3 : b;
      });
    }
    function humanId4(options) {
      if (options === void 0) {
        options = {};
      }
      if (typeof options === "string")
        options = { separator: options };
      if (typeof options === "boolean")
        options = { capitalize: options };
      var _a8 = options.separator, separator = _a8 === void 0 ? "" : _a8, _b5 = options.capitalize, capitalize = _b5 === void 0 ? true : _b5, _c = options.adjectiveCount, adjectiveCount = _c === void 0 ? 1 : _c, _d = options.addAdverb, addAdverb = _d === void 0 ? false : _d;
      var res = __spreadArray(__spreadArray(__spreadArray([], __spreadArray([], Array(adjectiveCount), true).map(function(_3) {
        return random2(exports.adjectives);
      }), true), [
        random2(exports.nouns),
        random2(exports.verbs)
      ], false), addAdverb ? [random2(exports.adverbs)] : [], true);
      if (capitalize)
        res = res.map(function(r3) {
          return r3.charAt(0).toUpperCase() + r3.substr(1);
        });
      return res.join(separator);
    }
    exports.humanId = humanId4;
    function poolSize(options) {
      if (options === void 0) {
        options = {};
      }
      var _a8 = options.adjectiveCount, adjectiveCount = _a8 === void 0 ? 1 : _a8, _b5 = options.addAdverb, addAdverb = _b5 === void 0 ? false : _b5;
      return exports.adjectives.length * adjectiveCount * exports.nouns.length * exports.verbs.length * (addAdverb ? exports.adverbs.length : 1);
    }
    exports.poolSize = poolSize;
    function maxLength(options) {
      if (options === void 0) {
        options = {};
      }
      var _a8 = options.adjectiveCount, adjectiveCount = _a8 === void 0 ? 1 : _a8, _b5 = options.addAdverb, addAdverb = _b5 === void 0 ? false : _b5, _c = options.separator, separator = _c === void 0 ? "" : _c;
      return longest(exports.adjectives).length * adjectiveCount + adjectiveCount * separator.length + longest(exports.nouns).length + separator.length + longest(exports.verbs).length + (addAdverb ? longest(exports.adverbs).length + separator.length : 0);
    }
    exports.maxLength = maxLength;
    function minLength(options) {
      if (options === void 0) {
        options = {};
      }
      var _a8 = options.adjectiveCount, adjectiveCount = _a8 === void 0 ? 1 : _a8, _b5 = options.addAdverb, addAdverb = _b5 === void 0 ? false : _b5, _c = options.separator, separator = _c === void 0 ? "" : _c;
      return shortest(exports.adjectives).length * adjectiveCount + adjectiveCount * separator.length + shortest(exports.nouns).length + separator.length + shortest(exports.verbs).length + (addAdverb ? shortest(exports.adverbs).length + separator.length : 0);
    }
    exports.minLength = minLength;
    exports.default = humanId4;
  }
});

// ../../node_modules/.pnpm/js-sha256@0.11.1/node_modules/js-sha256/src/sha256.js
var require_sha256 = __commonJS({
  "../../node_modules/.pnpm/js-sha256@0.11.1/node_modules/js-sha256/src/sha256.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    (function() {
      "use strict";
      var ERROR = "input is invalid type";
      var WINDOW = typeof window === "object";
      var root = WINDOW ? window : {};
      if (root.JS_SHA256_NO_WINDOW) {
        WINDOW = false;
      }
      var WEB_WORKER = !WINDOW && typeof self === "object";
      var NODE_JS = !root.JS_SHA256_NO_NODE_JS && typeof process === "object" && process.versions && process.versions.node && process.type != "renderer";
      if (NODE_JS) {
        root = global;
      } else if (WEB_WORKER) {
        root = self;
      }
      var COMMON_JS = !root.JS_SHA256_NO_COMMON_JS && typeof module === "object" && module.exports;
      var AMD = typeof define === "function" && define.amd;
      var ARRAY_BUFFER = !root.JS_SHA256_NO_ARRAY_BUFFER && typeof ArrayBuffer !== "undefined";
      var HEX_CHARS = "0123456789abcdef".split("");
      var EXTRA = [-2147483648, 8388608, 32768, 128];
      var SHIFT = [24, 16, 8, 0];
      var K = [
        1116352408,
        1899447441,
        3049323471,
        3921009573,
        961987163,
        1508970993,
        2453635748,
        2870763221,
        3624381080,
        310598401,
        607225278,
        1426881987,
        1925078388,
        2162078206,
        2614888103,
        3248222580,
        3835390401,
        4022224774,
        264347078,
        604807628,
        770255983,
        1249150122,
        1555081692,
        1996064986,
        2554220882,
        2821834349,
        2952996808,
        3210313671,
        3336571891,
        3584528711,
        113926993,
        338241895,
        666307205,
        773529912,
        1294757372,
        1396182291,
        1695183700,
        1986661051,
        2177026350,
        2456956037,
        2730485921,
        2820302411,
        3259730800,
        3345764771,
        3516065817,
        3600352804,
        4094571909,
        275423344,
        430227734,
        506948616,
        659060556,
        883997877,
        958139571,
        1322822218,
        1537002063,
        1747873779,
        1955562222,
        2024104815,
        2227730452,
        2361852424,
        2428436474,
        2756734187,
        3204031479,
        3329325298
      ];
      var OUTPUT_TYPES = ["hex", "array", "digest", "arrayBuffer"];
      var blocks = [];
      if (root.JS_SHA256_NO_NODE_JS || !Array.isArray) {
        Array.isArray = function(obj) {
          return Object.prototype.toString.call(obj) === "[object Array]";
        };
      }
      if (ARRAY_BUFFER && (root.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) {
        ArrayBuffer.isView = function(obj) {
          return typeof obj === "object" && obj.buffer && obj.buffer.constructor === ArrayBuffer;
        };
      }
      var createOutputMethod = function(outputType, is224) {
        return function(message) {
          return new Sha256(is224, true).update(message)[outputType]();
        };
      };
      var createMethod = function(is224) {
        var method = createOutputMethod("hex", is224);
        if (NODE_JS) {
          method = nodeWrap(method, is224);
        }
        method.create = function() {
          return new Sha256(is224);
        };
        method.update = function(message) {
          return method.create().update(message);
        };
        for (var i2 = 0; i2 < OUTPUT_TYPES.length; ++i2) {
          var type = OUTPUT_TYPES[i2];
          method[type] = createOutputMethod(type, is224);
        }
        return method;
      };
      var nodeWrap = function(method, is224) {
        var crypto2 = __require("crypto");
        var Buffer2 = __require("buffer").Buffer;
        var algorithm = is224 ? "sha224" : "sha256";
        var bufferFrom;
        if (Buffer2.from && !root.JS_SHA256_NO_BUFFER_FROM) {
          bufferFrom = Buffer2.from;
        } else {
          bufferFrom = function(message) {
            return new Buffer2(message);
          };
        }
        var nodeMethod = function(message) {
          if (typeof message === "string") {
            return crypto2.createHash(algorithm).update(message, "utf8").digest("hex");
          } else {
            if (message === null || message === void 0) {
              throw new Error(ERROR);
            } else if (message.constructor === ArrayBuffer) {
              message = new Uint8Array(message);
            }
          }
          if (Array.isArray(message) || ArrayBuffer.isView(message) || message.constructor === Buffer2) {
            return crypto2.createHash(algorithm).update(bufferFrom(message)).digest("hex");
          } else {
            return method(message);
          }
        };
        return nodeMethod;
      };
      var createHmacOutputMethod = function(outputType, is224) {
        return function(key, message) {
          return new HmacSha256(key, is224, true).update(message)[outputType]();
        };
      };
      var createHmacMethod = function(is224) {
        var method = createHmacOutputMethod("hex", is224);
        method.create = function(key) {
          return new HmacSha256(key, is224);
        };
        method.update = function(key, message) {
          return method.create(key).update(message);
        };
        for (var i2 = 0; i2 < OUTPUT_TYPES.length; ++i2) {
          var type = OUTPUT_TYPES[i2];
          method[type] = createHmacOutputMethod(type, is224);
        }
        return method;
      };
      function Sha256(is224, sharedMemory) {
        if (sharedMemory) {
          blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;
          this.blocks = blocks;
        } else {
          this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        }
        if (is224) {
          this.h0 = 3238371032;
          this.h1 = 914150663;
          this.h2 = 812702999;
          this.h3 = 4144912697;
          this.h4 = 4290775857;
          this.h5 = 1750603025;
          this.h6 = 1694076839;
          this.h7 = 3204075428;
        } else {
          this.h0 = 1779033703;
          this.h1 = 3144134277;
          this.h2 = 1013904242;
          this.h3 = 2773480762;
          this.h4 = 1359893119;
          this.h5 = 2600822924;
          this.h6 = 528734635;
          this.h7 = 1541459225;
        }
        this.block = this.start = this.bytes = this.hBytes = 0;
        this.finalized = this.hashed = false;
        this.first = true;
        this.is224 = is224;
      }
      Sha256.prototype.update = function(message) {
        if (this.finalized) {
          return;
        }
        var notString, type = typeof message;
        if (type !== "string") {
          if (type === "object") {
            if (message === null) {
              throw new Error(ERROR);
            } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) {
              message = new Uint8Array(message);
            } else if (!Array.isArray(message)) {
              if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) {
                throw new Error(ERROR);
              }
            }
          } else {
            throw new Error(ERROR);
          }
          notString = true;
        }
        var code, index = 0, i2, length = message.length, blocks2 = this.blocks;
        while (index < length) {
          if (this.hashed) {
            this.hashed = false;
            blocks2[0] = this.block;
            this.block = blocks2[16] = blocks2[1] = blocks2[2] = blocks2[3] = blocks2[4] = blocks2[5] = blocks2[6] = blocks2[7] = blocks2[8] = blocks2[9] = blocks2[10] = blocks2[11] = blocks2[12] = blocks2[13] = blocks2[14] = blocks2[15] = 0;
          }
          if (notString) {
            for (i2 = this.start; index < length && i2 < 64; ++index) {
              blocks2[i2 >>> 2] |= message[index] << SHIFT[i2++ & 3];
            }
          } else {
            for (i2 = this.start; index < length && i2 < 64; ++index) {
              code = message.charCodeAt(index);
              if (code < 128) {
                blocks2[i2 >>> 2] |= code << SHIFT[i2++ & 3];
              } else if (code < 2048) {
                blocks2[i2 >>> 2] |= (192 | code >>> 6) << SHIFT[i2++ & 3];
                blocks2[i2 >>> 2] |= (128 | code & 63) << SHIFT[i2++ & 3];
              } else if (code < 55296 || code >= 57344) {
                blocks2[i2 >>> 2] |= (224 | code >>> 12) << SHIFT[i2++ & 3];
                blocks2[i2 >>> 2] |= (128 | code >>> 6 & 63) << SHIFT[i2++ & 3];
                blocks2[i2 >>> 2] |= (128 | code & 63) << SHIFT[i2++ & 3];
              } else {
                code = 65536 + ((code & 1023) << 10 | message.charCodeAt(++index) & 1023);
                blocks2[i2 >>> 2] |= (240 | code >>> 18) << SHIFT[i2++ & 3];
                blocks2[i2 >>> 2] |= (128 | code >>> 12 & 63) << SHIFT[i2++ & 3];
                blocks2[i2 >>> 2] |= (128 | code >>> 6 & 63) << SHIFT[i2++ & 3];
                blocks2[i2 >>> 2] |= (128 | code & 63) << SHIFT[i2++ & 3];
              }
            }
          }
          this.lastByteIndex = i2;
          this.bytes += i2 - this.start;
          if (i2 >= 64) {
            this.block = blocks2[16];
            this.start = i2 - 64;
            this.hash();
            this.hashed = true;
          } else {
            this.start = i2;
          }
        }
        if (this.bytes > 4294967295) {
          this.hBytes += this.bytes / 4294967296 << 0;
          this.bytes = this.bytes % 4294967296;
        }
        return this;
      };
      Sha256.prototype.finalize = function() {
        if (this.finalized) {
          return;
        }
        this.finalized = true;
        var blocks2 = this.blocks, i2 = this.lastByteIndex;
        blocks2[16] = this.block;
        blocks2[i2 >>> 2] |= EXTRA[i2 & 3];
        this.block = blocks2[16];
        if (i2 >= 56) {
          if (!this.hashed) {
            this.hash();
          }
          blocks2[0] = this.block;
          blocks2[16] = blocks2[1] = blocks2[2] = blocks2[3] = blocks2[4] = blocks2[5] = blocks2[6] = blocks2[7] = blocks2[8] = blocks2[9] = blocks2[10] = blocks2[11] = blocks2[12] = blocks2[13] = blocks2[14] = blocks2[15] = 0;
        }
        blocks2[14] = this.hBytes << 3 | this.bytes >>> 29;
        blocks2[15] = this.bytes << 3;
        this.hash();
      };
      Sha256.prototype.hash = function() {
        var a3 = this.h0, b = this.h1, c3 = this.h2, d2 = this.h3, e2 = this.h4, f2 = this.h5, g = this.h6, h2 = this.h7, blocks2 = this.blocks, j2, s0, s1, maj, t1, t2, ch, ab, da, cd, bc;
        for (j2 = 16; j2 < 64; ++j2) {
          t1 = blocks2[j2 - 15];
          s0 = (t1 >>> 7 | t1 << 25) ^ (t1 >>> 18 | t1 << 14) ^ t1 >>> 3;
          t1 = blocks2[j2 - 2];
          s1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10;
          blocks2[j2] = blocks2[j2 - 16] + s0 + blocks2[j2 - 7] + s1 << 0;
        }
        bc = b & c3;
        for (j2 = 0; j2 < 64; j2 += 4) {
          if (this.first) {
            if (this.is224) {
              ab = 300032;
              t1 = blocks2[0] - 1413257819;
              h2 = t1 - 150054599 << 0;
              d2 = t1 + 24177077 << 0;
            } else {
              ab = 704751109;
              t1 = blocks2[0] - 210244248;
              h2 = t1 - 1521486534 << 0;
              d2 = t1 + 143694565 << 0;
            }
            this.first = false;
          } else {
            s0 = (a3 >>> 2 | a3 << 30) ^ (a3 >>> 13 | a3 << 19) ^ (a3 >>> 22 | a3 << 10);
            s1 = (e2 >>> 6 | e2 << 26) ^ (e2 >>> 11 | e2 << 21) ^ (e2 >>> 25 | e2 << 7);
            ab = a3 & b;
            maj = ab ^ a3 & c3 ^ bc;
            ch = e2 & f2 ^ ~e2 & g;
            t1 = h2 + s1 + ch + K[j2] + blocks2[j2];
            t2 = s0 + maj;
            h2 = d2 + t1 << 0;
            d2 = t1 + t2 << 0;
          }
          s0 = (d2 >>> 2 | d2 << 30) ^ (d2 >>> 13 | d2 << 19) ^ (d2 >>> 22 | d2 << 10);
          s1 = (h2 >>> 6 | h2 << 26) ^ (h2 >>> 11 | h2 << 21) ^ (h2 >>> 25 | h2 << 7);
          da = d2 & a3;
          maj = da ^ d2 & b ^ ab;
          ch = h2 & e2 ^ ~h2 & f2;
          t1 = g + s1 + ch + K[j2 + 1] + blocks2[j2 + 1];
          t2 = s0 + maj;
          g = c3 + t1 << 0;
          c3 = t1 + t2 << 0;
          s0 = (c3 >>> 2 | c3 << 30) ^ (c3 >>> 13 | c3 << 19) ^ (c3 >>> 22 | c3 << 10);
          s1 = (g >>> 6 | g << 26) ^ (g >>> 11 | g << 21) ^ (g >>> 25 | g << 7);
          cd = c3 & d2;
          maj = cd ^ c3 & a3 ^ da;
          ch = g & h2 ^ ~g & e2;
          t1 = f2 + s1 + ch + K[j2 + 2] + blocks2[j2 + 2];
          t2 = s0 + maj;
          f2 = b + t1 << 0;
          b = t1 + t2 << 0;
          s0 = (b >>> 2 | b << 30) ^ (b >>> 13 | b << 19) ^ (b >>> 22 | b << 10);
          s1 = (f2 >>> 6 | f2 << 26) ^ (f2 >>> 11 | f2 << 21) ^ (f2 >>> 25 | f2 << 7);
          bc = b & c3;
          maj = bc ^ b & d2 ^ cd;
          ch = f2 & g ^ ~f2 & h2;
          t1 = e2 + s1 + ch + K[j2 + 3] + blocks2[j2 + 3];
          t2 = s0 + maj;
          e2 = a3 + t1 << 0;
          a3 = t1 + t2 << 0;
          this.chromeBugWorkAround = true;
        }
        this.h0 = this.h0 + a3 << 0;
        this.h1 = this.h1 + b << 0;
        this.h2 = this.h2 + c3 << 0;
        this.h3 = this.h3 + d2 << 0;
        this.h4 = this.h4 + e2 << 0;
        this.h5 = this.h5 + f2 << 0;
        this.h6 = this.h6 + g << 0;
        this.h7 = this.h7 + h2 << 0;
      };
      Sha256.prototype.hex = function() {
        this.finalize();
        var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7;
        var hex = HEX_CHARS[h0 >>> 28 & 15] + HEX_CHARS[h0 >>> 24 & 15] + HEX_CHARS[h0 >>> 20 & 15] + HEX_CHARS[h0 >>> 16 & 15] + HEX_CHARS[h0 >>> 12 & 15] + HEX_CHARS[h0 >>> 8 & 15] + HEX_CHARS[h0 >>> 4 & 15] + HEX_CHARS[h0 & 15] + HEX_CHARS[h1 >>> 28 & 15] + HEX_CHARS[h1 >>> 24 & 15] + HEX_CHARS[h1 >>> 20 & 15] + HEX_CHARS[h1 >>> 16 & 15] + HEX_CHARS[h1 >>> 12 & 15] + HEX_CHARS[h1 >>> 8 & 15] + HEX_CHARS[h1 >>> 4 & 15] + HEX_CHARS[h1 & 15] + HEX_CHARS[h2 >>> 28 & 15] + HEX_CHARS[h2 >>> 24 & 15] + HEX_CHARS[h2 >>> 20 & 15] + HEX_CHARS[h2 >>> 16 & 15] + HEX_CHARS[h2 >>> 12 & 15] + HEX_CHARS[h2 >>> 8 & 15] + HEX_CHARS[h2 >>> 4 & 15] + HEX_CHARS[h2 & 15] + HEX_CHARS[h3 >>> 28 & 15] + HEX_CHARS[h3 >>> 24 & 15] + HEX_CHARS[h3 >>> 20 & 15] + HEX_CHARS[h3 >>> 16 & 15] + HEX_CHARS[h3 >>> 12 & 15] + HEX_CHARS[h3 >>> 8 & 15] + HEX_CHARS[h3 >>> 4 & 15] + HEX_CHARS[h3 & 15] + HEX_CHARS[h4 >>> 28 & 15] + HEX_CHARS[h4 >>> 24 & 15] + HEX_CHARS[h4 >>> 20 & 15] + HEX_CHARS[h4 >>> 16 & 15] + HEX_CHARS[h4 >>> 12 & 15] + HEX_CHARS[h4 >>> 8 & 15] + HEX_CHARS[h4 >>> 4 & 15] + HEX_CHARS[h4 & 15] + HEX_CHARS[h5 >>> 28 & 15] + HEX_CHARS[h5 >>> 24 & 15] + HEX_CHARS[h5 >>> 20 & 15] + HEX_CHARS[h5 >>> 16 & 15] + HEX_CHARS[h5 >>> 12 & 15] + HEX_CHARS[h5 >>> 8 & 15] + HEX_CHARS[h5 >>> 4 & 15] + HEX_CHARS[h5 & 15] + HEX_CHARS[h6 >>> 28 & 15] + HEX_CHARS[h6 >>> 24 & 15] + HEX_CHARS[h6 >>> 20 & 15] + HEX_CHARS[h6 >>> 16 & 15] + HEX_CHARS[h6 >>> 12 & 15] + HEX_CHARS[h6 >>> 8 & 15] + HEX_CHARS[h6 >>> 4 & 15] + HEX_CHARS[h6 & 15];
        if (!this.is224) {
          hex += HEX_CHARS[h7 >>> 28 & 15] + HEX_CHARS[h7 >>> 24 & 15] + HEX_CHARS[h7 >>> 20 & 15] + HEX_CHARS[h7 >>> 16 & 15] + HEX_CHARS[h7 >>> 12 & 15] + HEX_CHARS[h7 >>> 8 & 15] + HEX_CHARS[h7 >>> 4 & 15] + HEX_CHARS[h7 & 15];
        }
        return hex;
      };
      Sha256.prototype.toString = Sha256.prototype.hex;
      Sha256.prototype.digest = function() {
        this.finalize();
        var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7;
        var arr = [
          h0 >>> 24 & 255,
          h0 >>> 16 & 255,
          h0 >>> 8 & 255,
          h0 & 255,
          h1 >>> 24 & 255,
          h1 >>> 16 & 255,
          h1 >>> 8 & 255,
          h1 & 255,
          h2 >>> 24 & 255,
          h2 >>> 16 & 255,
          h2 >>> 8 & 255,
          h2 & 255,
          h3 >>> 24 & 255,
          h3 >>> 16 & 255,
          h3 >>> 8 & 255,
          h3 & 255,
          h4 >>> 24 & 255,
          h4 >>> 16 & 255,
          h4 >>> 8 & 255,
          h4 & 255,
          h5 >>> 24 & 255,
          h5 >>> 16 & 255,
          h5 >>> 8 & 255,
          h5 & 255,
          h6 >>> 24 & 255,
          h6 >>> 16 & 255,
          h6 >>> 8 & 255,
          h6 & 255
        ];
        if (!this.is224) {
          arr.push(h7 >>> 24 & 255, h7 >>> 16 & 255, h7 >>> 8 & 255, h7 & 255);
        }
        return arr;
      };
      Sha256.prototype.array = Sha256.prototype.digest;
      Sha256.prototype.arrayBuffer = function() {
        this.finalize();
        var buffer = new ArrayBuffer(this.is224 ? 28 : 32);
        var dataView = new DataView(buffer);
        dataView.setUint32(0, this.h0);
        dataView.setUint32(4, this.h1);
        dataView.setUint32(8, this.h2);
        dataView.setUint32(12, this.h3);
        dataView.setUint32(16, this.h4);
        dataView.setUint32(20, this.h5);
        dataView.setUint32(24, this.h6);
        if (!this.is224) {
          dataView.setUint32(28, this.h7);
        }
        return buffer;
      };
      function HmacSha256(key, is224, sharedMemory) {
        var i2, type = typeof key;
        if (type === "string") {
          var bytes = [], length = key.length, index = 0, code;
          for (i2 = 0; i2 < length; ++i2) {
            code = key.charCodeAt(i2);
            if (code < 128) {
              bytes[index++] = code;
            } else if (code < 2048) {
              bytes[index++] = 192 | code >>> 6;
              bytes[index++] = 128 | code & 63;
            } else if (code < 55296 || code >= 57344) {
              bytes[index++] = 224 | code >>> 12;
              bytes[index++] = 128 | code >>> 6 & 63;
              bytes[index++] = 128 | code & 63;
            } else {
              code = 65536 + ((code & 1023) << 10 | key.charCodeAt(++i2) & 1023);
              bytes[index++] = 240 | code >>> 18;
              bytes[index++] = 128 | code >>> 12 & 63;
              bytes[index++] = 128 | code >>> 6 & 63;
              bytes[index++] = 128 | code & 63;
            }
          }
          key = bytes;
        } else {
          if (type === "object") {
            if (key === null) {
              throw new Error(ERROR);
            } else if (ARRAY_BUFFER && key.constructor === ArrayBuffer) {
              key = new Uint8Array(key);
            } else if (!Array.isArray(key)) {
              if (!ARRAY_BUFFER || !ArrayBuffer.isView(key)) {
                throw new Error(ERROR);
              }
            }
          } else {
            throw new Error(ERROR);
          }
        }
        if (key.length > 64) {
          key = new Sha256(is224, true).update(key).array();
        }
        var oKeyPad = [], iKeyPad = [];
        for (i2 = 0; i2 < 64; ++i2) {
          var b = key[i2] || 0;
          oKeyPad[i2] = 92 ^ b;
          iKeyPad[i2] = 54 ^ b;
        }
        Sha256.call(this, is224, sharedMemory);
        this.update(iKeyPad);
        this.oKeyPad = oKeyPad;
        this.inner = true;
        this.sharedMemory = sharedMemory;
      }
      HmacSha256.prototype = new Sha256();
      HmacSha256.prototype.finalize = function() {
        Sha256.prototype.finalize.call(this);
        if (this.inner) {
          this.inner = false;
          var innerHash = this.array();
          Sha256.call(this, this.is224, this.sharedMemory);
          this.update(this.oKeyPad);
          this.update(innerHash);
          Sha256.prototype.finalize.call(this);
        }
      };
      var exports2 = createMethod();
      exports2.sha256 = exports2;
      exports2.sha224 = createMethod(true);
      exports2.sha256.hmac = createHmacMethod();
      exports2.sha224.hmac = createHmacMethod(true);
      if (COMMON_JS) {
        module.exports = exports2;
      } else {
        root.sha256 = exports2.sha256;
        root.sha224 = exports2.sha224;
        if (AMD) {
          define(function() {
            return exports2;
          });
        }
      }
    })();
  }
});

// ../../node_modules/.pnpm/consola@3.4.0/node_modules/consola/dist/chunks/prompt.mjs
var prompt_exports = {};
__export(prompt_exports, {
  kCancel: () => kCancel,
  prompt: () => prompt
});
import p, { stdin, stdout } from "node:process";
import f from "node:readline";
import { WriteStream } from "node:tty";
function getDefaultExportFromCjs(x2) {
  return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
}
function requireSrc() {
  if (hasRequiredSrc)
    return src;
  hasRequiredSrc = 1;
  const ESC = "\x1B";
  const CSI = `${ESC}[`;
  const beep = "\x07";
  const cursor = {
    to(x2, y3) {
      if (!y3)
        return `${CSI}${x2 + 1}G`;
      return `${CSI}${y3 + 1};${x2 + 1}H`;
    },
    move(x2, y3) {
      let ret = "";
      if (x2 < 0)
        ret += `${CSI}${-x2}D`;
      else if (x2 > 0)
        ret += `${CSI}${x2}C`;
      if (y3 < 0)
        ret += `${CSI}${-y3}A`;
      else if (y3 > 0)
        ret += `${CSI}${y3}B`;
      return ret;
    },
    up: (count = 1) => `${CSI}${count}A`,
    down: (count = 1) => `${CSI}${count}B`,
    forward: (count = 1) => `${CSI}${count}C`,
    backward: (count = 1) => `${CSI}${count}D`,
    nextLine: (count = 1) => `${CSI}E`.repeat(count),
    prevLine: (count = 1) => `${CSI}F`.repeat(count),
    left: `${CSI}G`,
    hide: `${CSI}?25l`,
    show: `${CSI}?25h`,
    save: `${ESC}7`,
    restore: `${ESC}8`
  };
  const scroll = {
    up: (count = 1) => `${CSI}S`.repeat(count),
    down: (count = 1) => `${CSI}T`.repeat(count)
  };
  const erase = {
    screen: `${CSI}2J`,
    up: (count = 1) => `${CSI}1J`.repeat(count),
    down: (count = 1) => `${CSI}J`.repeat(count),
    line: `${CSI}2K`,
    lineEnd: `${CSI}K`,
    lineStart: `${CSI}1K`,
    lines(count) {
      let clear = "";
      for (let i2 = 0; i2 < count; i2++)
        clear += this.line + (i2 < count - 1 ? cursor.up() : "");
      if (count)
        clear += cursor.left;
      return clear;
    }
  };
  src = { cursor, scroll, erase, beep };
  return src;
}
function requirePicocolors() {
  if (hasRequiredPicocolors)
    return picocolors.exports;
  hasRequiredPicocolors = 1;
  let p3 = process || {}, argv2 = p3.argv || [], env2 = p3.env || {};
  let isColorSupported2 = !(!!env2.NO_COLOR || argv2.includes("--no-color")) && (!!env2.FORCE_COLOR || argv2.includes("--color") || p3.platform === "win32" || (p3.stdout || {}).isTTY && env2.TERM !== "dumb" || !!env2.CI);
  let formatter = (open, close, replace = open) => (input) => {
    let string = "" + input, index = string.indexOf(close, open.length);
    return ~index ? open + replaceClose2(string, close, replace, index) + close : open + string + close;
  };
  let replaceClose2 = (string, close, replace, index) => {
    let result = "", cursor = 0;
    do {
      result += string.substring(cursor, index) + replace;
      cursor = index + close.length;
      index = string.indexOf(close, cursor);
    } while (~index);
    return result + string.substring(cursor);
  };
  let createColors2 = (enabled = isColorSupported2) => {
    let f2 = enabled ? formatter : () => String;
    return {
      isColorSupported: enabled,
      reset: f2("\x1B[0m", "\x1B[0m"),
      bold: f2("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
      dim: f2("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
      italic: f2("\x1B[3m", "\x1B[23m"),
      underline: f2("\x1B[4m", "\x1B[24m"),
      inverse: f2("\x1B[7m", "\x1B[27m"),
      hidden: f2("\x1B[8m", "\x1B[28m"),
      strikethrough: f2("\x1B[9m", "\x1B[29m"),
      black: f2("\x1B[30m", "\x1B[39m"),
      red: f2("\x1B[31m", "\x1B[39m"),
      green: f2("\x1B[32m", "\x1B[39m"),
      yellow: f2("\x1B[33m", "\x1B[39m"),
      blue: f2("\x1B[34m", "\x1B[39m"),
      magenta: f2("\x1B[35m", "\x1B[39m"),
      cyan: f2("\x1B[36m", "\x1B[39m"),
      white: f2("\x1B[37m", "\x1B[39m"),
      gray: f2("\x1B[90m", "\x1B[39m"),
      bgBlack: f2("\x1B[40m", "\x1B[49m"),
      bgRed: f2("\x1B[41m", "\x1B[49m"),
      bgGreen: f2("\x1B[42m", "\x1B[49m"),
      bgYellow: f2("\x1B[43m", "\x1B[49m"),
      bgBlue: f2("\x1B[44m", "\x1B[49m"),
      bgMagenta: f2("\x1B[45m", "\x1B[49m"),
      bgCyan: f2("\x1B[46m", "\x1B[49m"),
      bgWhite: f2("\x1B[47m", "\x1B[49m"),
      blackBright: f2("\x1B[90m", "\x1B[39m"),
      redBright: f2("\x1B[91m", "\x1B[39m"),
      greenBright: f2("\x1B[92m", "\x1B[39m"),
      yellowBright: f2("\x1B[93m", "\x1B[39m"),
      blueBright: f2("\x1B[94m", "\x1B[39m"),
      magentaBright: f2("\x1B[95m", "\x1B[39m"),
      cyanBright: f2("\x1B[96m", "\x1B[39m"),
      whiteBright: f2("\x1B[97m", "\x1B[39m"),
      bgBlackBright: f2("\x1B[100m", "\x1B[49m"),
      bgRedBright: f2("\x1B[101m", "\x1B[49m"),
      bgGreenBright: f2("\x1B[102m", "\x1B[49m"),
      bgYellowBright: f2("\x1B[103m", "\x1B[49m"),
      bgBlueBright: f2("\x1B[104m", "\x1B[49m"),
      bgMagentaBright: f2("\x1B[105m", "\x1B[49m"),
      bgCyanBright: f2("\x1B[106m", "\x1B[49m"),
      bgWhiteBright: f2("\x1B[107m", "\x1B[49m")
    };
  };
  picocolors.exports = createColors2();
  picocolors.exports.createColors = createColors2;
  return picocolors.exports;
}
function J({ onlyFirst: t2 = false } = {}) {
  const F2 = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");
  return new RegExp(F2, t2 ? void 0 : "g");
}
function T(t2) {
  if (typeof t2 != "string")
    throw new TypeError(`Expected a \`string\`, got \`${typeof t2}\``);
  return t2.replace(Q, "");
}
function O(t2) {
  return t2 && t2.__esModule && Object.prototype.hasOwnProperty.call(t2, "default") ? t2.default : t2;
}
function A$1(t2, u3 = {}) {
  if (typeof t2 != "string" || t2.length === 0 || (u3 = { ambiguousIsNarrow: true, ...u3 }, t2 = T(t2), t2.length === 0))
    return 0;
  t2 = t2.replace(FD(), "  ");
  const F2 = u3.ambiguousIsNarrow ? 1 : 2;
  let e2 = 0;
  for (const s2 of t2) {
    const i2 = s2.codePointAt(0);
    if (i2 <= 31 || i2 >= 127 && i2 <= 159 || i2 >= 768 && i2 <= 879)
      continue;
    switch (DD.eastAsianWidth(s2)) {
      case "F":
      case "W":
        e2 += 2;
        break;
      case "A":
        e2 += F2;
        break;
      default:
        e2 += 1;
    }
  }
  return e2;
}
function sD() {
  const t2 = /* @__PURE__ */ new Map();
  for (const [u3, F2] of Object.entries(r)) {
    for (const [e2, s2] of Object.entries(F2))
      r[e2] = { open: `\x1B[${s2[0]}m`, close: `\x1B[${s2[1]}m` }, F2[e2] = r[e2], t2.set(s2[0], s2[1]);
    Object.defineProperty(r, u3, { value: F2, enumerable: false });
  }
  return Object.defineProperty(r, "codes", { value: t2, enumerable: false }), r.color.close = "\x1B[39m", r.bgColor.close = "\x1B[49m", r.color.ansi = L(), r.color.ansi256 = N(), r.color.ansi16m = I(), r.bgColor.ansi = L(m$1), r.bgColor.ansi256 = N(m$1), r.bgColor.ansi16m = I(m$1), Object.defineProperties(r, { rgbToAnsi256: { value: (u3, F2, e2) => u3 === F2 && F2 === e2 ? u3 < 8 ? 16 : u3 > 248 ? 231 : Math.round((u3 - 8) / 247 * 24) + 232 : 16 + 36 * Math.round(u3 / 255 * 5) + 6 * Math.round(F2 / 255 * 5) + Math.round(e2 / 255 * 5), enumerable: false }, hexToRgb: { value: (u3) => {
    const F2 = /[a-f\d]{6}|[a-f\d]{3}/i.exec(u3.toString(16));
    if (!F2)
      return [0, 0, 0];
    let [e2] = F2;
    e2.length === 3 && (e2 = [...e2].map((i2) => i2 + i2).join(""));
    const s2 = Number.parseInt(e2, 16);
    return [s2 >> 16 & 255, s2 >> 8 & 255, s2 & 255];
  }, enumerable: false }, hexToAnsi256: { value: (u3) => r.rgbToAnsi256(...r.hexToRgb(u3)), enumerable: false }, ansi256ToAnsi: { value: (u3) => {
    if (u3 < 8)
      return 30 + u3;
    if (u3 < 16)
      return 90 + (u3 - 8);
    let F2, e2, s2;
    if (u3 >= 232)
      F2 = ((u3 - 232) * 10 + 8) / 255, e2 = F2, s2 = F2;
    else {
      u3 -= 16;
      const C2 = u3 % 36;
      F2 = Math.floor(u3 / 36) / 5, e2 = Math.floor(C2 / 6) / 5, s2 = C2 % 6 / 5;
    }
    const i2 = Math.max(F2, e2, s2) * 2;
    if (i2 === 0)
      return 30;
    let D2 = 30 + (Math.round(s2) << 2 | Math.round(e2) << 1 | Math.round(F2));
    return i2 === 2 && (D2 += 60), D2;
  }, enumerable: false }, rgbToAnsi: { value: (u3, F2, e2) => r.ansi256ToAnsi(r.rgbToAnsi256(u3, F2, e2)), enumerable: false }, hexToAnsi: { value: (u3) => r.ansi256ToAnsi(r.hexToAnsi256(u3)), enumerable: false } }), r;
}
function G$1(t2, u3, F2) {
  return String(t2).normalize().replace(/\r\n/g, `
`).split(`
`).map((e2) => oD(e2, u3, F2)).join(`
`);
}
function k$1(t2, u3) {
  if (typeof t2 == "string")
    return c.aliases.get(t2) === u3;
  for (const F2 of t2)
    if (F2 !== void 0 && k$1(F2, u3))
      return true;
  return false;
}
function lD(t2, u3) {
  if (t2 === u3)
    return;
  const F2 = t2.split(`
`), e2 = u3.split(`
`), s2 = [];
  for (let i2 = 0; i2 < Math.max(F2.length, e2.length); i2++)
    F2[i2] !== e2[i2] && s2.push(i2);
  return s2;
}
function d(t2, u3) {
  const F2 = t2;
  F2.isTTY && F2.setRawMode(u3);
}
function X() {
  return p.platform !== "win32" ? p.env.TERM !== "linux" : !!p.env.CI || !!p.env.WT_SESSION || !!p.env.TERMINUS_SUBLIME || p.env.ConEmuTask === "{cmd::Cmder}" || p.env.TERM_PROGRAM === "Terminus-Sublime" || p.env.TERM_PROGRAM === "vscode" || p.env.TERM === "xterm-256color" || p.env.TERM === "alacritty" || p.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
}
async function prompt(message, opts = {}) {
  const handleCancel = (value) => {
    if (typeof value !== "symbol" || value.toString() !== "Symbol(clack:cancel)") {
      return value;
    }
    switch (opts.cancel) {
      case "reject": {
        const error = new Error("Prompt cancelled.");
        error.name = "ConsolaPromptCancelledError";
        if (Error.captureStackTrace) {
          Error.captureStackTrace(error, prompt);
        }
        throw error;
      }
      case "undefined": {
        return void 0;
      }
      case "null": {
        return null;
      }
      case "symbol": {
        return kCancel;
      }
      default:
      case "default": {
        return opts.default ?? opts.initial;
      }
    }
  };
  if (!opts.type || opts.type === "text") {
    return await ue({
      message,
      defaultValue: opts.default,
      placeholder: opts.placeholder,
      initialValue: opts.initial
    }).then(handleCancel);
  }
  if (opts.type === "confirm") {
    return await me({
      message,
      initialValue: opts.initial
    }).then(handleCancel);
  }
  if (opts.type === "select") {
    return await de({
      message,
      options: opts.options.map(
        (o) => typeof o === "string" ? { value: o, label: o } : o
      ),
      initialValue: opts.initial
    }).then(handleCancel);
  }
  if (opts.type === "multiselect") {
    return await pe({
      message,
      options: opts.options.map(
        (o) => typeof o === "string" ? { value: o, label: o } : o
      ),
      required: opts.required,
      initialValues: opts.initial
    }).then(handleCancel);
  }
  throw new Error(`Unknown prompt type: ${opts.type}`);
}
var src, hasRequiredSrc, srcExports, picocolors, hasRequiredPicocolors, picocolorsExports, e, Q, P, X$1, DD, uD, FD, m$1, L, N, I, r, tD, eD, iD, v2, CD, w, W, rD, R$1, y$1, V$1, z, ED, _, nD, oD, aD, c, S$1, AD, pD, h, x, fD, bD, mD, Y, wD, SD, $D, q, jD, PD, E, u, ee, A, B, S, a, m, j, R, V, M, G, y, k, ue, me, de, pe, kCancel;
var init_prompt = __esm({
  "../../node_modules/.pnpm/consola@3.4.0/node_modules/consola/dist/chunks/prompt.mjs"() {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    srcExports = requireSrc();
    picocolors = { exports: {} };
    picocolorsExports = /* @__PURE__ */ requirePicocolors();
    e = /* @__PURE__ */ getDefaultExportFromCjs(picocolorsExports);
    Q = J();
    P = { exports: {} };
    (function(t2) {
      var u3 = {};
      t2.exports = u3, u3.eastAsianWidth = function(e2) {
        var s2 = e2.charCodeAt(0), i2 = e2.length == 2 ? e2.charCodeAt(1) : 0, D2 = s2;
        return 55296 <= s2 && s2 <= 56319 && 56320 <= i2 && i2 <= 57343 && (s2 &= 1023, i2 &= 1023, D2 = s2 << 10 | i2, D2 += 65536), D2 == 12288 || 65281 <= D2 && D2 <= 65376 || 65504 <= D2 && D2 <= 65510 ? "F" : D2 == 8361 || 65377 <= D2 && D2 <= 65470 || 65474 <= D2 && D2 <= 65479 || 65482 <= D2 && D2 <= 65487 || 65490 <= D2 && D2 <= 65495 || 65498 <= D2 && D2 <= 65500 || 65512 <= D2 && D2 <= 65518 ? "H" : 4352 <= D2 && D2 <= 4447 || 4515 <= D2 && D2 <= 4519 || 4602 <= D2 && D2 <= 4607 || 9001 <= D2 && D2 <= 9002 || 11904 <= D2 && D2 <= 11929 || 11931 <= D2 && D2 <= 12019 || 12032 <= D2 && D2 <= 12245 || 12272 <= D2 && D2 <= 12283 || 12289 <= D2 && D2 <= 12350 || 12353 <= D2 && D2 <= 12438 || 12441 <= D2 && D2 <= 12543 || 12549 <= D2 && D2 <= 12589 || 12593 <= D2 && D2 <= 12686 || 12688 <= D2 && D2 <= 12730 || 12736 <= D2 && D2 <= 12771 || 12784 <= D2 && D2 <= 12830 || 12832 <= D2 && D2 <= 12871 || 12880 <= D2 && D2 <= 13054 || 13056 <= D2 && D2 <= 19903 || 19968 <= D2 && D2 <= 42124 || 42128 <= D2 && D2 <= 42182 || 43360 <= D2 && D2 <= 43388 || 44032 <= D2 && D2 <= 55203 || 55216 <= D2 && D2 <= 55238 || 55243 <= D2 && D2 <= 55291 || 63744 <= D2 && D2 <= 64255 || 65040 <= D2 && D2 <= 65049 || 65072 <= D2 && D2 <= 65106 || 65108 <= D2 && D2 <= 65126 || 65128 <= D2 && D2 <= 65131 || 110592 <= D2 && D2 <= 110593 || 127488 <= D2 && D2 <= 127490 || 127504 <= D2 && D2 <= 127546 || 127552 <= D2 && D2 <= 127560 || 127568 <= D2 && D2 <= 127569 || 131072 <= D2 && D2 <= 194367 || 177984 <= D2 && D2 <= 196605 || 196608 <= D2 && D2 <= 262141 ? "W" : 32 <= D2 && D2 <= 126 || 162 <= D2 && D2 <= 163 || 165 <= D2 && D2 <= 166 || D2 == 172 || D2 == 175 || 10214 <= D2 && D2 <= 10221 || 10629 <= D2 && D2 <= 10630 ? "Na" : D2 == 161 || D2 == 164 || 167 <= D2 && D2 <= 168 || D2 == 170 || 173 <= D2 && D2 <= 174 || 176 <= D2 && D2 <= 180 || 182 <= D2 && D2 <= 186 || 188 <= D2 && D2 <= 191 || D2 == 198 || D2 == 208 || 215 <= D2 && D2 <= 216 || 222 <= D2 && D2 <= 225 || D2 == 230 || 232 <= D2 && D2 <= 234 || 236 <= D2 && D2 <= 237 || D2 == 240 || 242 <= D2 && D2 <= 243 || 247 <= D2 && D2 <= 250 || D2 == 252 || D2 == 254 || D2 == 257 || D2 == 273 || D2 == 275 || D2 == 283 || 294 <= D2 && D2 <= 295 || D2 == 299 || 305 <= D2 && D2 <= 307 || D2 == 312 || 319 <= D2 && D2 <= 322 || D2 == 324 || 328 <= D2 && D2 <= 331 || D2 == 333 || 338 <= D2 && D2 <= 339 || 358 <= D2 && D2 <= 359 || D2 == 363 || D2 == 462 || D2 == 464 || D2 == 466 || D2 == 468 || D2 == 470 || D2 == 472 || D2 == 474 || D2 == 476 || D2 == 593 || D2 == 609 || D2 == 708 || D2 == 711 || 713 <= D2 && D2 <= 715 || D2 == 717 || D2 == 720 || 728 <= D2 && D2 <= 731 || D2 == 733 || D2 == 735 || 768 <= D2 && D2 <= 879 || 913 <= D2 && D2 <= 929 || 931 <= D2 && D2 <= 937 || 945 <= D2 && D2 <= 961 || 963 <= D2 && D2 <= 969 || D2 == 1025 || 1040 <= D2 && D2 <= 1103 || D2 == 1105 || D2 == 8208 || 8211 <= D2 && D2 <= 8214 || 8216 <= D2 && D2 <= 8217 || 8220 <= D2 && D2 <= 8221 || 8224 <= D2 && D2 <= 8226 || 8228 <= D2 && D2 <= 8231 || D2 == 8240 || 8242 <= D2 && D2 <= 8243 || D2 == 8245 || D2 == 8251 || D2 == 8254 || D2 == 8308 || D2 == 8319 || 8321 <= D2 && D2 <= 8324 || D2 == 8364 || D2 == 8451 || D2 == 8453 || D2 == 8457 || D2 == 8467 || D2 == 8470 || 8481 <= D2 && D2 <= 8482 || D2 == 8486 || D2 == 8491 || 8531 <= D2 && D2 <= 8532 || 8539 <= D2 && D2 <= 8542 || 8544 <= D2 && D2 <= 8555 || 8560 <= D2 && D2 <= 8569 || D2 == 8585 || 8592 <= D2 && D2 <= 8601 || 8632 <= D2 && D2 <= 8633 || D2 == 8658 || D2 == 8660 || D2 == 8679 || D2 == 8704 || 8706 <= D2 && D2 <= 8707 || 8711 <= D2 && D2 <= 8712 || D2 == 8715 || D2 == 8719 || D2 == 8721 || D2 == 8725 || D2 == 8730 || 8733 <= D2 && D2 <= 8736 || D2 == 8739 || D2 == 8741 || 8743 <= D2 && D2 <= 8748 || D2 == 8750 || 8756 <= D2 && D2 <= 8759 || 8764 <= D2 && D2 <= 8765 || D2 == 8776 || D2 == 8780 || D2 == 8786 || 8800 <= D2 && D2 <= 8801 || 8804 <= D2 && D2 <= 8807 || 8810 <= D2 && D2 <= 8811 || 8814 <= D2 && D2 <= 8815 || 8834 <= D2 && D2 <= 8835 || 8838 <= D2 && D2 <= 8839 || D2 == 8853 || D2 == 8857 || D2 == 8869 || D2 == 8895 || D2 == 8978 || 9312 <= D2 && D2 <= 9449 || 9451 <= D2 && D2 <= 9547 || 9552 <= D2 && D2 <= 9587 || 9600 <= D2 && D2 <= 9615 || 9618 <= D2 && D2 <= 9621 || 9632 <= D2 && D2 <= 9633 || 9635 <= D2 && D2 <= 9641 || 9650 <= D2 && D2 <= 9651 || 9654 <= D2 && D2 <= 9655 || 9660 <= D2 && D2 <= 9661 || 9664 <= D2 && D2 <= 9665 || 9670 <= D2 && D2 <= 9672 || D2 == 9675 || 9678 <= D2 && D2 <= 9681 || 9698 <= D2 && D2 <= 9701 || D2 == 9711 || 9733 <= D2 && D2 <= 9734 || D2 == 9737 || 9742 <= D2 && D2 <= 9743 || 9748 <= D2 && D2 <= 9749 || D2 == 9756 || D2 == 9758 || D2 == 9792 || D2 == 9794 || 9824 <= D2 && D2 <= 9825 || 9827 <= D2 && D2 <= 9829 || 9831 <= D2 && D2 <= 9834 || 9836 <= D2 && D2 <= 9837 || D2 == 9839 || 9886 <= D2 && D2 <= 9887 || 9918 <= D2 && D2 <= 9919 || 9924 <= D2 && D2 <= 9933 || 9935 <= D2 && D2 <= 9953 || D2 == 9955 || 9960 <= D2 && D2 <= 9983 || D2 == 10045 || D2 == 10071 || 10102 <= D2 && D2 <= 10111 || 11093 <= D2 && D2 <= 11097 || 12872 <= D2 && D2 <= 12879 || 57344 <= D2 && D2 <= 63743 || 65024 <= D2 && D2 <= 65039 || D2 == 65533 || 127232 <= D2 && D2 <= 127242 || 127248 <= D2 && D2 <= 127277 || 127280 <= D2 && D2 <= 127337 || 127344 <= D2 && D2 <= 127386 || 917760 <= D2 && D2 <= 917999 || 983040 <= D2 && D2 <= 1048573 || 1048576 <= D2 && D2 <= 1114109 ? "A" : "N";
      }, u3.characterLength = function(e2) {
        var s2 = this.eastAsianWidth(e2);
        return s2 == "F" || s2 == "W" || s2 == "A" ? 2 : 1;
      };
      function F2(e2) {
        return e2.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g) || [];
      }
      u3.length = function(e2) {
        for (var s2 = F2(e2), i2 = 0, D2 = 0; D2 < s2.length; D2++)
          i2 = i2 + this.characterLength(s2[D2]);
        return i2;
      }, u3.slice = function(e2, s2, i2) {
        textLen = u3.length(e2), s2 = s2 || 0, i2 = i2 || 1, s2 < 0 && (s2 = textLen + s2), i2 < 0 && (i2 = textLen + i2);
        for (var D2 = "", C2 = 0, o = F2(e2), E2 = 0; E2 < o.length; E2++) {
          var a3 = o[E2], n2 = u3.length(a3);
          if (C2 >= s2 - (n2 == 2 ? 1 : 0))
            if (C2 + n2 <= i2)
              D2 += a3;
            else
              break;
          C2 += n2;
        }
        return D2;
      };
    })(P);
    X$1 = P.exports;
    DD = O(X$1);
    uD = function() {
      return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
    };
    FD = O(uD);
    m$1 = 10;
    L = (t2 = 0) => (u3) => `\x1B[${u3 + t2}m`;
    N = (t2 = 0) => (u3) => `\x1B[${38 + t2};5;${u3}m`;
    I = (t2 = 0) => (u3, F2, e2) => `\x1B[${38 + t2};2;${u3};${F2};${e2}m`;
    r = { modifier: { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], blackBright: [90, 39], gray: [90, 39], grey: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgGray: [100, 49], bgGrey: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } };
    Object.keys(r.modifier);
    tD = Object.keys(r.color);
    eD = Object.keys(r.bgColor);
    [...tD, ...eD];
    iD = sD();
    v2 = /* @__PURE__ */ new Set(["\x1B", "\x9B"]);
    CD = 39;
    w = "\x07";
    W = "[";
    rD = "]";
    R$1 = "m";
    y$1 = `${rD}8;;`;
    V$1 = (t2) => `${v2.values().next().value}${W}${t2}${R$1}`;
    z = (t2) => `${v2.values().next().value}${y$1}${t2}${w}`;
    ED = (t2) => t2.split(" ").map((u3) => A$1(u3));
    _ = (t2, u3, F2) => {
      const e2 = [...u3];
      let s2 = false, i2 = false, D2 = A$1(T(t2[t2.length - 1]));
      for (const [C2, o] of e2.entries()) {
        const E2 = A$1(o);
        if (D2 + E2 <= F2 ? t2[t2.length - 1] += o : (t2.push(o), D2 = 0), v2.has(o) && (s2 = true, i2 = e2.slice(C2 + 1).join("").startsWith(y$1)), s2) {
          i2 ? o === w && (s2 = false, i2 = false) : o === R$1 && (s2 = false);
          continue;
        }
        D2 += E2, D2 === F2 && C2 < e2.length - 1 && (t2.push(""), D2 = 0);
      }
      !D2 && t2[t2.length - 1].length > 0 && t2.length > 1 && (t2[t2.length - 2] += t2.pop());
    };
    nD = (t2) => {
      const u3 = t2.split(" ");
      let F2 = u3.length;
      for (; F2 > 0 && !(A$1(u3[F2 - 1]) > 0); )
        F2--;
      return F2 === u3.length ? t2 : u3.slice(0, F2).join(" ") + u3.slice(F2).join("");
    };
    oD = (t2, u3, F2 = {}) => {
      if (F2.trim !== false && t2.trim() === "")
        return "";
      let e2 = "", s2, i2;
      const D2 = ED(t2);
      let C2 = [""];
      for (const [E2, a3] of t2.split(" ").entries()) {
        F2.trim !== false && (C2[C2.length - 1] = C2[C2.length - 1].trimStart());
        let n2 = A$1(C2[C2.length - 1]);
        if (E2 !== 0 && (n2 >= u3 && (F2.wordWrap === false || F2.trim === false) && (C2.push(""), n2 = 0), (n2 > 0 || F2.trim === false) && (C2[C2.length - 1] += " ", n2++)), F2.hard && D2[E2] > u3) {
          const B3 = u3 - n2, p3 = 1 + Math.floor((D2[E2] - B3 - 1) / u3);
          Math.floor((D2[E2] - 1) / u3) < p3 && C2.push(""), _(C2, a3, u3);
          continue;
        }
        if (n2 + D2[E2] > u3 && n2 > 0 && D2[E2] > 0) {
          if (F2.wordWrap === false && n2 < u3) {
            _(C2, a3, u3);
            continue;
          }
          C2.push("");
        }
        if (n2 + D2[E2] > u3 && F2.wordWrap === false) {
          _(C2, a3, u3);
          continue;
        }
        C2[C2.length - 1] += a3;
      }
      F2.trim !== false && (C2 = C2.map((E2) => nD(E2)));
      const o = [...C2.join(`
`)];
      for (const [E2, a3] of o.entries()) {
        if (e2 += a3, v2.has(a3)) {
          const { groups: B3 } = new RegExp(`(?:\\${W}(?<code>\\d+)m|\\${y$1}(?<uri>.*)${w})`).exec(o.slice(E2).join("")) || { groups: {} };
          if (B3.code !== void 0) {
            const p3 = Number.parseFloat(B3.code);
            s2 = p3 === CD ? void 0 : p3;
          } else
            B3.uri !== void 0 && (i2 = B3.uri.length === 0 ? void 0 : B3.uri);
        }
        const n2 = iD.codes.get(Number(s2));
        o[E2 + 1] === `
` ? (i2 && (e2 += z("")), s2 && n2 && (e2 += V$1(n2))) : a3 === `
` && (s2 && n2 && (e2 += V$1(s2)), i2 && (e2 += z(i2)));
      }
      return e2;
    };
    aD = ["up", "down", "left", "right", "space", "enter", "cancel"];
    c = { actions: new Set(aD), aliases: /* @__PURE__ */ new Map([["k", "up"], ["j", "down"], ["h", "left"], ["l", "right"], ["", "cancel"], ["escape", "cancel"]]) };
    globalThis.process.platform.startsWith("win");
    S$1 = Symbol("clack:cancel");
    AD = Object.defineProperty;
    pD = (t2, u3, F2) => u3 in t2 ? AD(t2, u3, { enumerable: true, configurable: true, writable: true, value: F2 }) : t2[u3] = F2;
    h = (t2, u3, F2) => (pD(t2, typeof u3 != "symbol" ? u3 + "" : u3, F2), F2);
    x = class {
      constructor(u3, F2 = true) {
        h(this, "input"), h(this, "output"), h(this, "_abortSignal"), h(this, "rl"), h(this, "opts"), h(this, "_render"), h(this, "_track", false), h(this, "_prevFrame", ""), h(this, "_subscribers", /* @__PURE__ */ new Map()), h(this, "_cursor", 0), h(this, "state", "initial"), h(this, "error", ""), h(this, "value");
        const { input: e2 = stdin, output: s2 = stdout, render: i2, signal: D2, ...C2 } = u3;
        this.opts = C2, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = i2.bind(this), this._track = F2, this._abortSignal = D2, this.input = e2, this.output = s2;
      }
      unsubscribe() {
        this._subscribers.clear();
      }
      setSubscriber(u3, F2) {
        const e2 = this._subscribers.get(u3) ?? [];
        e2.push(F2), this._subscribers.set(u3, e2);
      }
      on(u3, F2) {
        this.setSubscriber(u3, { cb: F2 });
      }
      once(u3, F2) {
        this.setSubscriber(u3, { cb: F2, once: true });
      }
      emit(u3, ...F2) {
        const e2 = this._subscribers.get(u3) ?? [], s2 = [];
        for (const i2 of e2)
          i2.cb(...F2), i2.once && s2.push(() => e2.splice(e2.indexOf(i2), 1));
        for (const i2 of s2)
          i2();
      }
      prompt() {
        return new Promise((u3, F2) => {
          if (this._abortSignal) {
            if (this._abortSignal.aborted)
              return this.state = "cancel", this.close(), u3(S$1);
            this._abortSignal.addEventListener("abort", () => {
              this.state = "cancel", this.close();
            }, { once: true });
          }
          const e2 = new WriteStream(0);
          e2._write = (s2, i2, D2) => {
            var _a8, _b5;
            this._track && (this.value = (_a8 = this.rl) == null ? void 0 : _a8.line.replace(/\t/g, ""), this._cursor = ((_b5 = this.rl) == null ? void 0 : _b5.cursor) ?? 0, this.emit("value", this.value)), D2();
          }, this.input.pipe(e2), this.rl = f.createInterface({ input: this.input, output: e2, tabSize: 2, prompt: "", escapeCodeTimeout: 50 }), f.emitKeypressEvents(this.input, this.rl), this.rl.prompt(), this.opts.initialValue !== void 0 && this._track && this.rl.write(this.opts.initialValue), this.input.on("keypress", this.onKeypress), d(this.input, true), this.output.on("resize", this.render), this.render(), this.once("submit", () => {
            this.output.write(srcExports.cursor.show), this.output.off("resize", this.render), d(this.input, false), u3(this.value);
          }), this.once("cancel", () => {
            this.output.write(srcExports.cursor.show), this.output.off("resize", this.render), d(this.input, false), u3(S$1);
          });
        });
      }
      onKeypress(u3, F2) {
        var _a8, _b5;
        if (this.state === "error" && (this.state = "active"), (F2 == null ? void 0 : F2.name) && (!this._track && c.aliases.has(F2.name) && this.emit("cursor", c.aliases.get(F2.name)), c.actions.has(F2.name) && this.emit("cursor", F2.name)), u3 && (u3.toLowerCase() === "y" || u3.toLowerCase() === "n") && this.emit("confirm", u3.toLowerCase() === "y"), u3 === "	" && this.opts.placeholder && (this.value || ((_a8 = this.rl) == null ? void 0 : _a8.write(this.opts.placeholder), this.emit("value", this.opts.placeholder))), u3 && this.emit("key", u3.toLowerCase()), (F2 == null ? void 0 : F2.name) === "return") {
          if (this.opts.validate) {
            const e2 = this.opts.validate(this.value);
            e2 && (this.error = e2 instanceof Error ? e2.message : e2, this.state = "error", (_b5 = this.rl) == null ? void 0 : _b5.write(this.value));
          }
          this.state !== "error" && (this.state = "submit");
        }
        k$1([u3, F2 == null ? void 0 : F2.name, F2 == null ? void 0 : F2.sequence], "cancel") && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
      }
      close() {
        var _a8;
        this.input.unpipe(), this.input.removeListener("keypress", this.onKeypress), this.output.write(`
`), d(this.input, false), (_a8 = this.rl) == null ? void 0 : _a8.close(), this.rl = void 0, this.emit(`${this.state}`, this.value), this.unsubscribe();
      }
      restoreCursor() {
        const u3 = G$1(this._prevFrame, process.stdout.columns, { hard: true }).split(`
`).length - 1;
        this.output.write(srcExports.cursor.move(-999, u3 * -1));
      }
      render() {
        const u3 = G$1(this._render(this) ?? "", process.stdout.columns, { hard: true });
        if (u3 !== this._prevFrame) {
          if (this.state === "initial")
            this.output.write(srcExports.cursor.hide);
          else {
            const F2 = lD(this._prevFrame, u3);
            if (this.restoreCursor(), F2 && (F2 == null ? void 0 : F2.length) === 1) {
              const e2 = F2[0];
              this.output.write(srcExports.cursor.move(0, e2)), this.output.write(srcExports.erase.lines(1));
              const s2 = u3.split(`
`);
              this.output.write(s2[e2]), this._prevFrame = u3, this.output.write(srcExports.cursor.move(0, s2.length - e2 - 1));
              return;
            }
            if (F2 && (F2 == null ? void 0 : F2.length) > 1) {
              const e2 = F2[0];
              this.output.write(srcExports.cursor.move(0, e2)), this.output.write(srcExports.erase.down());
              const s2 = u3.split(`
`).slice(e2);
              this.output.write(s2.join(`
`)), this._prevFrame = u3;
              return;
            }
            this.output.write(srcExports.erase.down());
          }
          this.output.write(u3), this.state === "initial" && (this.state = "active"), this._prevFrame = u3;
        }
      }
    };
    fD = class extends x {
      get cursor() {
        return this.value ? 0 : 1;
      }
      get _value() {
        return this.cursor === 0;
      }
      constructor(u3) {
        super(u3, false), this.value = !!u3.initialValue, this.on("value", () => {
          this.value = this._value;
        }), this.on("confirm", (F2) => {
          this.output.write(srcExports.cursor.move(0, -1)), this.value = F2, this.state = "submit", this.close();
        }), this.on("cursor", () => {
          this.value = !this.value;
        });
      }
    };
    bD = Object.defineProperty;
    mD = (t2, u3, F2) => u3 in t2 ? bD(t2, u3, { enumerable: true, configurable: true, writable: true, value: F2 }) : t2[u3] = F2;
    Y = (t2, u3, F2) => (mD(t2, typeof u3 != "symbol" ? u3 + "" : u3, F2), F2);
    wD = class extends x {
      constructor(u3) {
        super(u3, false), Y(this, "options"), Y(this, "cursor", 0), this.options = u3.options, this.value = [...u3.initialValues ?? []], this.cursor = Math.max(this.options.findIndex(({ value: F2 }) => F2 === u3.cursorAt), 0), this.on("key", (F2) => {
          F2 === "a" && this.toggleAll();
        }), this.on("cursor", (F2) => {
          switch (F2) {
            case "left":
            case "up":
              this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
              break;
            case "down":
            case "right":
              this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
              break;
            case "space":
              this.toggleValue();
              break;
          }
        });
      }
      get _value() {
        return this.options[this.cursor].value;
      }
      toggleAll() {
        const u3 = this.value.length === this.options.length;
        this.value = u3 ? [] : this.options.map((F2) => F2.value);
      }
      toggleValue() {
        const u3 = this.value.includes(this._value);
        this.value = u3 ? this.value.filter((F2) => F2 !== this._value) : [...this.value, this._value];
      }
    };
    SD = Object.defineProperty;
    $D = (t2, u3, F2) => u3 in t2 ? SD(t2, u3, { enumerable: true, configurable: true, writable: true, value: F2 }) : t2[u3] = F2;
    q = (t2, u3, F2) => ($D(t2, typeof u3 != "symbol" ? u3 + "" : u3, F2), F2);
    jD = class extends x {
      constructor(u3) {
        super(u3, false), q(this, "options"), q(this, "cursor", 0), this.options = u3.options, this.cursor = this.options.findIndex(({ value: F2 }) => F2 === u3.initialValue), this.cursor === -1 && (this.cursor = 0), this.changeValue(), this.on("cursor", (F2) => {
          switch (F2) {
            case "left":
            case "up":
              this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
              break;
            case "down":
            case "right":
              this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
              break;
          }
          this.changeValue();
        });
      }
      get _value() {
        return this.options[this.cursor];
      }
      changeValue() {
        this.value = this._value.value;
      }
    };
    PD = class extends x {
      get valueWithCursor() {
        if (this.state === "submit")
          return this.value;
        if (this.cursor >= this.value.length)
          return `${this.value}\u2588`;
        const u3 = this.value.slice(0, this.cursor), [F2, ...e$1] = this.value.slice(this.cursor);
        return `${u3}${e.inverse(F2)}${e$1.join("")}`;
      }
      get cursor() {
        return this._cursor;
      }
      constructor(u3) {
        super(u3), this.on("finalize", () => {
          this.value || (this.value = u3.defaultValue);
        });
      }
    };
    E = X();
    u = (s2, n2) => E ? s2 : n2;
    ee = u("\u276F", ">");
    A = u("\u25A0", "x");
    B = u("\u25B2", "x");
    S = u("\u2714", "\u221A");
    a = u("");
    m = u("");
    j = u("\u25CF", ">");
    R = u("\u25CB", " ");
    V = u("\u25FB", "[\u2022]");
    M = u("\u25FC", "[+]");
    G = u("\u25FB", "[ ]");
    y = (s2) => {
      switch (s2) {
        case "initial":
        case "active":
          return e.cyan(ee);
        case "cancel":
          return e.red(A);
        case "error":
          return e.yellow(B);
        case "submit":
          return e.green(S);
      }
    };
    k = (s2) => {
      const { cursor: n2, options: t2, style: i2 } = s2, r3 = s2.maxItems ?? Number.POSITIVE_INFINITY, c3 = Math.max(process.stdout.rows - 4, 0), o = Math.min(c3, Math.max(r3, 5));
      let l2 = 0;
      n2 >= l2 + o - 3 ? l2 = Math.max(Math.min(n2 - o + 3, t2.length - o), 0) : n2 < l2 + 2 && (l2 = Math.max(n2 - 2, 0));
      const $ = o < t2.length && l2 > 0, d2 = o < t2.length && l2 + o < t2.length;
      return t2.slice(l2, l2 + o).map((w2, b, C2) => {
        const I3 = b === 0 && $, x2 = b === C2.length - 1 && d2;
        return I3 || x2 ? e.dim("...") : i2(w2, b + l2 === n2);
      });
    };
    ue = (s2) => new PD({ validate: s2.validate, placeholder: s2.placeholder, defaultValue: s2.defaultValue, initialValue: s2.initialValue, render() {
      var _a8;
      const n2 = `${e.gray(a)}
${y(this.state)} ${s2.message}
`, t2 = s2.placeholder ? e.inverse(s2.placeholder[0]) + e.dim(s2.placeholder.slice(1)) : e.inverse(e.hidden("_")), i2 = this.value ? this.valueWithCursor : t2;
      switch (this.state) {
        case "error":
          return `${n2.trim()}
${e.yellow(a)} ${i2}
${e.yellow(m)} ${e.yellow(this.error)}
`;
        case "submit":
          return `${n2}${e.gray(a)} ${e.dim(this.value || s2.placeholder)}`;
        case "cancel":
          return `${n2}${e.gray(a)} ${e.strikethrough(e.dim(this.value ?? ""))}${((_a8 = this.value) == null ? void 0 : _a8.trim()) ? `
${e.gray(a)}` : ""}`;
        default:
          return `${n2}${e.cyan(a)} ${i2}
${e.cyan(m)}
`;
      }
    } }).prompt();
    me = (s2) => {
      const n2 = s2.active ?? "Yes", t2 = s2.inactive ?? "No";
      return new fD({ active: n2, inactive: t2, initialValue: s2.initialValue ?? true, render() {
        const i2 = `${e.gray(a)}
${y(this.state)} ${s2.message}
`, r3 = this.value ? n2 : t2;
        switch (this.state) {
          case "submit":
            return `${i2}${e.gray(a)} ${e.dim(r3)}`;
          case "cancel":
            return `${i2}${e.gray(a)} ${e.strikethrough(e.dim(r3))}
${e.gray(a)}`;
          default:
            return `${i2}${e.cyan(a)} ${this.value ? `${e.green(j)} ${n2}` : `${e.dim(R)} ${e.dim(n2)}`} ${e.dim("/")} ${this.value ? `${e.dim(R)} ${e.dim(t2)}` : `${e.green(j)} ${t2}`}
${e.cyan(m)}
`;
        }
      } }).prompt();
    };
    de = (s2) => {
      const n2 = (t2, i2) => {
        const r3 = t2.label ?? String(t2.value);
        switch (i2) {
          case "selected":
            return `${e.dim(r3)}`;
          case "active":
            return `${e.green(j)} ${r3} ${t2.hint ? e.dim(`(${t2.hint})`) : ""}`;
          case "cancelled":
            return `${e.strikethrough(e.dim(r3))}`;
          default:
            return `${e.dim(R)} ${e.dim(r3)}`;
        }
      };
      return new jD({ options: s2.options, initialValue: s2.initialValue, render() {
        const t2 = `${e.gray(a)}
${y(this.state)} ${s2.message}
`;
        switch (this.state) {
          case "submit":
            return `${t2}${e.gray(a)} ${n2(this.options[this.cursor], "selected")}`;
          case "cancel":
            return `${t2}${e.gray(a)} ${n2(this.options[this.cursor], "cancelled")}
${e.gray(a)}`;
          default:
            return `${t2}${e.cyan(a)} ${k({ cursor: this.cursor, options: this.options, maxItems: s2.maxItems, style: (i2, r3) => n2(i2, r3 ? "active" : "inactive") }).join(`
${e.cyan(a)}  `)}
${e.cyan(m)}
`;
        }
      } }).prompt();
    };
    pe = (s2) => {
      const n2 = (t2, i2) => {
        const r3 = t2.label ?? String(t2.value);
        return i2 === "active" ? `${e.cyan(V)} ${r3} ${t2.hint ? e.dim(`(${t2.hint})`) : ""}` : i2 === "selected" ? `${e.green(M)} ${e.dim(r3)}` : i2 === "cancelled" ? `${e.strikethrough(e.dim(r3))}` : i2 === "active-selected" ? `${e.green(M)} ${r3} ${t2.hint ? e.dim(`(${t2.hint})`) : ""}` : i2 === "submitted" ? `${e.dim(r3)}` : `${e.dim(G)} ${e.dim(r3)}`;
      };
      return new wD({ options: s2.options, initialValues: s2.initialValues, required: s2.required ?? true, cursorAt: s2.cursorAt, validate(t2) {
        if (this.required && t2.length === 0)
          return `Please select at least one option.
${e.reset(e.dim(`Press ${e.gray(e.bgWhite(e.inverse(" space ")))} to select, ${e.gray(e.bgWhite(e.inverse(" enter ")))} to submit`))}`;
      }, render() {
        const t2 = `${e.gray(a)}
${y(this.state)} ${s2.message}
`, i2 = (r3, c3) => {
          const o = this.value.includes(r3.value);
          return c3 && o ? n2(r3, "active-selected") : o ? n2(r3, "selected") : n2(r3, c3 ? "active" : "inactive");
        };
        switch (this.state) {
          case "submit":
            return `${t2}${e.gray(a)} ${this.options.filter(({ value: r3 }) => this.value.includes(r3)).map((r3) => n2(r3, "submitted")).join(e.dim(", ")) || e.dim("none")}`;
          case "cancel": {
            const r3 = this.options.filter(({ value: c3 }) => this.value.includes(c3)).map((c3) => n2(c3, "cancelled")).join(e.dim(", "));
            return `${t2}${e.gray(a)} ${r3.trim() ? `${r3}
${e.gray(a)}` : ""}`;
          }
          case "error": {
            const r3 = this.error.split(`
`).map((c3, o) => o === 0 ? `${e.yellow(m)} ${e.yellow(c3)}` : `   ${c3}`).join(`
`);
            return `${t2 + e.yellow(a)} ${k({ options: this.options, cursor: this.cursor, maxItems: s2.maxItems, style: i2 }).join(`
${e.yellow(a)}  `)}
${r3}
`;
          }
          default:
            return `${t2}${e.cyan(a)} ${k({ options: this.options, cursor: this.cursor, maxItems: s2.maxItems, style: i2 }).join(`
${e.cyan(a)}  `)}
${e.cyan(m)}
`;
        }
      } }).prompt();
    };
    kCancel = Symbol.for("cancel");
  }
});

// ../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/eta.js
var require_eta = __commonJS({
  "../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/eta.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var ETA = class {
      constructor(length, initTime, initValue) {
        this.etaBufferLength = length || 100;
        this.valueBuffer = [initValue];
        this.timeBuffer = [initTime];
        this.eta = "0";
      }
      // add new values to calculation buffer
      update(time, value, total) {
        this.valueBuffer.push(value);
        this.timeBuffer.push(time);
        this.calculate(total - value);
      }
      // fetch estimated time
      getTime() {
        return this.eta;
      }
      // eta calculation - request number of remaining events
      calculate(remaining) {
        const currentBufferSize = this.valueBuffer.length;
        const buffer = Math.min(this.etaBufferLength, currentBufferSize);
        const v_diff = this.valueBuffer[currentBufferSize - 1] - this.valueBuffer[currentBufferSize - buffer];
        const t_diff = this.timeBuffer[currentBufferSize - 1] - this.timeBuffer[currentBufferSize - buffer];
        const vt_rate = v_diff / t_diff;
        this.valueBuffer = this.valueBuffer.slice(-this.etaBufferLength);
        this.timeBuffer = this.timeBuffer.slice(-this.etaBufferLength);
        const eta = Math.ceil(remaining / vt_rate / 1e3);
        if (isNaN(eta)) {
          this.eta = "NULL";
        } else if (!isFinite(eta)) {
          this.eta = "INF";
        } else if (eta > 1e7) {
          this.eta = "INF";
        } else if (eta < 0) {
          this.eta = 0;
        } else {
          this.eta = eta;
        }
      }
    };
    module.exports = ETA;
  }
});

// ../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/terminal.js
var require_terminal = __commonJS({
  "../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/terminal.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var _readline = __require("readline");
    var Terminal = class {
      constructor(outputStream) {
        this.stream = outputStream;
        this.linewrap = true;
        this.dy = 0;
      }
      // save cursor position + settings
      cursorSave() {
        if (!this.stream.isTTY) {
          return;
        }
        this.stream.write("\x1B7");
      }
      // restore last cursor position + settings
      cursorRestore() {
        if (!this.stream.isTTY) {
          return;
        }
        this.stream.write("\x1B8");
      }
      // show/hide cursor
      cursor(enabled) {
        if (!this.stream.isTTY) {
          return;
        }
        if (enabled) {
          this.stream.write("\x1B[?25h");
        } else {
          this.stream.write("\x1B[?25l");
        }
      }
      // change cursor positionn
      cursorTo(x2 = null, y3 = null) {
        if (!this.stream.isTTY) {
          return;
        }
        _readline.cursorTo(this.stream, x2, y3);
      }
      // change relative cursor position
      cursorRelative(dx = null, dy = null) {
        if (!this.stream.isTTY) {
          return;
        }
        this.dy = this.dy + dy;
        _readline.moveCursor(this.stream, dx, dy);
      }
      // relative reset
      cursorRelativeReset() {
        if (!this.stream.isTTY) {
          return;
        }
        _readline.moveCursor(this.stream, 0, -this.dy);
        _readline.cursorTo(this.stream, 0, null);
        this.dy = 0;
      }
      // clear to the right from cursor
      clearRight() {
        if (!this.stream.isTTY) {
          return;
        }
        _readline.clearLine(this.stream, 1);
      }
      // clear the full line
      clearLine() {
        if (!this.stream.isTTY) {
          return;
        }
        _readline.clearLine(this.stream, 0);
      }
      // clear everyting beyond the current line
      clearBottom() {
        if (!this.stream.isTTY) {
          return;
        }
        _readline.clearScreenDown(this.stream);
      }
      // add new line; increment counter
      newline() {
        this.stream.write("\n");
        this.dy++;
      }
      // write content to output stream
      // @TODO use string-width to strip length
      write(s2, rawWrite = false) {
        if (this.linewrap === true && rawWrite === false) {
          this.stream.write(s2.substr(0, this.getWidth()));
        } else {
          this.stream.write(s2);
        }
      }
      // control line wrapping
      lineWrapping(enabled) {
        if (!this.stream.isTTY) {
          return;
        }
        this.linewrap = enabled;
        if (enabled) {
          this.stream.write("\x1B[?7h");
        } else {
          this.stream.write("\x1B[?7l");
        }
      }
      // tty environment ?
      isTTY() {
        return this.stream.isTTY === true;
      }
      // get terminal width
      getWidth() {
        return this.stream.columns || (this.stream.isTTY ? 80 : 200);
      }
    };
    module.exports = Terminal;
  }
});

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

// ../../node_modules/.pnpm/strip-ansi@6.0.1/node_modules/strip-ansi/index.js
var require_strip_ansi = __commonJS({
  "../../node_modules/.pnpm/strip-ansi@6.0.1/node_modules/strip-ansi/index.js"(exports, module) {
    "use strict";
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var ansiRegex3 = require_ansi_regex();
    module.exports = (string) => typeof string === "string" ? string.replace(ansiRegex3(), "") : string;
  }
});

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

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

// ../../node_modules/.pnpm/string-width@4.2.3/node_modules/string-width/index.js
var require_string_width = __commonJS({
  "../../node_modules/.pnpm/string-width@4.2.3/node_modules/string-width/index.js"(exports, module) {
    "use strict";
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var stripAnsi3 = require_strip_ansi();
    var isFullwidthCodePoint = require_is_fullwidth_code_point();
    var emojiRegex2 = require_emoji_regex();
    var stringWidth2 = (string) => {
      if (typeof string !== "string" || string.length === 0) {
        return 0;
      }
      string = stripAnsi3(string);
      if (string.length === 0) {
        return 0;
      }
      string = string.replace(emojiRegex2(), "  ");
      let width = 0;
      for (let i2 = 0; i2 < string.length; i2++) {
        const code = string.codePointAt(i2);
        if (code <= 31 || code >= 127 && code <= 159) {
          continue;
        }
        if (code >= 768 && code <= 879) {
          continue;
        }
        if (code > 65535) {
          i2++;
        }
        width += isFullwidthCodePoint(code) ? 2 : 1;
      }
      return width;
    };
    module.exports = stringWidth2;
    module.exports.default = stringWidth2;
  }
});

// ../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/format-value.js
var require_format_value = __commonJS({
  "../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/format-value.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    module.exports = function formatValue(v3, options, type) {
      if (options.autopadding !== true) {
        return v3;
      }
      function autopadding(value, length) {
        return (options.autopaddingChar + value).slice(-length);
      }
      switch (type) {
        case "percentage":
          return autopadding(v3, 3);
        default:
          return v3;
      }
    };
  }
});

// ../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/format-bar.js
var require_format_bar = __commonJS({
  "../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/format-bar.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    module.exports = function formatBar(progress, options) {
      const completeSize = Math.round(progress * options.barsize);
      const incompleteSize = options.barsize - completeSize;
      return options.barCompleteString.substr(0, completeSize) + options.barGlue + options.barIncompleteString.substr(0, incompleteSize);
    };
  }
});

// ../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/format-time.js
var require_format_time = __commonJS({
  "../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/format-time.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    module.exports = function formatTime(t2, options, roundToMultipleOf) {
      function round(input) {
        if (roundToMultipleOf) {
          return roundToMultipleOf * Math.round(input / roundToMultipleOf);
        } else {
          return input;
        }
      }
      function autopadding(v3) {
        return (options.autopaddingChar + v3).slice(-2);
      }
      if (t2 > 3600) {
        return autopadding(Math.floor(t2 / 3600)) + "h" + autopadding(round(t2 % 3600 / 60)) + "m";
      } else if (t2 > 60) {
        return autopadding(Math.floor(t2 / 60)) + "m" + autopadding(round(t2 % 60)) + "s";
      } else if (t2 > 10) {
        return autopadding(round(t2)) + "s";
      } else {
        return autopadding(t2) + "s";
      }
    };
  }
});

// ../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/formatter.js
var require_formatter = __commonJS({
  "../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/formatter.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var _stringWidth = require_string_width();
    var _defaultFormatValue = require_format_value();
    var _defaultFormatBar = require_format_bar();
    var _defaultFormatTime = require_format_time();
    module.exports = function defaultFormatter(options, params, payload) {
      let s2 = options.format;
      const formatTime = options.formatTime || _defaultFormatTime;
      const formatValue = options.formatValue || _defaultFormatValue;
      const formatBar = options.formatBar || _defaultFormatBar;
      const percentage = Math.floor(params.progress * 100) + "";
      const stopTime = params.stopTime || Date.now();
      const elapsedTime = Math.round((stopTime - params.startTime) / 1e3);
      const context2 = Object.assign({}, payload, {
        bar: formatBar(params.progress, options),
        percentage: formatValue(percentage, options, "percentage"),
        total: formatValue(params.total, options, "total"),
        value: formatValue(params.value, options, "value"),
        eta: formatValue(params.eta, options, "eta"),
        eta_formatted: formatTime(params.eta, options, 5),
        duration: formatValue(elapsedTime, options, "duration"),
        duration_formatted: formatTime(elapsedTime, options, 1)
      });
      s2 = s2.replace(/\{(\w+)\}/g, function(match, key) {
        if (typeof context2[key] !== "undefined") {
          return context2[key];
        }
        return match;
      });
      const fullMargin = Math.max(0, params.maxWidth - _stringWidth(s2) - 2);
      const halfMargin = Math.floor(fullMargin / 2);
      switch (options.align) {
        case "right":
          s2 = fullMargin > 0 ? " ".repeat(fullMargin) + s2 : s2;
          break;
        case "center":
          s2 = halfMargin > 0 ? " ".repeat(halfMargin) + s2 : s2;
          break;
        case "left":
        default:
          break;
      }
      return s2;
    };
  }
});

// ../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/options.js
var require_options = __commonJS({
  "../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/options.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    function mergeOption(v3, defaultValue) {
      if (typeof v3 === "undefined" || v3 === null) {
        return defaultValue;
      } else {
        return v3;
      }
    }
    module.exports = {
      // set global options
      parse: function parse(rawOptions, preset) {
        const options = {};
        const opt = Object.assign({}, preset, rawOptions);
        options.throttleTime = 1e3 / mergeOption(opt.fps, 10);
        options.stream = mergeOption(opt.stream, process.stderr);
        options.terminal = mergeOption(opt.terminal, null);
        options.clearOnComplete = mergeOption(opt.clearOnComplete, false);
        options.stopOnComplete = mergeOption(opt.stopOnComplete, false);
        options.barsize = mergeOption(opt.barsize, 40);
        options.align = mergeOption(opt.align, "left");
        options.hideCursor = mergeOption(opt.hideCursor, false);
        options.linewrap = mergeOption(opt.linewrap, false);
        options.barGlue = mergeOption(opt.barGlue, "");
        options.barCompleteChar = mergeOption(opt.barCompleteChar, "=");
        options.barIncompleteChar = mergeOption(opt.barIncompleteChar, "-");
        options.format = mergeOption(opt.format, "progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}");
        options.formatTime = mergeOption(opt.formatTime, null);
        options.formatValue = mergeOption(opt.formatValue, null);
        options.formatBar = mergeOption(opt.formatBar, null);
        options.etaBufferLength = mergeOption(opt.etaBuffer, 10);
        options.etaAsynchronousUpdate = mergeOption(opt.etaAsynchronousUpdate, false);
        options.progressCalculationRelative = mergeOption(opt.progressCalculationRelative, false);
        options.synchronousUpdate = mergeOption(opt.synchronousUpdate, true);
        options.noTTYOutput = mergeOption(opt.noTTYOutput, false);
        options.notTTYSchedule = mergeOption(opt.notTTYSchedule, 2e3);
        options.emptyOnZero = mergeOption(opt.emptyOnZero, false);
        options.forceRedraw = mergeOption(opt.forceRedraw, false);
        options.autopadding = mergeOption(opt.autopadding, false);
        options.gracefulExit = mergeOption(opt.gracefulExit, false);
        return options;
      },
      // derived options: instance specific, has to be created for every bar element
      assignDerivedOptions: function assignDerivedOptions(options) {
        options.barCompleteString = options.barCompleteChar.repeat(options.barsize + 1);
        options.barIncompleteString = options.barIncompleteChar.repeat(options.barsize + 1);
        options.autopaddingChar = options.autopadding ? mergeOption(options.autopaddingChar, "   ") : "";
        return options;
      }
    };
  }
});

// ../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/generic-bar.js
var require_generic_bar = __commonJS({
  "../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/generic-bar.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var _ETA = require_eta();
    var _Terminal = require_terminal();
    var _formatter = require_formatter();
    var _options = require_options();
    var _EventEmitter = __require("events");
    module.exports = class GenericBar extends _EventEmitter {
      constructor(options) {
        super();
        this.options = _options.assignDerivedOptions(options);
        this.terminal = this.options.terminal ? this.options.terminal : new _Terminal(this.options.stream);
        this.value = 0;
        this.startValue = 0;
        this.total = 100;
        this.lastDrawnString = null;
        this.startTime = null;
        this.stopTime = null;
        this.lastRedraw = Date.now();
        this.eta = new _ETA(this.options.etaBufferLength, 0, 0);
        this.payload = {};
        this.isActive = false;
        this.formatter = typeof this.options.format === "function" ? this.options.format : _formatter;
      }
      // internal render function
      render(forceRendering = false) {
        const params = {
          progress: this.getProgress(),
          eta: this.eta.getTime(),
          startTime: this.startTime,
          stopTime: this.stopTime,
          total: this.total,
          value: this.value,
          maxWidth: this.terminal.getWidth()
        };
        if (this.options.etaAsynchronousUpdate) {
          this.updateETA();
        }
        const s2 = this.formatter(this.options, params, this.payload);
        const forceRedraw = forceRendering || this.options.forceRedraw || this.options.noTTYOutput && !this.terminal.isTTY();
        if (forceRedraw || this.lastDrawnString != s2) {
          this.emit("redraw-pre");
          this.terminal.cursorTo(0, null);
          this.terminal.write(s2);
          this.terminal.clearRight();
          this.lastDrawnString = s2;
          this.lastRedraw = Date.now();
          this.emit("redraw-post");
        }
      }
      // start the progress bar
      start(total, startValue, payload) {
        this.value = startValue || 0;
        this.total = typeof total !== "undefined" && total >= 0 ? total : 100;
        this.startValue = startValue || 0;
        this.payload = payload || {};
        this.startTime = Date.now();
        this.stopTime = null;
        this.lastDrawnString = "";
        this.eta = new _ETA(this.options.etaBufferLength, this.startTime, this.value);
        this.isActive = true;
        this.emit("start", total, startValue);
      }
      // stop the bar
      stop() {
        this.isActive = false;
        this.stopTime = Date.now();
        this.emit("stop", this.total, this.value);
      }
      // update the bar value
      // update(value, payload)
      // update(payload)
      update(arg0, arg1 = {}) {
        if (typeof arg0 === "number") {
          this.value = arg0;
          this.eta.update(Date.now(), arg0, this.total);
        }
        const payloadData = (typeof arg0 === "object" ? arg0 : arg1) || {};
        this.emit("update", this.total, this.value);
        for (const key in payloadData) {
          this.payload[key] = payloadData[key];
        }
        if (this.value >= this.getTotal() && this.options.stopOnComplete) {
          this.stop();
        }
      }
      // calculate the actual progress value
      getProgress() {
        let progress = this.value / this.total;
        if (this.options.progressCalculationRelative) {
          progress = (this.value - this.startValue) / (this.total - this.startValue);
        }
        if (isNaN(progress)) {
          progress = this.options && this.options.emptyOnZero ? 0 : 1;
        }
        progress = Math.min(Math.max(progress, 0), 1);
        return progress;
      }
      // update the bar value
      // increment(delta, payload)
      // increment(payload)
      increment(arg0 = 1, arg1 = {}) {
        if (typeof arg0 === "object") {
          this.update(this.value + 1, arg0);
        } else {
          this.update(this.value + arg0, arg1);
        }
      }
      // get the total (limit) value
      getTotal() {
        return this.total;
      }
      // set the total (limit) value
      setTotal(total) {
        if (typeof total !== "undefined" && total >= 0) {
          this.total = total;
        }
      }
      // force eta calculation update (long running processes)
      updateETA() {
        this.eta.update(Date.now(), this.value, this.total);
      }
    };
  }
});

// ../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/single-bar.js
var require_single_bar = __commonJS({
  "../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/single-bar.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var _GenericBar = require_generic_bar();
    var _options = require_options();
    module.exports = class SingleBar extends _GenericBar {
      constructor(options, preset) {
        super(_options.parse(options, preset));
        this.timer = null;
        if (this.options.noTTYOutput && this.terminal.isTTY() === false) {
          this.options.synchronousUpdate = false;
        }
        this.schedulingRate = this.terminal.isTTY() ? this.options.throttleTime : this.options.notTTYSchedule;
        this.sigintCallback = null;
      }
      // internal render function
      render() {
        if (this.timer) {
          clearTimeout(this.timer);
          this.timer = null;
        }
        super.render();
        if (this.options.noTTYOutput && this.terminal.isTTY() === false) {
          this.terminal.newline();
        }
        this.timer = setTimeout(this.render.bind(this), this.schedulingRate);
      }
      update(current, payload) {
        if (!this.timer) {
          return;
        }
        super.update(current, payload);
        if (this.options.synchronousUpdate && this.lastRedraw + this.options.throttleTime * 2 < Date.now()) {
          this.render();
        }
      }
      // start the progress bar
      start(total, startValue, payload) {
        if (this.options.noTTYOutput === false && this.terminal.isTTY() === false) {
          return;
        }
        if (this.sigintCallback === null && this.options.gracefulExit) {
          this.sigintCallback = this.stop.bind(this);
          process.once("SIGINT", this.sigintCallback);
          process.once("SIGTERM", this.sigintCallback);
        }
        this.terminal.cursorSave();
        if (this.options.hideCursor === true) {
          this.terminal.cursor(false);
        }
        if (this.options.linewrap === false) {
          this.terminal.lineWrapping(false);
        }
        super.start(total, startValue, payload);
        this.render();
      }
      // stop the bar
      stop() {
        if (!this.timer) {
          return;
        }
        if (this.sigintCallback) {
          process.removeListener("SIGINT", this.sigintCallback);
          process.removeListener("SIGTERM", this.sigintCallback);
          this.sigintCallback = null;
        }
        this.render();
        super.stop();
        clearTimeout(this.timer);
        this.timer = null;
        if (this.options.hideCursor === true) {
          this.terminal.cursor(true);
        }
        if (this.options.linewrap === false) {
          this.terminal.lineWrapping(true);
        }
        this.terminal.cursorRestore();
        if (this.options.clearOnComplete) {
          this.terminal.cursorTo(0, null);
          this.terminal.clearLine();
        } else {
          this.terminal.newline();
        }
      }
    };
  }
});

// ../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/multi-bar.js
var require_multi_bar = __commonJS({
  "../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/lib/multi-bar.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var _Terminal = require_terminal();
    var _BarElement = require_generic_bar();
    var _options = require_options();
    var _EventEmitter = __require("events");
    module.exports = class MultiBar extends _EventEmitter {
      constructor(options, preset) {
        super();
        this.bars = [];
        this.options = _options.parse(options, preset);
        this.options.synchronousUpdate = false;
        this.terminal = this.options.terminal ? this.options.terminal : new _Terminal(this.options.stream);
        this.timer = null;
        this.isActive = false;
        this.schedulingRate = this.terminal.isTTY() ? this.options.throttleTime : this.options.notTTYSchedule;
        this.loggingBuffer = [];
        this.sigintCallback = null;
      }
      // add a new bar to the stack
      create(total, startValue, payload, barOptions = {}) {
        const bar = new _BarElement(Object.assign(
          {},
          // global options
          this.options,
          // terminal instance
          {
            terminal: this.terminal
          },
          // overrides
          barOptions
        ));
        this.bars.push(bar);
        if (this.options.noTTYOutput === false && this.terminal.isTTY() === false) {
          return bar;
        }
        if (this.sigintCallback === null && this.options.gracefulExit) {
          this.sigintCallback = this.stop.bind(this);
          process.once("SIGINT", this.sigintCallback);
          process.once("SIGTERM", this.sigintCallback);
        }
        if (!this.isActive) {
          if (this.options.hideCursor === true) {
            this.terminal.cursor(false);
          }
          if (this.options.linewrap === false) {
            this.terminal.lineWrapping(false);
          }
          this.timer = setTimeout(this.update.bind(this), this.schedulingRate);
        }
        this.isActive = true;
        bar.start(total, startValue, payload);
        this.emit("start");
        return bar;
      }
      // remove a bar from the stack
      remove(bar) {
        const index = this.bars.indexOf(bar);
        if (index < 0) {
          return false;
        }
        this.bars.splice(index, 1);
        this.update();
        this.terminal.newline();
        this.terminal.clearBottom();
        return true;
      }
      // internal update routine
      update() {
        if (this.timer) {
          clearTimeout(this.timer);
          this.timer = null;
        }
        this.emit("update-pre");
        this.terminal.cursorRelativeReset();
        this.emit("redraw-pre");
        if (this.loggingBuffer.length > 0) {
          this.terminal.clearLine();
          while (this.loggingBuffer.length > 0) {
            this.terminal.write(this.loggingBuffer.shift(), true);
          }
        }
        for (let i2 = 0; i2 < this.bars.length; i2++) {
          if (i2 > 0) {
            this.terminal.newline();
          }
          this.bars[i2].render();
        }
        this.emit("redraw-post");
        if (this.options.noTTYOutput && this.terminal.isTTY() === false) {
          this.terminal.newline();
          this.terminal.newline();
        }
        this.timer = setTimeout(this.update.bind(this), this.schedulingRate);
        this.emit("update-post");
        if (this.options.stopOnComplete && !this.bars.find((bar) => bar.isActive)) {
          this.stop();
        }
      }
      stop() {
        clearTimeout(this.timer);
        this.timer = null;
        if (this.sigintCallback) {
          process.removeListener("SIGINT", this.sigintCallback);
          process.removeListener("SIGTERM", this.sigintCallback);
          this.sigintCallback = null;
        }
        this.isActive = false;
        if (this.options.hideCursor === true) {
          this.terminal.cursor(true);
        }
        if (this.options.linewrap === false) {
          this.terminal.lineWrapping(true);
        }
        this.terminal.cursorRelativeReset();
        this.emit("stop-pre-clear");
        if (this.options.clearOnComplete) {
          this.terminal.clearBottom();
        } else {
          for (let i2 = 0; i2 < this.bars.length; i2++) {
            if (i2 > 0) {
              this.terminal.newline();
            }
            this.bars[i2].render();
            this.bars[i2].stop();
          }
          this.terminal.newline();
        }
        this.emit("stop");
      }
      log(s2) {
        this.loggingBuffer.push(s2);
      }
    };
  }
});

// ../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/presets/legacy.js
var require_legacy = __commonJS({
  "../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/presets/legacy.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    module.exports = {
      format: "progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}",
      barCompleteChar: "=",
      barIncompleteChar: "-"
    };
  }
});

// ../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/presets/shades-classic.js
var require_shades_classic = __commonJS({
  "../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/presets/shades-classic.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    module.exports = {
      format: " {bar} {percentage}% | ETA: {eta}s | {value}/{total}",
      barCompleteChar: "\u2588",
      barIncompleteChar: "\u2591"
    };
  }
});

// ../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/presets/shades-grey.js
var require_shades_grey = __commonJS({
  "../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/presets/shades-grey.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    module.exports = {
      format: " \x1B[90m{bar}\x1B[0m {percentage}% | ETA: {eta}s | {value}/{total}",
      barCompleteChar: "\u2588",
      barIncompleteChar: "\u2591"
    };
  }
});

// ../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/presets/rect.js
var require_rect = __commonJS({
  "../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/presets/rect.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    module.exports = {
      format: " {bar}\u25A0 {percentage}% | ETA: {eta}s | {value}/{total}",
      barCompleteChar: "\u25A0",
      barIncompleteChar: " "
    };
  }
});

// ../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/presets/index.js
var require_presets = __commonJS({
  "../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/presets/index.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var _legacy = require_legacy();
    var _shades_classic = require_shades_classic();
    var _shades_grey = require_shades_grey();
    var _rect = require_rect();
    module.exports = {
      legacy: _legacy,
      shades_classic: _shades_classic,
      shades_grey: _shades_grey,
      rect: _rect
    };
  }
});

// ../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/cli-progress.js
var require_cli_progress = __commonJS({
  "../../node_modules/.pnpm/cli-progress@3.12.0/node_modules/cli-progress/cli-progress.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var _SingleBar = require_single_bar();
    var _MultiBar = require_multi_bar();
    var _Presets = require_presets();
    var _Formatter = require_formatter();
    var _defaultFormatValue = require_format_value();
    var _defaultFormatBar = require_format_bar();
    var _defaultFormatTime = require_format_time();
    module.exports = {
      Bar: _SingleBar,
      SingleBar: _SingleBar,
      MultiBar: _MultiBar,
      Presets: _Presets,
      Format: {
        Formatter: _Formatter,
        BarFormat: _defaultFormatBar,
        ValueFormat: _defaultFormatValue,
        TimeFormat: _defaultFormatTime
      }
    };
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/is.js
var require_is = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/is.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var objectToString = Object.prototype.toString;
    function isError(wat) {
      switch (objectToString.call(wat)) {
        case "[object Error]":
        case "[object Exception]":
        case "[object DOMException]":
          return true;
        default:
          return isInstanceOf(wat, Error);
      }
    }
    function isBuiltin(wat, className) {
      return objectToString.call(wat) === `[object ${className}]`;
    }
    function isErrorEvent(wat) {
      return isBuiltin(wat, "ErrorEvent");
    }
    function isDOMError(wat) {
      return isBuiltin(wat, "DOMError");
    }
    function isDOMException(wat) {
      return isBuiltin(wat, "DOMException");
    }
    function isString2(wat) {
      return isBuiltin(wat, "String");
    }
    function isParameterizedString(wat) {
      return typeof wat === "object" && wat !== null && "__sentry_template_string__" in wat && "__sentry_template_values__" in wat;
    }
    function isPrimitive(wat) {
      return wat === null || isParameterizedString(wat) || typeof wat !== "object" && typeof wat !== "function";
    }
    function isPlainObject3(wat) {
      return isBuiltin(wat, "Object");
    }
    function isEvent(wat) {
      return typeof Event !== "undefined" && isInstanceOf(wat, Event);
    }
    function isElement(wat) {
      return typeof Element !== "undefined" && isInstanceOf(wat, Element);
    }
    function isRegExp(wat) {
      return isBuiltin(wat, "RegExp");
    }
    function isThenable(wat) {
      return Boolean(wat && wat.then && typeof wat.then === "function");
    }
    function isSyntheticEvent(wat) {
      return isPlainObject3(wat) && "nativeEvent" in wat && "preventDefault" in wat && "stopPropagation" in wat;
    }
    function isNaN2(wat) {
      return typeof wat === "number" && wat !== wat;
    }
    function isInstanceOf(wat, base) {
      try {
        return wat instanceof base;
      } catch (_e) {
        return false;
      }
    }
    function isVueViewModel(wat) {
      return !!(typeof wat === "object" && wat !== null && (wat.__isVue || wat._isVue));
    }
    exports.isDOMError = isDOMError;
    exports.isDOMException = isDOMException;
    exports.isElement = isElement;
    exports.isError = isError;
    exports.isErrorEvent = isErrorEvent;
    exports.isEvent = isEvent;
    exports.isInstanceOf = isInstanceOf;
    exports.isNaN = isNaN2;
    exports.isParameterizedString = isParameterizedString;
    exports.isPlainObject = isPlainObject3;
    exports.isPrimitive = isPrimitive;
    exports.isRegExp = isRegExp;
    exports.isString = isString2;
    exports.isSyntheticEvent = isSyntheticEvent;
    exports.isThenable = isThenable;
    exports.isVueViewModel = isVueViewModel;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/string.js
var require_string = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/string.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var is = require_is();
    function truncate(str, max = 0) {
      if (typeof str !== "string" || max === 0) {
        return str;
      }
      return str.length <= max ? str : `${str.slice(0, max)}...`;
    }
    function snipLine(line, colno) {
      let newLine = line;
      const lineLength = newLine.length;
      if (lineLength <= 150) {
        return newLine;
      }
      if (colno > lineLength) {
        colno = lineLength;
      }
      let start = Math.max(colno - 60, 0);
      if (start < 5) {
        start = 0;
      }
      let end = Math.min(start + 140, lineLength);
      if (end > lineLength - 5) {
        end = lineLength;
      }
      if (end === lineLength) {
        start = Math.max(end - 140, 0);
      }
      newLine = newLine.slice(start, end);
      if (start > 0) {
        newLine = `'{snip} ${newLine}`;
      }
      if (end < lineLength) {
        newLine += " {snip}";
      }
      return newLine;
    }
    function safeJoin(input, delimiter) {
      if (!Array.isArray(input)) {
        return "";
      }
      const output = [];
      for (let i2 = 0; i2 < input.length; i2++) {
        const value = input[i2];
        try {
          if (is.isVueViewModel(value)) {
            output.push("[VueViewModel]");
          } else {
            output.push(String(value));
          }
        } catch (e2) {
          output.push("[value cannot be serialized]");
        }
      }
      return output.join(delimiter);
    }
    function isMatchingPattern(value, pattern, requireExactStringMatch = false) {
      if (!is.isString(value)) {
        return false;
      }
      if (is.isRegExp(pattern)) {
        return pattern.test(value);
      }
      if (is.isString(pattern)) {
        return requireExactStringMatch ? value === pattern : value.includes(pattern);
      }
      return false;
    }
    function stringMatchesSomePattern(testString, patterns = [], requireExactStringMatch = false) {
      return patterns.some((pattern) => isMatchingPattern(testString, pattern, requireExactStringMatch));
    }
    exports.isMatchingPattern = isMatchingPattern;
    exports.safeJoin = safeJoin;
    exports.snipLine = snipLine;
    exports.stringMatchesSomePattern = stringMatchesSomePattern;
    exports.truncate = truncate;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/aggregate-errors.js
var require_aggregate_errors = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/aggregate-errors.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var is = require_is();
    var string = require_string();
    function applyAggregateErrorsToEvent(exceptionFromErrorImplementation, parser, maxValueLimit = 250, key, limit, event, hint) {
      if (!event.exception || !event.exception.values || !hint || !is.isInstanceOf(hint.originalException, Error)) {
        return;
      }
      const originalException = event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : void 0;
      if (originalException) {
        event.exception.values = truncateAggregateExceptions(
          aggregateExceptionsFromError(
            exceptionFromErrorImplementation,
            parser,
            limit,
            hint.originalException,
            key,
            event.exception.values,
            originalException,
            0
          ),
          maxValueLimit
        );
      }
    }
    function aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, error, key, prevExceptions, exception, exceptionId) {
      if (prevExceptions.length >= limit + 1) {
        return prevExceptions;
      }
      let newExceptions = [...prevExceptions];
      if (is.isInstanceOf(error[key], Error)) {
        applyExceptionGroupFieldsForParentException(exception, exceptionId);
        const newException = exceptionFromErrorImplementation(parser, error[key]);
        const newExceptionId = newExceptions.length;
        applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId);
        newExceptions = aggregateExceptionsFromError(
          exceptionFromErrorImplementation,
          parser,
          limit,
          error[key],
          key,
          [newException, ...newExceptions],
          newException,
          newExceptionId
        );
      }
      if (Array.isArray(error.errors)) {
        error.errors.forEach((childError, i2) => {
          if (is.isInstanceOf(childError, Error)) {
            applyExceptionGroupFieldsForParentException(exception, exceptionId);
            const newException = exceptionFromErrorImplementation(parser, childError);
            const newExceptionId = newExceptions.length;
            applyExceptionGroupFieldsForChildException(newException, `errors[${i2}]`, newExceptionId, exceptionId);
            newExceptions = aggregateExceptionsFromError(
              exceptionFromErrorImplementation,
              parser,
              limit,
              childError,
              key,
              [newException, ...newExceptions],
              newException,
              newExceptionId
            );
          }
        });
      }
      return newExceptions;
    }
    function applyExceptionGroupFieldsForParentException(exception, exceptionId) {
      exception.mechanism = exception.mechanism || { type: "generic", handled: true };
      exception.mechanism = {
        ...exception.mechanism,
        ...exception.type === "AggregateError" && { is_exception_group: true },
        exception_id: exceptionId
      };
    }
    function applyExceptionGroupFieldsForChildException(exception, source, exceptionId, parentId) {
      exception.mechanism = exception.mechanism || { type: "generic", handled: true };
      exception.mechanism = {
        ...exception.mechanism,
        type: "chained",
        source,
        exception_id: exceptionId,
        parent_id: parentId
      };
    }
    function truncateAggregateExceptions(exceptions, maxValueLength) {
      return exceptions.map((exception) => {
        if (exception.value) {
          exception.value = string.truncate(exception.value, maxValueLength);
        }
        return exception;
      });
    }
    exports.applyAggregateErrorsToEvent = applyAggregateErrorsToEvent;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/worldwide.js
var require_worldwide = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/worldwide.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    function isGlobalObj(obj) {
      return obj && obj.Math == Math ? obj : void 0;
    }
    var GLOBAL_OBJ = typeof globalThis == "object" && isGlobalObj(globalThis) || // eslint-disable-next-line no-restricted-globals
    typeof window == "object" && isGlobalObj(window) || typeof self == "object" && isGlobalObj(self) || typeof global == "object" && isGlobalObj(global) || /* @__PURE__ */ function() {
      return this;
    }() || {};
    function getGlobalObject() {
      return GLOBAL_OBJ;
    }
    function getGlobalSingleton(name, creator, obj) {
      const gbl = obj || GLOBAL_OBJ;
      const __SENTRY__ = gbl.__SENTRY__ = gbl.__SENTRY__ || {};
      const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());
      return singleton;
    }
    exports.GLOBAL_OBJ = GLOBAL_OBJ;
    exports.getGlobalObject = getGlobalObject;
    exports.getGlobalSingleton = getGlobalSingleton;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/browser.js
var require_browser = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/browser.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var is = require_is();
    var worldwide = require_worldwide();
    var WINDOW = worldwide.getGlobalObject();
    var DEFAULT_MAX_STRING_LENGTH = 80;
    function htmlTreeAsString(elem, options = {}) {
      if (!elem) {
        return "<unknown>";
      }
      try {
        let currentElem = elem;
        const MAX_TRAVERSE_HEIGHT = 5;
        const out = [];
        let height = 0;
        let len = 0;
        const separator = " > ";
        const sepLength = separator.length;
        let nextStr;
        const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;
        const maxStringLength = !Array.isArray(options) && options.maxStringLength || DEFAULT_MAX_STRING_LENGTH;
        while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {
          nextStr = _htmlElementAsString(currentElem, keyAttrs);
          if (nextStr === "html" || height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength) {
            break;
          }
          out.push(nextStr);
          len += nextStr.length;
          currentElem = currentElem.parentNode;
        }
        return out.reverse().join(separator);
      } catch (_oO) {
        return "<unknown>";
      }
    }
    function _htmlElementAsString(el, keyAttrs) {
      const elem = el;
      const out = [];
      let className;
      let classes;
      let key;
      let attr;
      let i2;
      if (!elem || !elem.tagName) {
        return "";
      }
      if (WINDOW.HTMLElement) {
        if (elem instanceof HTMLElement && elem.dataset && elem.dataset["sentryComponent"]) {
          return elem.dataset["sentryComponent"];
        }
      }
      out.push(elem.tagName.toLowerCase());
      const keyAttrPairs = keyAttrs && keyAttrs.length ? keyAttrs.filter((keyAttr) => elem.getAttribute(keyAttr)).map((keyAttr) => [keyAttr, elem.getAttribute(keyAttr)]) : null;
      if (keyAttrPairs && keyAttrPairs.length) {
        keyAttrPairs.forEach((keyAttrPair) => {
          out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`);
        });
      } else {
        if (elem.id) {
          out.push(`#${elem.id}`);
        }
        className = elem.className;
        if (className && is.isString(className)) {
          classes = className.split(/\s+/);
          for (i2 = 0; i2 < classes.length; i2++) {
            out.push(`.${classes[i2]}`);
          }
        }
      }
      const allowedAttrs = ["aria-label", "type", "name", "title", "alt"];
      for (i2 = 0; i2 < allowedAttrs.length; i2++) {
        key = allowedAttrs[i2];
        attr = elem.getAttribute(key);
        if (attr) {
          out.push(`[${key}="${attr}"]`);
        }
      }
      return out.join("");
    }
    function getLocationHref() {
      try {
        return WINDOW.document.location.href;
      } catch (oO) {
        return "";
      }
    }
    function getDomElement(selector) {
      if (WINDOW.document && WINDOW.document.querySelector) {
        return WINDOW.document.querySelector(selector);
      }
      return null;
    }
    function getComponentName(elem) {
      if (!WINDOW.HTMLElement) {
        return null;
      }
      let currentElem = elem;
      const MAX_TRAVERSE_HEIGHT = 5;
      for (let i2 = 0; i2 < MAX_TRAVERSE_HEIGHT; i2++) {
        if (!currentElem) {
          return null;
        }
        if (currentElem instanceof HTMLElement && currentElem.dataset["sentryComponent"]) {
          return currentElem.dataset["sentryComponent"];
        }
        currentElem = currentElem.parentNode;
      }
      return null;
    }
    exports.getComponentName = getComponentName;
    exports.getDomElement = getDomElement;
    exports.getLocationHref = getLocationHref;
    exports.htmlTreeAsString = htmlTreeAsString;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/debug-build.js
var require_debug_build = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/debug-build.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
    exports.DEBUG_BUILD = DEBUG_BUILD;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/logger.js
var require_logger = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/logger.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var debugBuild = require_debug_build();
    var worldwide = require_worldwide();
    var PREFIX = "Sentry Logger ";
    var CONSOLE_LEVELS = [
      "debug",
      "info",
      "warn",
      "error",
      "log",
      "assert",
      "trace"
    ];
    var originalConsoleMethods = {};
    function consoleSandbox(callback) {
      if (!("console" in worldwide.GLOBAL_OBJ)) {
        return callback();
      }
      const console2 = worldwide.GLOBAL_OBJ.console;
      const wrappedFuncs = {};
      const wrappedLevels = Object.keys(originalConsoleMethods);
      wrappedLevels.forEach((level) => {
        const originalConsoleMethod = originalConsoleMethods[level];
        wrappedFuncs[level] = console2[level];
        console2[level] = originalConsoleMethod;
      });
      try {
        return callback();
      } finally {
        wrappedLevels.forEach((level) => {
          console2[level] = wrappedFuncs[level];
        });
      }
    }
    function makeLogger() {
      let enabled = false;
      const logger2 = {
        enable: () => {
          enabled = true;
        },
        disable: () => {
          enabled = false;
        },
        isEnabled: () => enabled
      };
      if (debugBuild.DEBUG_BUILD) {
        CONSOLE_LEVELS.forEach((name) => {
          logger2[name] = (...args) => {
            if (enabled) {
              consoleSandbox(() => {
                worldwide.GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);
              });
            }
          };
        });
      } else {
        CONSOLE_LEVELS.forEach((name) => {
          logger2[name] = () => void 0;
        });
      }
      return logger2;
    }
    var logger = makeLogger();
    exports.CONSOLE_LEVELS = CONSOLE_LEVELS;
    exports.consoleSandbox = consoleSandbox;
    exports.logger = logger;
    exports.originalConsoleMethods = originalConsoleMethods;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/dsn.js
var require_dsn = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/dsn.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var debugBuild = require_debug_build();
    var logger = require_logger();
    var DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;
    function isValidProtocol(protocol) {
      return protocol === "http" || protocol === "https";
    }
    function dsnToString(dsn, withPassword = false) {
      const { host, path: path2, pass, port, projectId, protocol, publicKey } = dsn;
      return `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ""}@${host}${port ? `:${port}` : ""}/${path2 ? `${path2}/` : path2}${projectId}`;
    }
    function dsnFromString(str) {
      const match = DSN_REGEX.exec(str);
      if (!match) {
        logger.consoleSandbox(() => {
          console.error(`Invalid Sentry Dsn: ${str}`);
        });
        return void 0;
      }
      const [protocol, publicKey, pass = "", host, port = "", lastPath] = match.slice(1);
      let path2 = "";
      let projectId = lastPath;
      const split = projectId.split("/");
      if (split.length > 1) {
        path2 = split.slice(0, -1).join("/");
        projectId = split.pop();
      }
      if (projectId) {
        const projectMatch = projectId.match(/^\d+/);
        if (projectMatch) {
          projectId = projectMatch[0];
        }
      }
      return dsnFromComponents({ host, pass, path: path2, projectId, port, protocol, publicKey });
    }
    function dsnFromComponents(components) {
      return {
        protocol: components.protocol,
        publicKey: components.publicKey || "",
        pass: components.pass || "",
        host: components.host,
        port: components.port || "",
        path: components.path || "",
        projectId: components.projectId
      };
    }
    function validateDsn(dsn) {
      if (!debugBuild.DEBUG_BUILD) {
        return true;
      }
      const { port, projectId, protocol } = dsn;
      const requiredComponents = ["protocol", "publicKey", "host", "projectId"];
      const hasMissingRequiredComponent = requiredComponents.find((component) => {
        if (!dsn[component]) {
          logger.logger.error(`Invalid Sentry Dsn: ${component} missing`);
          return true;
        }
        return false;
      });
      if (hasMissingRequiredComponent) {
        return false;
      }
      if (!projectId.match(/^\d+$/)) {
        logger.logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);
        return false;
      }
      if (!isValidProtocol(protocol)) {
        logger.logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);
        return false;
      }
      if (port && isNaN(parseInt(port, 10))) {
        logger.logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);
        return false;
      }
      return true;
    }
    function makeDsn(from) {
      const components = typeof from === "string" ? dsnFromString(from) : dsnFromComponents(from);
      if (!components || !validateDsn(components)) {
        return void 0;
      }
      return components;
    }
    exports.dsnFromString = dsnFromString;
    exports.dsnToString = dsnToString;
    exports.makeDsn = makeDsn;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/error.js
var require_error2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/error.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var SentryError = class extends Error {
      /** Display name of this error instance. */
      constructor(message, logLevel = "warn") {
        super(message);
        this.message = message;
        this.name = new.target.prototype.constructor.name;
        Object.setPrototypeOf(this, new.target.prototype);
        this.logLevel = logLevel;
      }
    };
    exports.SentryError = SentryError;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/object.js
var require_object = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/object.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var browser = require_browser();
    var debugBuild = require_debug_build();
    var is = require_is();
    var logger = require_logger();
    var string = require_string();
    function fill(source, name, replacementFactory) {
      if (!(name in source)) {
        return;
      }
      const original = source[name];
      const wrapped = replacementFactory(original);
      if (typeof wrapped === "function") {
        markFunctionWrapped(wrapped, original);
      }
      source[name] = wrapped;
    }
    function addNonEnumerableProperty(obj, name, value) {
      try {
        Object.defineProperty(obj, name, {
          // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it
          value,
          writable: true,
          configurable: true
        });
      } catch (o_O) {
        debugBuild.DEBUG_BUILD && logger.logger.log(`Failed to add non-enumerable property "${name}" to object`, obj);
      }
    }
    function markFunctionWrapped(wrapped, original) {
      try {
        const proto = original.prototype || {};
        wrapped.prototype = original.prototype = proto;
        addNonEnumerableProperty(wrapped, "__sentry_original__", original);
      } catch (o_O) {
      }
    }
    function getOriginalFunction(func) {
      return func.__sentry_original__;
    }
    function urlEncode(object) {
      return Object.keys(object).map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`).join("&");
    }
    function convertToPlainObject(value) {
      if (is.isError(value)) {
        return {
          message: value.message,
          name: value.name,
          stack: value.stack,
          ...getOwnProperties(value)
        };
      } else if (is.isEvent(value)) {
        const newObj = {
          type: value.type,
          target: serializeEventTarget(value.target),
          currentTarget: serializeEventTarget(value.currentTarget),
          ...getOwnProperties(value)
        };
        if (typeof CustomEvent !== "undefined" && is.isInstanceOf(value, CustomEvent)) {
          newObj.detail = value.detail;
        }
        return newObj;
      } else {
        return value;
      }
    }
    function serializeEventTarget(target) {
      try {
        return is.isElement(target) ? browser.htmlTreeAsString(target) : Object.prototype.toString.call(target);
      } catch (_oO) {
        return "<unknown>";
      }
    }
    function getOwnProperties(obj) {
      if (typeof obj === "object" && obj !== null) {
        const extractedProps = {};
        for (const property in obj) {
          if (Object.prototype.hasOwnProperty.call(obj, property)) {
            extractedProps[property] = obj[property];
          }
        }
        return extractedProps;
      } else {
        return {};
      }
    }
    function extractExceptionKeysForMessage(exception, maxLength = 40) {
      const keys = Object.keys(convertToPlainObject(exception));
      keys.sort();
      if (!keys.length) {
        return "[object has no keys]";
      }
      if (keys[0].length >= maxLength) {
        return string.truncate(keys[0], maxLength);
      }
      for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {
        const serialized = keys.slice(0, includedKeys).join(", ");
        if (serialized.length > maxLength) {
          continue;
        }
        if (includedKeys === keys.length) {
          return serialized;
        }
        return string.truncate(serialized, maxLength);
      }
      return "";
    }
    function dropUndefinedKeys(inputValue) {
      const memoizationMap = /* @__PURE__ */ new Map();
      return _dropUndefinedKeys(inputValue, memoizationMap);
    }
    function _dropUndefinedKeys(inputValue, memoizationMap) {
      if (isPojo(inputValue)) {
        const memoVal = memoizationMap.get(inputValue);
        if (memoVal !== void 0) {
          return memoVal;
        }
        const returnValue = {};
        memoizationMap.set(inputValue, returnValue);
        for (const key of Object.keys(inputValue)) {
          if (typeof inputValue[key] !== "undefined") {
            returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);
          }
        }
        return returnValue;
      }
      if (Array.isArray(inputValue)) {
        const memoVal = memoizationMap.get(inputValue);
        if (memoVal !== void 0) {
          return memoVal;
        }
        const returnValue = [];
        memoizationMap.set(inputValue, returnValue);
        inputValue.forEach((item) => {
          returnValue.push(_dropUndefinedKeys(item, memoizationMap));
        });
        return returnValue;
      }
      return inputValue;
    }
    function isPojo(input) {
      if (!is.isPlainObject(input)) {
        return false;
      }
      try {
        const name = Object.getPrototypeOf(input).constructor.name;
        return !name || name === "Object";
      } catch (e2) {
        return true;
      }
    }
    function objectify(wat) {
      let objectified;
      switch (true) {
        case (wat === void 0 || wat === null):
          objectified = new String(wat);
          break;
        case (typeof wat === "symbol" || typeof wat === "bigint"):
          objectified = Object(wat);
          break;
        case is.isPrimitive(wat):
          objectified = new wat.constructor(wat);
          break;
        default:
          objectified = wat;
          break;
      }
      return objectified;
    }
    exports.addNonEnumerableProperty = addNonEnumerableProperty;
    exports.convertToPlainObject = convertToPlainObject;
    exports.dropUndefinedKeys = dropUndefinedKeys;
    exports.extractExceptionKeysForMessage = extractExceptionKeysForMessage;
    exports.fill = fill;
    exports.getOriginalFunction = getOriginalFunction;
    exports.markFunctionWrapped = markFunctionWrapped;
    exports.objectify = objectify;
    exports.urlEncode = urlEncode;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/node-stack-trace.js
var require_node_stack_trace = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/node-stack-trace.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    function filenameIsInApp(filename, isNative = false) {
      const isInternal = isNative || filename && // It's not internal if it's an absolute linux path
      !filename.startsWith("/") && // It's not internal if it's an absolute windows path
      !filename.match(/^[A-Z]:/) && // It's not internal if the path is starting with a dot
      !filename.startsWith(".") && // It's not internal if the frame has a protocol. In node, this is usually the case if the file got pre-processed with a bundler like webpack
      !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//);
      return !isInternal && filename !== void 0 && !filename.includes("node_modules/");
    }
    function node(getModule) {
      const FILENAME_MATCH = /^\s*[-]{4,}$/;
      const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
      return (line) => {
        const lineMatch = line.match(FULL_MATCH);
        if (lineMatch) {
          let object;
          let method;
          let functionName;
          let typeName;
          let methodName;
          if (lineMatch[1]) {
            functionName = lineMatch[1];
            let methodStart = functionName.lastIndexOf(".");
            if (functionName[methodStart - 1] === ".") {
              methodStart--;
            }
            if (methodStart > 0) {
              object = functionName.slice(0, methodStart);
              method = functionName.slice(methodStart + 1);
              const objectEnd = object.indexOf(".Module");
              if (objectEnd > 0) {
                functionName = functionName.slice(objectEnd + 1);
                object = object.slice(0, objectEnd);
              }
            }
            typeName = void 0;
          }
          if (method) {
            typeName = object;
            methodName = method;
          }
          if (method === "<anonymous>") {
            methodName = void 0;
            functionName = void 0;
          }
          if (functionName === void 0) {
            methodName = methodName || "<anonymous>";
            functionName = typeName ? `${typeName}.${methodName}` : methodName;
          }
          let filename = lineMatch[2] && lineMatch[2].startsWith("file://") ? lineMatch[2].slice(7) : lineMatch[2];
          const isNative = lineMatch[5] === "native";
          if (filename && filename.match(/\/[A-Z]:/)) {
            filename = filename.slice(1);
          }
          if (!filename && lineMatch[5] && !isNative) {
            filename = lineMatch[5];
          }
          return {
            filename,
            module: getModule ? getModule(filename) : void 0,
            function: functionName,
            lineno: parseInt(lineMatch[3], 10) || void 0,
            colno: parseInt(lineMatch[4], 10) || void 0,
            in_app: filenameIsInApp(filename, isNative)
          };
        }
        if (line.match(FILENAME_MATCH)) {
          return {
            filename: line
          };
        }
        return void 0;
      };
    }
    exports.filenameIsInApp = filenameIsInApp;
    exports.node = node;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/stacktrace.js
var require_stacktrace = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/stacktrace.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var nodeStackTrace = require_node_stack_trace();
    var STACKTRACE_FRAME_LIMIT = 50;
    var WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
    var STRIP_FRAME_REGEXP = /captureMessage|captureException/;
    function createStackParser(...parsers) {
      const sortedParsers = parsers.sort((a3, b) => a3[0] - b[0]).map((p3) => p3[1]);
      return (stack, skipFirst = 0) => {
        const frames = [];
        const lines = stack.split("\n");
        for (let i2 = skipFirst; i2 < lines.length; i2++) {
          const line = lines[i2];
          if (line.length > 1024) {
            continue;
          }
          const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line;
          if (cleanedLine.match(/\S*Error: /)) {
            continue;
          }
          for (const parser of sortedParsers) {
            const frame = parser(cleanedLine);
            if (frame) {
              frames.push(frame);
              break;
            }
          }
          if (frames.length >= STACKTRACE_FRAME_LIMIT) {
            break;
          }
        }
        return stripSentryFramesAndReverse(frames);
      };
    }
    function stackParserFromStackParserOptions(stackParser) {
      if (Array.isArray(stackParser)) {
        return createStackParser(...stackParser);
      }
      return stackParser;
    }
    function stripSentryFramesAndReverse(stack) {
      if (!stack.length) {
        return [];
      }
      const localStack = Array.from(stack);
      if (/sentryWrapped/.test(localStack[localStack.length - 1].function || "")) {
        localStack.pop();
      }
      localStack.reverse();
      if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || "")) {
        localStack.pop();
        if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || "")) {
          localStack.pop();
        }
      }
      return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
        ...frame,
        filename: frame.filename || localStack[localStack.length - 1].filename,
        function: frame.function || "?"
      }));
    }
    var defaultFunctionName = "<anonymous>";
    function getFunctionName(fn) {
      try {
        if (!fn || typeof fn !== "function") {
          return defaultFunctionName;
        }
        return fn.name || defaultFunctionName;
      } catch (e2) {
        return defaultFunctionName;
      }
    }
    function nodeStackLineParser(getModule) {
      return [90, nodeStackTrace.node(getModule)];
    }
    exports.filenameIsInApp = nodeStackTrace.filenameIsInApp;
    exports.createStackParser = createStackParser;
    exports.getFunctionName = getFunctionName;
    exports.nodeStackLineParser = nodeStackLineParser;
    exports.stackParserFromStackParserOptions = stackParserFromStackParserOptions;
    exports.stripSentryFramesAndReverse = stripSentryFramesAndReverse;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/instrument/_handlers.js
var require_handlers = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/instrument/_handlers.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var debugBuild = require_debug_build();
    var logger = require_logger();
    var stacktrace = require_stacktrace();
    var handlers = {};
    var instrumented = {};
    function addHandler(type, handler) {
      handlers[type] = handlers[type] || [];
      handlers[type].push(handler);
    }
    function resetInstrumentationHandlers() {
      Object.keys(handlers).forEach((key) => {
        handlers[key] = void 0;
      });
    }
    function maybeInstrument(type, instrumentFn) {
      if (!instrumented[type]) {
        instrumentFn();
        instrumented[type] = true;
      }
    }
    function triggerHandlers(type, data) {
      const typeHandlers = type && handlers[type];
      if (!typeHandlers) {
        return;
      }
      for (const handler of typeHandlers) {
        try {
          handler(data);
        } catch (e2) {
          debugBuild.DEBUG_BUILD && logger.logger.error(
            `Error while triggering instrumentation handler.
Type: ${type}
Name: ${stacktrace.getFunctionName(handler)}
Error:`,
            e2
          );
        }
      }
    }
    exports.addHandler = addHandler;
    exports.maybeInstrument = maybeInstrument;
    exports.resetInstrumentationHandlers = resetInstrumentationHandlers;
    exports.triggerHandlers = triggerHandlers;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/instrument/console.js
var require_console = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/instrument/console.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var logger = require_logger();
    var object = require_object();
    var worldwide = require_worldwide();
    var _handlers = require_handlers();
    function addConsoleInstrumentationHandler(handler) {
      const type = "console";
      _handlers.addHandler(type, handler);
      _handlers.maybeInstrument(type, instrumentConsole);
    }
    function instrumentConsole() {
      if (!("console" in worldwide.GLOBAL_OBJ)) {
        return;
      }
      logger.CONSOLE_LEVELS.forEach(function(level) {
        if (!(level in worldwide.GLOBAL_OBJ.console)) {
          return;
        }
        object.fill(worldwide.GLOBAL_OBJ.console, level, function(originalConsoleMethod) {
          logger.originalConsoleMethods[level] = originalConsoleMethod;
          return function(...args) {
            const handlerData = { args, level };
            _handlers.triggerHandlers("console", handlerData);
            const log2 = logger.originalConsoleMethods[level];
            log2 && log2.apply(worldwide.GLOBAL_OBJ.console, args);
          };
        });
      });
    }
    exports.addConsoleInstrumentationHandler = addConsoleInstrumentationHandler;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/misc.js
var require_misc = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/misc.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var object = require_object();
    var string = require_string();
    var worldwide = require_worldwide();
    function uuid4() {
      const gbl = worldwide.GLOBAL_OBJ;
      const crypto2 = gbl.crypto || gbl.msCrypto;
      let getRandomByte = () => Math.random() * 16;
      try {
        if (crypto2 && crypto2.randomUUID) {
          return crypto2.randomUUID().replace(/-/g, "");
        }
        if (crypto2 && crypto2.getRandomValues) {
          getRandomByte = () => {
            const typedArray = new Uint8Array(1);
            crypto2.getRandomValues(typedArray);
            return typedArray[0];
          };
        }
      } catch (_3) {
      }
      return ("10000000100040008000" + 1e11).replace(
        /[018]/g,
        (c3) => (
          // eslint-disable-next-line no-bitwise
          (c3 ^ (getRandomByte() & 15) >> c3 / 4).toString(16)
        )
      );
    }
    function getFirstException(event) {
      return event.exception && event.exception.values ? event.exception.values[0] : void 0;
    }
    function getEventDescription(event) {
      const { message, event_id: eventId } = event;
      if (message) {
        return message;
      }
      const firstException = getFirstException(event);
      if (firstException) {
        if (firstException.type && firstException.value) {
          return `${firstException.type}: ${firstException.value}`;
        }
        return firstException.type || firstException.value || eventId || "<unknown>";
      }
      return eventId || "<unknown>";
    }
    function addExceptionTypeValue(event, value, type) {
      const exception = event.exception = event.exception || {};
      const values = exception.values = exception.values || [];
      const firstException = values[0] = values[0] || {};
      if (!firstException.value) {
        firstException.value = value || "";
      }
      if (!firstException.type) {
        firstException.type = type || "Error";
      }
    }
    function addExceptionMechanism(event, newMechanism) {
      const firstException = getFirstException(event);
      if (!firstException) {
        return;
      }
      const defaultMechanism = { type: "generic", handled: true };
      const currentMechanism = firstException.mechanism;
      firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };
      if (newMechanism && "data" in newMechanism) {
        const mergedData = { ...currentMechanism && currentMechanism.data, ...newMechanism.data };
        firstException.mechanism.data = mergedData;
      }
    }
    var SEMVER_REGEXP = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
    function parseSemver2(input) {
      const match = input.match(SEMVER_REGEXP) || [];
      const major = parseInt(match[1], 10);
      const minor = parseInt(match[2], 10);
      const patch = parseInt(match[3], 10);
      return {
        buildmetadata: match[5],
        major: isNaN(major) ? void 0 : major,
        minor: isNaN(minor) ? void 0 : minor,
        patch: isNaN(patch) ? void 0 : patch,
        prerelease: match[4]
      };
    }
    function addContextToFrame(lines, frame, linesOfContext = 5) {
      if (frame.lineno === void 0) {
        return;
      }
      const maxLines = lines.length;
      const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);
      frame.pre_context = lines.slice(Math.max(0, sourceLine - linesOfContext), sourceLine).map((line) => string.snipLine(line, 0));
      frame.context_line = string.snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);
      frame.post_context = lines.slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext).map((line) => string.snipLine(line, 0));
    }
    function checkOrSetAlreadyCaught(exception) {
      if (exception && exception.__sentry_captured__) {
        return true;
      }
      try {
        object.addNonEnumerableProperty(exception, "__sentry_captured__", true);
      } catch (err) {
      }
      return false;
    }
    function arrayify(maybeArray) {
      return Array.isArray(maybeArray) ? maybeArray : [maybeArray];
    }
    exports.addContextToFrame = addContextToFrame;
    exports.addExceptionMechanism = addExceptionMechanism;
    exports.addExceptionTypeValue = addExceptionTypeValue;
    exports.arrayify = arrayify;
    exports.checkOrSetAlreadyCaught = checkOrSetAlreadyCaught;
    exports.getEventDescription = getEventDescription;
    exports.parseSemver = parseSemver2;
    exports.uuid4 = uuid4;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/instrument/dom.js
var require_dom = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/instrument/dom.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var misc = require_misc();
    var object = require_object();
    var worldwide = require_worldwide();
    var _handlers = require_handlers();
    var WINDOW = worldwide.GLOBAL_OBJ;
    var DEBOUNCE_DURATION = 1e3;
    var debounceTimerID;
    var lastCapturedEventType;
    var lastCapturedEventTargetId;
    function addClickKeypressInstrumentationHandler(handler) {
      const type = "dom";
      _handlers.addHandler(type, handler);
      _handlers.maybeInstrument(type, instrumentDOM);
    }
    function instrumentDOM() {
      if (!WINDOW.document) {
        return;
      }
      const triggerDOMHandler = _handlers.triggerHandlers.bind(null, "dom");
      const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);
      WINDOW.document.addEventListener("click", globalDOMEventHandler, false);
      WINDOW.document.addEventListener("keypress", globalDOMEventHandler, false);
      ["EventTarget", "Node"].forEach((target) => {
        const proto = WINDOW[target] && WINDOW[target].prototype;
        if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty("addEventListener")) {
          return;
        }
        object.fill(proto, "addEventListener", function(originalAddEventListener) {
          return function(type, listener, options) {
            if (type === "click" || type == "keypress") {
              try {
                const el = this;
                const handlers = el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {};
                const handlerForType = handlers[type] = handlers[type] || { refCount: 0 };
                if (!handlerForType.handler) {
                  const handler = makeDOMEventHandler(triggerDOMHandler);
                  handlerForType.handler = handler;
                  originalAddEventListener.call(this, type, handler, options);
                }
                handlerForType.refCount++;
              } catch (e2) {
              }
            }
            return originalAddEventListener.call(this, type, listener, options);
          };
        });
        object.fill(
          proto,
          "removeEventListener",
          function(originalRemoveEventListener) {
            return function(type, listener, options) {
              if (type === "click" || type == "keypress") {
                try {
                  const el = this;
                  const handlers = el.__sentry_instrumentation_handlers__ || {};
                  const handlerForType = handlers[type];
                  if (handlerForType) {
                    handlerForType.refCount--;
                    if (handlerForType.refCount <= 0) {
                      originalRemoveEventListener.call(this, type, handlerForType.handler, options);
                      handlerForType.handler = void 0;
                      delete handlers[type];
                    }
                    if (Object.keys(handlers).length === 0) {
                      delete el.__sentry_instrumentation_handlers__;
                    }
                  }
                } catch (e2) {
                }
              }
              return originalRemoveEventListener.call(this, type, listener, options);
            };
          }
        );
      });
    }
    function isSimilarToLastCapturedEvent(event) {
      if (event.type !== lastCapturedEventType) {
        return false;
      }
      try {
        if (!event.target || event.target._sentryId !== lastCapturedEventTargetId) {
          return false;
        }
      } catch (e2) {
      }
      return true;
    }
    function shouldSkipDOMEvent(eventType, target) {
      if (eventType !== "keypress") {
        return false;
      }
      if (!target || !target.tagName) {
        return true;
      }
      if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable) {
        return false;
      }
      return true;
    }
    function makeDOMEventHandler(handler, globalListener = false) {
      return (event) => {
        if (!event || event["_sentryCaptured"]) {
          return;
        }
        const target = getEventTarget(event);
        if (shouldSkipDOMEvent(event.type, target)) {
          return;
        }
        object.addNonEnumerableProperty(event, "_sentryCaptured", true);
        if (target && !target._sentryId) {
          object.addNonEnumerableProperty(target, "_sentryId", misc.uuid4());
        }
        const name = event.type === "keypress" ? "input" : event.type;
        if (!isSimilarToLastCapturedEvent(event)) {
          const handlerData = { event, name, global: globalListener };
          handler(handlerData);
          lastCapturedEventType = event.type;
          lastCapturedEventTargetId = target ? target._sentryId : void 0;
        }
        clearTimeout(debounceTimerID);
        debounceTimerID = WINDOW.setTimeout(() => {
          lastCapturedEventTargetId = void 0;
          lastCapturedEventType = void 0;
        }, DEBOUNCE_DURATION);
      };
    }
    function getEventTarget(event) {
      try {
        return event.target;
      } catch (e2) {
        return null;
      }
    }
    exports.addClickKeypressInstrumentationHandler = addClickKeypressInstrumentationHandler;
    exports.instrumentDOM = instrumentDOM;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/supports.js
var require_supports = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/supports.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var debugBuild = require_debug_build();
    var logger = require_logger();
    var worldwide = require_worldwide();
    var WINDOW = worldwide.getGlobalObject();
    function supportsErrorEvent() {
      try {
        new ErrorEvent("");
        return true;
      } catch (e2) {
        return false;
      }
    }
    function supportsDOMError() {
      try {
        new DOMError("");
        return true;
      } catch (e2) {
        return false;
      }
    }
    function supportsDOMException() {
      try {
        new DOMException("");
        return true;
      } catch (e2) {
        return false;
      }
    }
    function supportsFetch() {
      if (!("fetch" in WINDOW)) {
        return false;
      }
      try {
        new Headers();
        new Request("http://www.example.com");
        new Response();
        return true;
      } catch (e2) {
        return false;
      }
    }
    function isNativeFetch(func) {
      return func && /^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString());
    }
    function supportsNativeFetch() {
      if (typeof EdgeRuntime === "string") {
        return true;
      }
      if (!supportsFetch()) {
        return false;
      }
      if (isNativeFetch(WINDOW.fetch)) {
        return true;
      }
      let result = false;
      const doc = WINDOW.document;
      if (doc && typeof doc.createElement === "function") {
        try {
          const sandbox = doc.createElement("iframe");
          sandbox.hidden = true;
          doc.head.appendChild(sandbox);
          if (sandbox.contentWindow && sandbox.contentWindow.fetch) {
            result = isNativeFetch(sandbox.contentWindow.fetch);
          }
          doc.head.removeChild(sandbox);
        } catch (err) {
          debugBuild.DEBUG_BUILD && logger.logger.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ", err);
        }
      }
      return result;
    }
    function supportsReportingObserver() {
      return "ReportingObserver" in WINDOW;
    }
    function supportsReferrerPolicy() {
      if (!supportsFetch()) {
        return false;
      }
      try {
        new Request("_", {
          referrerPolicy: "origin"
        });
        return true;
      } catch (e2) {
        return false;
      }
    }
    exports.isNativeFetch = isNativeFetch;
    exports.supportsDOMError = supportsDOMError;
    exports.supportsDOMException = supportsDOMException;
    exports.supportsErrorEvent = supportsErrorEvent;
    exports.supportsFetch = supportsFetch;
    exports.supportsNativeFetch = supportsNativeFetch;
    exports.supportsReferrerPolicy = supportsReferrerPolicy;
    exports.supportsReportingObserver = supportsReportingObserver;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/instrument/fetch.js
var require_fetch = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/instrument/fetch.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var object = require_object();
    var supports = require_supports();
    var worldwide = require_worldwide();
    var _handlers = require_handlers();
    function addFetchInstrumentationHandler(handler) {
      const type = "fetch";
      _handlers.addHandler(type, handler);
      _handlers.maybeInstrument(type, instrumentFetch);
    }
    function instrumentFetch() {
      if (!supports.supportsNativeFetch()) {
        return;
      }
      object.fill(worldwide.GLOBAL_OBJ, "fetch", function(originalFetch) {
        return function(...args) {
          const { method, url } = parseFetchArgs(args);
          const handlerData = {
            args,
            fetchData: {
              method,
              url
            },
            startTimestamp: Date.now()
          };
          _handlers.triggerHandlers("fetch", {
            ...handlerData
          });
          return originalFetch.apply(worldwide.GLOBAL_OBJ, args).then(
            (response) => {
              const finishedHandlerData = {
                ...handlerData,
                endTimestamp: Date.now(),
                response
              };
              _handlers.triggerHandlers("fetch", finishedHandlerData);
              return response;
            },
            (error) => {
              const erroredHandlerData = {
                ...handlerData,
                endTimestamp: Date.now(),
                error
              };
              _handlers.triggerHandlers("fetch", erroredHandlerData);
              throw error;
            }
          );
        };
      });
    }
    function hasProp(obj, prop) {
      return !!obj && typeof obj === "object" && !!obj[prop];
    }
    function getUrlFromResource(resource) {
      if (typeof resource === "string") {
        return resource;
      }
      if (!resource) {
        return "";
      }
      if (hasProp(resource, "url")) {
        return resource.url;
      }
      if (resource.toString) {
        return resource.toString();
      }
      return "";
    }
    function parseFetchArgs(fetchArgs) {
      if (fetchArgs.length === 0) {
        return { method: "GET", url: "" };
      }
      if (fetchArgs.length === 2) {
        const [url, options] = fetchArgs;
        return {
          url: getUrlFromResource(url),
          method: hasProp(options, "method") ? String(options.method).toUpperCase() : "GET"
        };
      }
      const arg = fetchArgs[0];
      return {
        url: getUrlFromResource(arg),
        method: hasProp(arg, "method") ? String(arg.method).toUpperCase() : "GET"
      };
    }
    exports.addFetchInstrumentationHandler = addFetchInstrumentationHandler;
    exports.parseFetchArgs = parseFetchArgs;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/instrument/globalError.js
var require_globalError = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/instrument/globalError.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var worldwide = require_worldwide();
    var _handlers = require_handlers();
    var _oldOnErrorHandler = null;
    function addGlobalErrorInstrumentationHandler(handler) {
      const type = "error";
      _handlers.addHandler(type, handler);
      _handlers.maybeInstrument(type, instrumentError);
    }
    function instrumentError() {
      _oldOnErrorHandler = worldwide.GLOBAL_OBJ.onerror;
      worldwide.GLOBAL_OBJ.onerror = function(msg, url, line, column, error) {
        const handlerData = {
          column,
          error,
          line,
          msg,
          url
        };
        _handlers.triggerHandlers("error", handlerData);
        if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) {
          return _oldOnErrorHandler.apply(this, arguments);
        }
        return false;
      };
      worldwide.GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;
    }
    exports.addGlobalErrorInstrumentationHandler = addGlobalErrorInstrumentationHandler;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/instrument/globalUnhandledRejection.js
var require_globalUnhandledRejection = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/instrument/globalUnhandledRejection.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var worldwide = require_worldwide();
    var _handlers = require_handlers();
    var _oldOnUnhandledRejectionHandler = null;
    function addGlobalUnhandledRejectionInstrumentationHandler(handler) {
      const type = "unhandledrejection";
      _handlers.addHandler(type, handler);
      _handlers.maybeInstrument(type, instrumentUnhandledRejection);
    }
    function instrumentUnhandledRejection() {
      _oldOnUnhandledRejectionHandler = worldwide.GLOBAL_OBJ.onunhandledrejection;
      worldwide.GLOBAL_OBJ.onunhandledrejection = function(e2) {
        const handlerData = e2;
        _handlers.triggerHandlers("unhandledrejection", handlerData);
        if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) {
          return _oldOnUnhandledRejectionHandler.apply(this, arguments);
        }
        return true;
      };
      worldwide.GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;
    }
    exports.addGlobalUnhandledRejectionInstrumentationHandler = addGlobalUnhandledRejectionInstrumentationHandler;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/vendor/supportsHistory.js
var require_supportsHistory = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/vendor/supportsHistory.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var worldwide = require_worldwide();
    var WINDOW = worldwide.getGlobalObject();
    function supportsHistory() {
      const chromeVar = WINDOW.chrome;
      const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime;
      const hasHistoryApi = "history" in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;
      return !isChromePackagedApp && hasHistoryApi;
    }
    exports.supportsHistory = supportsHistory;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/instrument/history.js
var require_history = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/instrument/history.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var object = require_object();
    require_debug_build();
    require_logger();
    var worldwide = require_worldwide();
    var supportsHistory = require_supportsHistory();
    var _handlers = require_handlers();
    var WINDOW = worldwide.GLOBAL_OBJ;
    var lastHref;
    function addHistoryInstrumentationHandler(handler) {
      const type = "history";
      _handlers.addHandler(type, handler);
      _handlers.maybeInstrument(type, instrumentHistory);
    }
    function instrumentHistory() {
      if (!supportsHistory.supportsHistory()) {
        return;
      }
      const oldOnPopState = WINDOW.onpopstate;
      WINDOW.onpopstate = function(...args) {
        const to = WINDOW.location.href;
        const from = lastHref;
        lastHref = to;
        const handlerData = { from, to };
        _handlers.triggerHandlers("history", handlerData);
        if (oldOnPopState) {
          try {
            return oldOnPopState.apply(this, args);
          } catch (_oO) {
          }
        }
      };
      function historyReplacementFunction(originalHistoryFunction) {
        return function(...args) {
          const url = args.length > 2 ? args[2] : void 0;
          if (url) {
            const from = lastHref;
            const to = String(url);
            lastHref = to;
            const handlerData = { from, to };
            _handlers.triggerHandlers("history", handlerData);
          }
          return originalHistoryFunction.apply(this, args);
        };
      }
      object.fill(WINDOW.history, "pushState", historyReplacementFunction);
      object.fill(WINDOW.history, "replaceState", historyReplacementFunction);
    }
    exports.addHistoryInstrumentationHandler = addHistoryInstrumentationHandler;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/instrument/xhr.js
var require_xhr = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/instrument/xhr.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var is = require_is();
    var object = require_object();
    var worldwide = require_worldwide();
    var _handlers = require_handlers();
    var WINDOW = worldwide.GLOBAL_OBJ;
    var SENTRY_XHR_DATA_KEY = "__sentry_xhr_v3__";
    function addXhrInstrumentationHandler(handler) {
      const type = "xhr";
      _handlers.addHandler(type, handler);
      _handlers.maybeInstrument(type, instrumentXHR);
    }
    function instrumentXHR() {
      if (!WINDOW.XMLHttpRequest) {
        return;
      }
      const xhrproto = XMLHttpRequest.prototype;
      object.fill(xhrproto, "open", function(originalOpen) {
        return function(...args) {
          const startTimestamp = Date.now();
          const method = is.isString(args[0]) ? args[0].toUpperCase() : void 0;
          const url = parseUrl(args[1]);
          if (!method || !url) {
            return originalOpen.apply(this, args);
          }
          this[SENTRY_XHR_DATA_KEY] = {
            method,
            url,
            request_headers: {}
          };
          if (method === "POST" && url.match(/sentry_key/)) {
            this.__sentry_own_request__ = true;
          }
          const onreadystatechangeHandler = () => {
            const xhrInfo = this[SENTRY_XHR_DATA_KEY];
            if (!xhrInfo) {
              return;
            }
            if (this.readyState === 4) {
              try {
                xhrInfo.status_code = this.status;
              } catch (e2) {
              }
              const handlerData = {
                args: [method, url],
                endTimestamp: Date.now(),
                startTimestamp,
                xhr: this
              };
              _handlers.triggerHandlers("xhr", handlerData);
            }
          };
          if ("onreadystatechange" in this && typeof this.onreadystatechange === "function") {
            object.fill(this, "onreadystatechange", function(original) {
              return function(...readyStateArgs) {
                onreadystatechangeHandler();
                return original.apply(this, readyStateArgs);
              };
            });
          } else {
            this.addEventListener("readystatechange", onreadystatechangeHandler);
          }
          object.fill(this, "setRequestHeader", function(original) {
            return function(...setRequestHeaderArgs) {
              const [header, value] = setRequestHeaderArgs;
              const xhrInfo = this[SENTRY_XHR_DATA_KEY];
              if (xhrInfo && is.isString(header) && is.isString(value)) {
                xhrInfo.request_headers[header.toLowerCase()] = value;
              }
              return original.apply(this, setRequestHeaderArgs);
            };
          });
          return originalOpen.apply(this, args);
        };
      });
      object.fill(xhrproto, "send", function(originalSend) {
        return function(...args) {
          const sentryXhrData = this[SENTRY_XHR_DATA_KEY];
          if (!sentryXhrData) {
            return originalSend.apply(this, args);
          }
          if (args[0] !== void 0) {
            sentryXhrData.body = args[0];
          }
          const handlerData = {
            args: [sentryXhrData.method, sentryXhrData.url],
            startTimestamp: Date.now(),
            xhr: this
          };
          _handlers.triggerHandlers("xhr", handlerData);
          return originalSend.apply(this, args);
        };
      });
    }
    function parseUrl(url) {
      if (is.isString(url)) {
        return url;
      }
      try {
        return url.toString();
      } catch (e2) {
      }
      return void 0;
    }
    exports.SENTRY_XHR_DATA_KEY = SENTRY_XHR_DATA_KEY;
    exports.addXhrInstrumentationHandler = addXhrInstrumentationHandler;
    exports.instrumentXHR = instrumentXHR;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/instrument/index.js
var require_instrument = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/instrument/index.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var debugBuild = require_debug_build();
    var logger = require_logger();
    var console2 = require_console();
    var dom = require_dom();
    var fetch2 = require_fetch();
    var globalError = require_globalError();
    var globalUnhandledRejection = require_globalUnhandledRejection();
    var history = require_history();
    var xhr = require_xhr();
    function addInstrumentationHandler(type, callback) {
      switch (type) {
        case "console":
          return console2.addConsoleInstrumentationHandler(callback);
        case "dom":
          return dom.addClickKeypressInstrumentationHandler(callback);
        case "xhr":
          return xhr.addXhrInstrumentationHandler(callback);
        case "fetch":
          return fetch2.addFetchInstrumentationHandler(callback);
        case "history":
          return history.addHistoryInstrumentationHandler(callback);
        case "error":
          return globalError.addGlobalErrorInstrumentationHandler(callback);
        case "unhandledrejection":
          return globalUnhandledRejection.addGlobalUnhandledRejectionInstrumentationHandler(callback);
        default:
          debugBuild.DEBUG_BUILD && logger.logger.warn("unknown instrumentation type:", type);
      }
    }
    exports.addConsoleInstrumentationHandler = console2.addConsoleInstrumentationHandler;
    exports.addClickKeypressInstrumentationHandler = dom.addClickKeypressInstrumentationHandler;
    exports.addFetchInstrumentationHandler = fetch2.addFetchInstrumentationHandler;
    exports.addGlobalErrorInstrumentationHandler = globalError.addGlobalErrorInstrumentationHandler;
    exports.addGlobalUnhandledRejectionInstrumentationHandler = globalUnhandledRejection.addGlobalUnhandledRejectionInstrumentationHandler;
    exports.addHistoryInstrumentationHandler = history.addHistoryInstrumentationHandler;
    exports.SENTRY_XHR_DATA_KEY = xhr.SENTRY_XHR_DATA_KEY;
    exports.addXhrInstrumentationHandler = xhr.addXhrInstrumentationHandler;
    exports.addInstrumentationHandler = addInstrumentationHandler;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/env.js
var require_env = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/env.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    function isBrowserBundle() {
      return typeof __SENTRY_BROWSER_BUNDLE__ !== "undefined" && !!__SENTRY_BROWSER_BUNDLE__;
    }
    function getSDKSource() {
      return "npm";
    }
    exports.getSDKSource = getSDKSource;
    exports.isBrowserBundle = isBrowserBundle;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/node.js
var require_node = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/node.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var env2 = require_env();
    function isNodeEnv() {
      return !env2.isBrowserBundle() && Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]";
    }
    function dynamicRequire(mod, request) {
      return mod.require(request);
    }
    function loadModule(moduleName) {
      let mod;
      try {
        mod = dynamicRequire(module, moduleName);
      } catch (e2) {
      }
      try {
        const { cwd } = dynamicRequire(module, "process");
        mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`);
      } catch (e2) {
      }
      return mod;
    }
    exports.dynamicRequire = dynamicRequire;
    exports.isNodeEnv = isNodeEnv;
    exports.loadModule = loadModule;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/isBrowser.js
var require_isBrowser = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/isBrowser.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var node = require_node();
    var worldwide = require_worldwide();
    function isBrowser() {
      return typeof window !== "undefined" && (!node.isNodeEnv() || isElectronNodeRenderer());
    }
    function isElectronNodeRenderer() {
      return (
        // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
        worldwide.GLOBAL_OBJ.process !== void 0 && worldwide.GLOBAL_OBJ.process.type === "renderer"
      );
    }
    exports.isBrowser = isBrowser;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/memo.js
var require_memo = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/memo.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    function memoBuilder() {
      const hasWeakSet = typeof WeakSet === "function";
      const inner = hasWeakSet ? /* @__PURE__ */ new WeakSet() : [];
      function memoize2(obj) {
        if (hasWeakSet) {
          if (inner.has(obj)) {
            return true;
          }
          inner.add(obj);
          return false;
        }
        for (let i2 = 0; i2 < inner.length; i2++) {
          const value = inner[i2];
          if (value === obj) {
            return true;
          }
        }
        inner.push(obj);
        return false;
      }
      function unmemoize(obj) {
        if (hasWeakSet) {
          inner.delete(obj);
        } else {
          for (let i2 = 0; i2 < inner.length; i2++) {
            if (inner[i2] === obj) {
              inner.splice(i2, 1);
              break;
            }
          }
        }
      }
      return [memoize2, unmemoize];
    }
    exports.memoBuilder = memoBuilder;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/normalize.js
var require_normalize = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/normalize.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var is = require_is();
    var memo = require_memo();
    var object = require_object();
    var stacktrace = require_stacktrace();
    function normalize(input, depth = 100, maxProperties = Infinity) {
      try {
        return visit("", input, depth, maxProperties);
      } catch (err) {
        return { ERROR: `**non-serializable** (${err})` };
      }
    }
    function normalizeToSize(object2, depth = 3, maxSize = 100 * 1024) {
      const normalized = normalize(object2, depth);
      if (jsonSize(normalized) > maxSize) {
        return normalizeToSize(object2, depth - 1, maxSize);
      }
      return normalized;
    }
    function visit(key, value, depth = Infinity, maxProperties = Infinity, memo$1 = memo.memoBuilder()) {
      const [memoize2, unmemoize] = memo$1;
      if (value == null || // this matches null and undefined -> eqeq not eqeqeq
      ["number", "boolean", "string"].includes(typeof value) && !is.isNaN(value)) {
        return value;
      }
      const stringified = stringifyValue(key, value);
      if (!stringified.startsWith("[object ")) {
        return stringified;
      }
      if (value["__sentry_skip_normalization__"]) {
        return value;
      }
      const remainingDepth = typeof value["__sentry_override_normalization_depth__"] === "number" ? value["__sentry_override_normalization_depth__"] : depth;
      if (remainingDepth === 0) {
        return stringified.replace("object ", "");
      }
      if (memoize2(value)) {
        return "[Circular ~]";
      }
      const valueWithToJSON = value;
      if (valueWithToJSON && typeof valueWithToJSON.toJSON === "function") {
        try {
          const jsonValue = valueWithToJSON.toJSON();
          return visit("", jsonValue, remainingDepth - 1, maxProperties, memo$1);
        } catch (err) {
        }
      }
      const normalized = Array.isArray(value) ? [] : {};
      let numAdded = 0;
      const visitable = object.convertToPlainObject(value);
      for (const visitKey in visitable) {
        if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {
          continue;
        }
        if (numAdded >= maxProperties) {
          normalized[visitKey] = "[MaxProperties ~]";
          break;
        }
        const visitValue = visitable[visitKey];
        normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo$1);
        numAdded++;
      }
      unmemoize(value);
      return normalized;
    }
    function stringifyValue(key, value) {
      try {
        if (key === "domain" && value && typeof value === "object" && value._events) {
          return "[Domain]";
        }
        if (key === "domainEmitter") {
          return "[DomainEmitter]";
        }
        if (typeof global !== "undefined" && value === global) {
          return "[Global]";
        }
        if (typeof window !== "undefined" && value === window) {
          return "[Window]";
        }
        if (typeof document !== "undefined" && value === document) {
          return "[Document]";
        }
        if (is.isVueViewModel(value)) {
          return "[VueViewModel]";
        }
        if (is.isSyntheticEvent(value)) {
          return "[SyntheticEvent]";
        }
        if (typeof value === "number" && value !== value) {
          return "[NaN]";
        }
        if (typeof value === "function") {
          return `[Function: ${stacktrace.getFunctionName(value)}]`;
        }
        if (typeof value === "symbol") {
          return `[${String(value)}]`;
        }
        if (typeof value === "bigint") {
          return `[BigInt: ${String(value)}]`;
        }
        const objName = getConstructorName(value);
        if (/^HTML(\w*)Element$/.test(objName)) {
          return `[HTMLElement: ${objName}]`;
        }
        return `[object ${objName}]`;
      } catch (err) {
        return `**non-serializable** (${err})`;
      }
    }
    function getConstructorName(value) {
      const prototype = Object.getPrototypeOf(value);
      return prototype ? prototype.constructor.name : "null prototype";
    }
    function utf8Length(value) {
      return ~-encodeURI(value).split(/%..|./).length;
    }
    function jsonSize(value) {
      return utf8Length(JSON.stringify(value));
    }
    function normalizeUrlToBase(url, basePath) {
      const escapedBase = basePath.replace(/\\/g, "/").replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
      let newUrl = url;
      try {
        newUrl = decodeURI(url);
      } catch (_Oo) {
      }
      return newUrl.replace(/\\/g, "/").replace(/webpack:\/?/g, "").replace(new RegExp(`(file://)?/*${escapedBase}/*`, "ig"), "app:///");
    }
    exports.normalize = normalize;
    exports.normalizeToSize = normalizeToSize;
    exports.normalizeUrlToBase = normalizeUrlToBase;
    exports.walk = visit;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/path.js
var require_path = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/path.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    function normalizeArray(parts, allowAboveRoot) {
      let up = 0;
      for (let i2 = parts.length - 1; i2 >= 0; i2--) {
        const last = parts[i2];
        if (last === ".") {
          parts.splice(i2, 1);
        } else if (last === "..") {
          parts.splice(i2, 1);
          up++;
        } else if (up) {
          parts.splice(i2, 1);
          up--;
        }
      }
      if (allowAboveRoot) {
        for (; up--; up) {
          parts.unshift("..");
        }
      }
      return parts;
    }
    var splitPathRe = /^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/;
    function splitPath(filename) {
      const truncated = filename.length > 1024 ? `<truncated>${filename.slice(-1024)}` : filename;
      const parts = splitPathRe.exec(truncated);
      return parts ? parts.slice(1) : [];
    }
    function resolve2(...args) {
      let resolvedPath = "";
      let resolvedAbsolute = false;
      for (let i2 = args.length - 1; i2 >= -1 && !resolvedAbsolute; i2--) {
        const path2 = i2 >= 0 ? args[i2] : "/";
        if (!path2) {
          continue;
        }
        resolvedPath = `${path2}/${resolvedPath}`;
        resolvedAbsolute = path2.charAt(0) === "/";
      }
      resolvedPath = normalizeArray(
        resolvedPath.split("/").filter((p3) => !!p3),
        !resolvedAbsolute
      ).join("/");
      return (resolvedAbsolute ? "/" : "") + resolvedPath || ".";
    }
    function trim4(arr) {
      let start = 0;
      for (; start < arr.length; start++) {
        if (arr[start] !== "") {
          break;
        }
      }
      let end = arr.length - 1;
      for (; end >= 0; end--) {
        if (arr[end] !== "") {
          break;
        }
      }
      if (start > end) {
        return [];
      }
      return arr.slice(start, end - start + 1);
    }
    function relative(from, to) {
      from = resolve2(from).slice(1);
      to = resolve2(to).slice(1);
      const fromParts = trim4(from.split("/"));
      const toParts = trim4(to.split("/"));
      const length = Math.min(fromParts.length, toParts.length);
      let samePartsLength = length;
      for (let i2 = 0; i2 < length; i2++) {
        if (fromParts[i2] !== toParts[i2]) {
          samePartsLength = i2;
          break;
        }
      }
      let outputParts = [];
      for (let i2 = samePartsLength; i2 < fromParts.length; i2++) {
        outputParts.push("..");
      }
      outputParts = outputParts.concat(toParts.slice(samePartsLength));
      return outputParts.join("/");
    }
    function normalizePath(path2) {
      const isPathAbsolute = isAbsolute(path2);
      const trailingSlash = path2.slice(-1) === "/";
      let normalizedPath = normalizeArray(
        path2.split("/").filter((p3) => !!p3),
        !isPathAbsolute
      ).join("/");
      if (!normalizedPath && !isPathAbsolute) {
        normalizedPath = ".";
      }
      if (normalizedPath && trailingSlash) {
        normalizedPath += "/";
      }
      return (isPathAbsolute ? "/" : "") + normalizedPath;
    }
    function isAbsolute(path2) {
      return path2.charAt(0) === "/";
    }
    function join(...args) {
      return normalizePath(args.join("/"));
    }
    function dirname(path2) {
      const result = splitPath(path2);
      const root = result[0];
      let dir = result[1];
      if (!root && !dir) {
        return ".";
      }
      if (dir) {
        dir = dir.slice(0, dir.length - 1);
      }
      return root + dir;
    }
    function basename(path2, ext) {
      let f2 = splitPath(path2)[2];
      if (ext && f2.slice(ext.length * -1) === ext) {
        f2 = f2.slice(0, f2.length - ext.length);
      }
      return f2;
    }
    exports.basename = basename;
    exports.dirname = dirname;
    exports.isAbsolute = isAbsolute;
    exports.join = join;
    exports.normalizePath = normalizePath;
    exports.relative = relative;
    exports.resolve = resolve2;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/syncpromise.js
var require_syncpromise = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/syncpromise.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var is = require_is();
    var States;
    (function(States2) {
      const PENDING = 0;
      States2[States2["PENDING"] = PENDING] = "PENDING";
      const RESOLVED = 1;
      States2[States2["RESOLVED"] = RESOLVED] = "RESOLVED";
      const REJECTED = 2;
      States2[States2["REJECTED"] = REJECTED] = "REJECTED";
    })(States || (States = {}));
    function resolvedSyncPromise(value) {
      return new SyncPromise((resolve2) => {
        resolve2(value);
      });
    }
    function rejectedSyncPromise(reason) {
      return new SyncPromise((_3, reject) => {
        reject(reason);
      });
    }
    var SyncPromise = class _SyncPromise {
      constructor(executor) {
        _SyncPromise.prototype.__init.call(this);
        _SyncPromise.prototype.__init2.call(this);
        _SyncPromise.prototype.__init3.call(this);
        _SyncPromise.prototype.__init4.call(this);
        this._state = States.PENDING;
        this._handlers = [];
        try {
          executor(this._resolve, this._reject);
        } catch (e2) {
          this._reject(e2);
        }
      }
      /** JSDoc */
      then(onfulfilled, onrejected) {
        return new _SyncPromise((resolve2, reject) => {
          this._handlers.push([
            false,
            (result) => {
              if (!onfulfilled) {
                resolve2(result);
              } else {
                try {
                  resolve2(onfulfilled(result));
                } catch (e2) {
                  reject(e2);
                }
              }
            },
            (reason) => {
              if (!onrejected) {
                reject(reason);
              } else {
                try {
                  resolve2(onrejected(reason));
                } catch (e2) {
                  reject(e2);
                }
              }
            }
          ]);
          this._executeHandlers();
        });
      }
      /** JSDoc */
      catch(onrejected) {
        return this.then((val) => val, onrejected);
      }
      /** JSDoc */
      finally(onfinally) {
        return new _SyncPromise((resolve2, reject) => {
          let val;
          let isRejected;
          return this.then(
            (value) => {
              isRejected = false;
              val = value;
              if (onfinally) {
                onfinally();
              }
            },
            (reason) => {
              isRejected = true;
              val = reason;
              if (onfinally) {
                onfinally();
              }
            }
          ).then(() => {
            if (isRejected) {
              reject(val);
              return;
            }
            resolve2(val);
          });
        });
      }
      /** JSDoc */
      __init() {
        this._resolve = (value) => {
          this._setResult(States.RESOLVED, value);
        };
      }
      /** JSDoc */
      __init2() {
        this._reject = (reason) => {
          this._setResult(States.REJECTED, reason);
        };
      }
      /** JSDoc */
      __init3() {
        this._setResult = (state, value) => {
          if (this._state !== States.PENDING) {
            return;
          }
          if (is.isThenable(value)) {
            void value.then(this._resolve, this._reject);
            return;
          }
          this._state = state;
          this._value = value;
          this._executeHandlers();
        };
      }
      /** JSDoc */
      __init4() {
        this._executeHandlers = () => {
          if (this._state === States.PENDING) {
            return;
          }
          const cachedHandlers = this._handlers.slice();
          this._handlers = [];
          cachedHandlers.forEach((handler) => {
            if (handler[0]) {
              return;
            }
            if (this._state === States.RESOLVED) {
              handler[1](this._value);
            }
            if (this._state === States.REJECTED) {
              handler[2](this._value);
            }
            handler[0] = true;
          });
        };
      }
    };
    exports.SyncPromise = SyncPromise;
    exports.rejectedSyncPromise = rejectedSyncPromise;
    exports.resolvedSyncPromise = resolvedSyncPromise;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/promisebuffer.js
var require_promisebuffer = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/promisebuffer.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var error = require_error2();
    var syncpromise = require_syncpromise();
    function makePromiseBuffer(limit) {
      const buffer = [];
      function isReady() {
        return limit === void 0 || buffer.length < limit;
      }
      function remove(task) {
        return buffer.splice(buffer.indexOf(task), 1)[0];
      }
      function add(taskProducer) {
        if (!isReady()) {
          return syncpromise.rejectedSyncPromise(new error.SentryError("Not adding Promise because buffer limit was reached."));
        }
        const task = taskProducer();
        if (buffer.indexOf(task) === -1) {
          buffer.push(task);
        }
        void task.then(() => remove(task)).then(
          null,
          () => remove(task).then(null, () => {
          })
        );
        return task;
      }
      function drain(timeout) {
        return new syncpromise.SyncPromise((resolve2, reject) => {
          let counter = buffer.length;
          if (!counter) {
            return resolve2(true);
          }
          const capturedSetTimeout = setTimeout(() => {
            if (timeout && timeout > 0) {
              resolve2(false);
            }
          }, timeout);
          buffer.forEach((item) => {
            void syncpromise.resolvedSyncPromise(item).then(() => {
              if (!--counter) {
                clearTimeout(capturedSetTimeout);
                resolve2(true);
              }
            }, reject);
          });
        });
      }
      return {
        $: buffer,
        add,
        drain
      };
    }
    exports.makePromiseBuffer = makePromiseBuffer;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/cookie.js
var require_cookie = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/cookie.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    function parseCookie(str) {
      const obj = {};
      let index = 0;
      while (index < str.length) {
        const eqIdx = str.indexOf("=", index);
        if (eqIdx === -1) {
          break;
        }
        let endIdx = str.indexOf(";", index);
        if (endIdx === -1) {
          endIdx = str.length;
        } else if (endIdx < eqIdx) {
          index = str.lastIndexOf(";", eqIdx - 1) + 1;
          continue;
        }
        const key = str.slice(index, eqIdx).trim();
        if (void 0 === obj[key]) {
          let val = str.slice(eqIdx + 1, endIdx).trim();
          if (val.charCodeAt(0) === 34) {
            val = val.slice(1, -1);
          }
          try {
            obj[key] = val.indexOf("%") !== -1 ? decodeURIComponent(val) : val;
          } catch (e2) {
            obj[key] = val;
          }
        }
        index = endIdx + 1;
      }
      return obj;
    }
    exports.parseCookie = parseCookie;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/url.js
var require_url = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/url.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    function parseUrl(url) {
      if (!url) {
        return {};
      }
      const match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);
      if (!match) {
        return {};
      }
      const query = match[6] || "";
      const fragment = match[8] || "";
      return {
        host: match[4],
        path: match[5],
        protocol: match[2],
        search: query,
        hash: fragment,
        relative: match[5] + query + fragment
        // everything minus origin
      };
    }
    function stripUrlQueryAndFragment(urlPath) {
      return urlPath.split(/[\?#]/, 1)[0];
    }
    function getNumberOfUrlSegments(url) {
      return url.split(/\\?\//).filter((s2) => s2.length > 0 && s2 !== ",").length;
    }
    function getSanitizedUrlString(url) {
      const { protocol, host, path: path2 } = url;
      const filteredHost = host && host.replace(/^.*@/, "[filtered]:[filtered]@").replace(/(:80)$/, "").replace(/(:443)$/, "") || "";
      return `${protocol ? `${protocol}://` : ""}${filteredHost}${path2}`;
    }
    exports.getNumberOfUrlSegments = getNumberOfUrlSegments;
    exports.getSanitizedUrlString = getSanitizedUrlString;
    exports.parseUrl = parseUrl;
    exports.stripUrlQueryAndFragment = stripUrlQueryAndFragment;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/requestdata.js
var require_requestdata = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/requestdata.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var cookie = require_cookie();
    var debugBuild = require_debug_build();
    var is = require_is();
    var logger = require_logger();
    var normalize = require_normalize();
    var url = require_url();
    var DEFAULT_INCLUDES = {
      ip: false,
      request: true,
      transaction: true,
      user: true
    };
    var DEFAULT_REQUEST_INCLUDES = ["cookies", "data", "headers", "method", "query_string", "url"];
    var DEFAULT_USER_INCLUDES = ["id", "username", "email"];
    function addRequestDataToTransaction(transaction, req, deps) {
      if (!transaction)
        return;
      if (!transaction.metadata.source || transaction.metadata.source === "url") {
        const [name, source] = extractPathForTransaction(req, { path: true, method: true });
        transaction.updateName(name);
        transaction.setMetadata({ source });
      }
      transaction.setAttribute("url", req.originalUrl || req.url);
      if (req.baseUrl) {
        transaction.setAttribute("baseUrl", req.baseUrl);
      }
      transaction.setData("query", extractQueryParams(req, deps));
    }
    function extractPathForTransaction(req, options = {}) {
      const method = req.method && req.method.toUpperCase();
      let path2 = "";
      let source = "url";
      if (options.customRoute || req.route) {
        path2 = options.customRoute || `${req.baseUrl || ""}${req.route && req.route.path}`;
        source = "route";
      } else if (req.originalUrl || req.url) {
        path2 = url.stripUrlQueryAndFragment(req.originalUrl || req.url || "");
      }
      let name = "";
      if (options.method && method) {
        name += method;
      }
      if (options.method && options.path) {
        name += " ";
      }
      if (options.path && path2) {
        name += path2;
      }
      return [name, source];
    }
    function extractTransaction(req, type) {
      switch (type) {
        case "path": {
          return extractPathForTransaction(req, { path: true })[0];
        }
        case "handler": {
          return req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name || "<anonymous>";
        }
        case "methodPath":
        default: {
          const customRoute = req._reconstructedRoute ? req._reconstructedRoute : void 0;
          return extractPathForTransaction(req, { path: true, method: true, customRoute })[0];
        }
      }
    }
    function extractUserData(user, keys) {
      const extractedUser = {};
      const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES;
      attributes.forEach((key) => {
        if (user && key in user) {
          extractedUser[key] = user[key];
        }
      });
      return extractedUser;
    }
    function extractRequestData(req, options) {
      const { include = DEFAULT_REQUEST_INCLUDES, deps } = options || {};
      const requestData = {};
      const headers = req.headers || {};
      const method = req.method;
      const host = headers.host || req.hostname || req.host || "<no host>";
      const protocol = req.protocol === "https" || req.socket && req.socket.encrypted ? "https" : "http";
      const originalUrl = req.originalUrl || req.url || "";
      const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`;
      include.forEach((key) => {
        switch (key) {
          case "headers": {
            requestData.headers = headers;
            if (!include.includes("cookies")) {
              delete requestData.headers.cookie;
            }
            break;
          }
          case "method": {
            requestData.method = method;
            break;
          }
          case "url": {
            requestData.url = absoluteUrl;
            break;
          }
          case "cookies": {
            requestData.cookies = // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can
            // come off in v8
            req.cookies || headers.cookie && cookie.parseCookie(headers.cookie) || {};
            break;
          }
          case "query_string": {
            requestData.query_string = extractQueryParams(req, deps);
            break;
          }
          case "data": {
            if (method === "GET" || method === "HEAD") {
              break;
            }
            if (req.body !== void 0) {
              requestData.data = is.isString(req.body) ? req.body : JSON.stringify(normalize.normalize(req.body));
            }
            break;
          }
          default: {
            if ({}.hasOwnProperty.call(req, key)) {
              requestData[key] = req[key];
            }
          }
        }
      });
      return requestData;
    }
    function addRequestDataToEvent(event, req, options) {
      const include = {
        ...DEFAULT_INCLUDES,
        ...options && options.include
      };
      if (include.request) {
        const extractedRequestData = Array.isArray(include.request) ? extractRequestData(req, { include: include.request, deps: options && options.deps }) : extractRequestData(req, { deps: options && options.deps });
        event.request = {
          ...event.request,
          ...extractedRequestData
        };
      }
      if (include.user) {
        const extractedUser = req.user && is.isPlainObject(req.user) ? extractUserData(req.user, include.user) : {};
        if (Object.keys(extractedUser).length) {
          event.user = {
            ...event.user,
            ...extractedUser
          };
        }
      }
      if (include.ip) {
        const ip = req.ip || req.socket && req.socket.remoteAddress;
        if (ip) {
          event.user = {
            ...event.user,
            ip_address: ip
          };
        }
      }
      if (include.transaction && !event.transaction) {
        event.transaction = extractTransaction(req, include.transaction);
      }
      return event;
    }
    function extractQueryParams(req, deps) {
      let originalUrl = req.originalUrl || req.url || "";
      if (!originalUrl) {
        return;
      }
      if (originalUrl.startsWith("/")) {
        originalUrl = `http://dogs.are.great${originalUrl}`;
      }
      try {
        return req.query || typeof URL !== "undefined" && new URL(originalUrl).search.slice(1) || // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node
        deps && deps.url && deps.url.parse(originalUrl).query || void 0;
      } catch (e2) {
        return void 0;
      }
    }
    function winterCGHeadersToDict(winterCGHeaders) {
      const headers = {};
      try {
        winterCGHeaders.forEach((value, key) => {
          if (typeof value === "string") {
            headers[key] = value;
          }
        });
      } catch (e2) {
        debugBuild.DEBUG_BUILD && logger.logger.warn("Sentry failed extracting headers from a request object. If you see this, please file an issue.");
      }
      return headers;
    }
    function winterCGRequestToRequestData(req) {
      const headers = winterCGHeadersToDict(req.headers);
      return {
        method: req.method,
        url: req.url,
        headers
      };
    }
    exports.DEFAULT_USER_INCLUDES = DEFAULT_USER_INCLUDES;
    exports.addRequestDataToEvent = addRequestDataToEvent;
    exports.addRequestDataToTransaction = addRequestDataToTransaction;
    exports.extractPathForTransaction = extractPathForTransaction;
    exports.extractRequestData = extractRequestData;
    exports.winterCGHeadersToDict = winterCGHeadersToDict;
    exports.winterCGRequestToRequestData = winterCGRequestToRequestData;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/severity.js
var require_severity = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/severity.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var validSeverityLevels = ["fatal", "error", "warning", "log", "info", "debug"];
    function severityFromString(level) {
      return severityLevelFromString(level);
    }
    function severityLevelFromString(level) {
      return level === "warn" ? "warning" : validSeverityLevels.includes(level) ? level : "log";
    }
    exports.severityFromString = severityFromString;
    exports.severityLevelFromString = severityLevelFromString;
    exports.validSeverityLevels = validSeverityLevels;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/time.js
var require_time = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/time.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var worldwide = require_worldwide();
    var ONE_SECOND_IN_MS = 1e3;
    function dateTimestampInSeconds() {
      return Date.now() / ONE_SECOND_IN_MS;
    }
    function createUnixTimestampInSecondsFunc() {
      const { performance: performance2 } = worldwide.GLOBAL_OBJ;
      if (!performance2 || !performance2.now) {
        return dateTimestampInSeconds;
      }
      const approxStartingTimeOrigin = Date.now() - performance2.now();
      const timeOrigin = performance2.timeOrigin == void 0 ? approxStartingTimeOrigin : performance2.timeOrigin;
      return () => {
        return (timeOrigin + performance2.now()) / ONE_SECOND_IN_MS;
      };
    }
    var timestampInSeconds = createUnixTimestampInSecondsFunc();
    var timestampWithMs = timestampInSeconds;
    exports._browserPerformanceTimeOriginMode = void 0;
    var browserPerformanceTimeOrigin = (() => {
      const { performance: performance2 } = worldwide.GLOBAL_OBJ;
      if (!performance2 || !performance2.now) {
        exports._browserPerformanceTimeOriginMode = "none";
        return void 0;
      }
      const threshold = 3600 * 1e3;
      const performanceNow2 = performance2.now();
      const dateNow = Date.now();
      const timeOriginDelta = performance2.timeOrigin ? Math.abs(performance2.timeOrigin + performanceNow2 - dateNow) : threshold;
      const timeOriginIsReliable = timeOriginDelta < threshold;
      const navigationStart = performance2.timing && performance2.timing.navigationStart;
      const hasNavigationStart = typeof navigationStart === "number";
      const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow2 - dateNow) : threshold;
      const navigationStartIsReliable = navigationStartDelta < threshold;
      if (timeOriginIsReliable || navigationStartIsReliable) {
        if (timeOriginDelta <= navigationStartDelta) {
          exports._browserPerformanceTimeOriginMode = "timeOrigin";
          return performance2.timeOrigin;
        } else {
          exports._browserPerformanceTimeOriginMode = "navigationStart";
          return navigationStart;
        }
      }
      exports._browserPerformanceTimeOriginMode = "dateNow";
      return dateNow;
    })();
    exports.browserPerformanceTimeOrigin = browserPerformanceTimeOrigin;
    exports.dateTimestampInSeconds = dateTimestampInSeconds;
    exports.timestampInSeconds = timestampInSeconds;
    exports.timestampWithMs = timestampWithMs;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/baggage.js
var require_baggage = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/baggage.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var debugBuild = require_debug_build();
    var is = require_is();
    var logger = require_logger();
    var BAGGAGE_HEADER_NAME = "baggage";
    var SENTRY_BAGGAGE_KEY_PREFIX = "sentry-";
    var SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;
    var MAX_BAGGAGE_STRING_LENGTH = 8192;
    function baggageHeaderToDynamicSamplingContext(baggageHeader) {
      if (!is.isString(baggageHeader) && !Array.isArray(baggageHeader)) {
        return void 0;
      }
      let baggageObject = {};
      if (Array.isArray(baggageHeader)) {
        baggageObject = baggageHeader.reduce((acc, curr) => {
          const currBaggageObject = baggageHeaderToObject(curr);
          for (const key of Object.keys(currBaggageObject)) {
            acc[key] = currBaggageObject[key];
          }
          return acc;
        }, {});
      } else {
        if (!baggageHeader) {
          return void 0;
        }
        baggageObject = baggageHeaderToObject(baggageHeader);
      }
      const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => {
        if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {
          const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);
          acc[nonPrefixedKey] = value;
        }
        return acc;
      }, {});
      if (Object.keys(dynamicSamplingContext).length > 0) {
        return dynamicSamplingContext;
      } else {
        return void 0;
      }
    }
    function dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext) {
      if (!dynamicSamplingContext) {
        return void 0;
      }
      const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce(
        (acc, [dscKey, dscValue]) => {
          if (dscValue) {
            acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;
          }
          return acc;
        },
        {}
      );
      return objectToBaggageHeader(sentryPrefixedDSC);
    }
    function baggageHeaderToObject(baggageHeader) {
      return baggageHeader.split(",").map((baggageEntry) => baggageEntry.split("=").map((keyOrValue) => decodeURIComponent(keyOrValue.trim()))).reduce((acc, [key, value]) => {
        acc[key] = value;
        return acc;
      }, {});
    }
    function objectToBaggageHeader(object) {
      if (Object.keys(object).length === 0) {
        return void 0;
      }
      return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {
        const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;
        const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;
        if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {
          debugBuild.DEBUG_BUILD && logger.logger.warn(
            `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`
          );
          return baggageHeader;
        } else {
          return newBaggageHeader;
        }
      }, "");
    }
    exports.BAGGAGE_HEADER_NAME = BAGGAGE_HEADER_NAME;
    exports.MAX_BAGGAGE_STRING_LENGTH = MAX_BAGGAGE_STRING_LENGTH;
    exports.SENTRY_BAGGAGE_KEY_PREFIX = SENTRY_BAGGAGE_KEY_PREFIX;
    exports.SENTRY_BAGGAGE_KEY_PREFIX_REGEX = SENTRY_BAGGAGE_KEY_PREFIX_REGEX;
    exports.baggageHeaderToDynamicSamplingContext = baggageHeaderToDynamicSamplingContext;
    exports.dynamicSamplingContextToSentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/tracing.js
var require_tracing = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/tracing.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var baggage = require_baggage();
    var misc = require_misc();
    var TRACEPARENT_REGEXP = new RegExp(
      "^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$"
      // whitespace
    );
    function extractTraceparentData(traceparent) {
      if (!traceparent) {
        return void 0;
      }
      const matches = traceparent.match(TRACEPARENT_REGEXP);
      if (!matches) {
        return void 0;
      }
      let parentSampled;
      if (matches[3] === "1") {
        parentSampled = true;
      } else if (matches[3] === "0") {
        parentSampled = false;
      }
      return {
        traceId: matches[1],
        parentSampled,
        parentSpanId: matches[2]
      };
    }
    function tracingContextFromHeaders(sentryTrace, baggage$1) {
      const traceparentData = extractTraceparentData(sentryTrace);
      const dynamicSamplingContext = baggage.baggageHeaderToDynamicSamplingContext(baggage$1);
      const { traceId, parentSpanId, parentSampled } = traceparentData || {};
      if (!traceparentData) {
        return {
          traceparentData,
          dynamicSamplingContext: void 0,
          propagationContext: {
            traceId: traceId || misc.uuid4(),
            spanId: misc.uuid4().substring(16)
          }
        };
      } else {
        return {
          traceparentData,
          dynamicSamplingContext: dynamicSamplingContext || {},
          // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it
          propagationContext: {
            traceId: traceId || misc.uuid4(),
            parentSpanId: parentSpanId || misc.uuid4().substring(16),
            spanId: misc.uuid4().substring(16),
            sampled: parentSampled,
            dsc: dynamicSamplingContext || {}
            // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it
          }
        };
      }
    }
    function propagationContextFromHeaders(sentryTrace, baggage$1) {
      const traceparentData = extractTraceparentData(sentryTrace);
      const dynamicSamplingContext = baggage.baggageHeaderToDynamicSamplingContext(baggage$1);
      const { traceId, parentSpanId, parentSampled } = traceparentData || {};
      if (!traceparentData) {
        return {
          traceId: traceId || misc.uuid4(),
          spanId: misc.uuid4().substring(16)
        };
      } else {
        return {
          traceId: traceId || misc.uuid4(),
          parentSpanId: parentSpanId || misc.uuid4().substring(16),
          spanId: misc.uuid4().substring(16),
          sampled: parentSampled,
          dsc: dynamicSamplingContext || {}
          // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it
        };
      }
    }
    function generateSentryTraceHeader(traceId = misc.uuid4(), spanId = misc.uuid4().substring(16), sampled) {
      let sampledString = "";
      if (sampled !== void 0) {
        sampledString = sampled ? "-1" : "-0";
      }
      return `${traceId}-${spanId}${sampledString}`;
    }
    exports.TRACEPARENT_REGEXP = TRACEPARENT_REGEXP;
    exports.extractTraceparentData = extractTraceparentData;
    exports.generateSentryTraceHeader = generateSentryTraceHeader;
    exports.propagationContextFromHeaders = propagationContextFromHeaders;
    exports.tracingContextFromHeaders = tracingContextFromHeaders;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/envelope.js
var require_envelope = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/envelope.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var dsn = require_dsn();
    var normalize = require_normalize();
    var object = require_object();
    function createEnvelope(headers, items = []) {
      return [headers, items];
    }
    function addItemToEnvelope(envelope, newItem) {
      const [headers, items] = envelope;
      return [headers, [...items, newItem]];
    }
    function forEachEnvelopeItem(envelope, callback) {
      const envelopeItems = envelope[1];
      for (const envelopeItem of envelopeItems) {
        const envelopeItemType = envelopeItem[0].type;
        const result = callback(envelopeItem, envelopeItemType);
        if (result) {
          return true;
        }
      }
      return false;
    }
    function envelopeContainsItemType(envelope, types) {
      return forEachEnvelopeItem(envelope, (_3, type) => types.includes(type));
    }
    function encodeUTF8(input, textEncoder) {
      const utf8 = textEncoder || new TextEncoder();
      return utf8.encode(input);
    }
    function serializeEnvelope(envelope, textEncoder) {
      const [envHeaders, items] = envelope;
      let parts = JSON.stringify(envHeaders);
      function append(next) {
        if (typeof parts === "string") {
          parts = typeof next === "string" ? parts + next : [encodeUTF8(parts, textEncoder), next];
        } else {
          parts.push(typeof next === "string" ? encodeUTF8(next, textEncoder) : next);
        }
      }
      for (const item of items) {
        const [itemHeaders, payload] = item;
        append(`
${JSON.stringify(itemHeaders)}
`);
        if (typeof payload === "string" || payload instanceof Uint8Array) {
          append(payload);
        } else {
          let stringifiedPayload;
          try {
            stringifiedPayload = JSON.stringify(payload);
          } catch (e2) {
            stringifiedPayload = JSON.stringify(normalize.normalize(payload));
          }
          append(stringifiedPayload);
        }
      }
      return typeof parts === "string" ? parts : concatBuffers(parts);
    }
    function concatBuffers(buffers) {
      const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);
      const merged = new Uint8Array(totalLength);
      let offset = 0;
      for (const buffer of buffers) {
        merged.set(buffer, offset);
        offset += buffer.length;
      }
      return merged;
    }
    function parseEnvelope(env2, textEncoder, textDecoder) {
      let buffer = typeof env2 === "string" ? textEncoder.encode(env2) : env2;
      function readBinary(length) {
        const bin = buffer.subarray(0, length);
        buffer = buffer.subarray(length + 1);
        return bin;
      }
      function readJson() {
        let i2 = buffer.indexOf(10);
        if (i2 < 0) {
          i2 = buffer.length;
        }
        return JSON.parse(textDecoder.decode(readBinary(i2)));
      }
      const envelopeHeader = readJson();
      const items = [];
      while (buffer.length) {
        const itemHeader = readJson();
        const binaryLength = typeof itemHeader.length === "number" ? itemHeader.length : void 0;
        items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);
      }
      return [envelopeHeader, items];
    }
    function createAttachmentEnvelopeItem(attachment, textEncoder) {
      const buffer = typeof attachment.data === "string" ? encodeUTF8(attachment.data, textEncoder) : attachment.data;
      return [
        object.dropUndefinedKeys({
          type: "attachment",
          length: buffer.length,
          filename: attachment.filename,
          content_type: attachment.contentType,
          attachment_type: attachment.attachmentType
        }),
        buffer
      ];
    }
    var ITEM_TYPE_TO_DATA_CATEGORY_MAP = {
      session: "session",
      sessions: "session",
      attachment: "attachment",
      transaction: "transaction",
      event: "error",
      client_report: "internal",
      user_report: "default",
      profile: "profile",
      replay_event: "replay",
      replay_recording: "replay",
      check_in: "monitor",
      feedback: "feedback",
      span: "span",
      statsd: "metric_bucket"
    };
    function envelopeItemTypeToDataCategory(type) {
      return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];
    }
    function getSdkMetadataForEnvelopeHeader(metadataOrEvent) {
      if (!metadataOrEvent || !metadataOrEvent.sdk) {
        return;
      }
      const { name, version: version2 } = metadataOrEvent.sdk;
      return { name, version: version2 };
    }
    function createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn$1) {
      const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;
      return {
        event_id: event.event_id,
        sent_at: (/* @__PURE__ */ new Date()).toISOString(),
        ...sdkInfo && { sdk: sdkInfo },
        ...!!tunnel && dsn$1 && { dsn: dsn.dsnToString(dsn$1) },
        ...dynamicSamplingContext && {
          trace: object.dropUndefinedKeys({ ...dynamicSamplingContext })
        }
      };
    }
    exports.addItemToEnvelope = addItemToEnvelope;
    exports.createAttachmentEnvelopeItem = createAttachmentEnvelopeItem;
    exports.createEnvelope = createEnvelope;
    exports.createEventEnvelopeHeaders = createEventEnvelopeHeaders;
    exports.envelopeContainsItemType = envelopeContainsItemType;
    exports.envelopeItemTypeToDataCategory = envelopeItemTypeToDataCategory;
    exports.forEachEnvelopeItem = forEachEnvelopeItem;
    exports.getSdkMetadataForEnvelopeHeader = getSdkMetadataForEnvelopeHeader;
    exports.parseEnvelope = parseEnvelope;
    exports.serializeEnvelope = serializeEnvelope;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/clientreport.js
var require_clientreport = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/clientreport.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var envelope = require_envelope();
    var time = require_time();
    function createClientReportEnvelope(discarded_events, dsn, timestamp) {
      const clientReportItem = [
        { type: "client_report" },
        {
          timestamp: timestamp || time.dateTimestampInSeconds(),
          discarded_events
        }
      ];
      return envelope.createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);
    }
    exports.createClientReportEnvelope = createClientReportEnvelope;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/ratelimit.js
var require_ratelimit = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/ratelimit.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var DEFAULT_RETRY_AFTER = 60 * 1e3;
    function parseRetryAfterHeader(header, now = Date.now()) {
      const headerDelay = parseInt(`${header}`, 10);
      if (!isNaN(headerDelay)) {
        return headerDelay * 1e3;
      }
      const headerDate = Date.parse(`${header}`);
      if (!isNaN(headerDate)) {
        return headerDate - now;
      }
      return DEFAULT_RETRY_AFTER;
    }
    function disabledUntil(limits, dataCategory) {
      return limits[dataCategory] || limits.all || 0;
    }
    function isRateLimited(limits, dataCategory, now = Date.now()) {
      return disabledUntil(limits, dataCategory) > now;
    }
    function updateRateLimits(limits, { statusCode, headers }, now = Date.now()) {
      const updatedRateLimits = {
        ...limits
      };
      const rateLimitHeader = headers && headers["x-sentry-rate-limits"];
      const retryAfterHeader = headers && headers["retry-after"];
      if (rateLimitHeader) {
        for (const limit of rateLimitHeader.trim().split(",")) {
          const [retryAfter, categories, , , namespaces] = limit.split(":", 5);
          const headerDelay = parseInt(retryAfter, 10);
          const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1e3;
          if (!categories) {
            updatedRateLimits.all = now + delay;
          } else {
            for (const category of categories.split(";")) {
              if (category === "metric_bucket") {
                if (!namespaces || namespaces.split(";").includes("custom")) {
                  updatedRateLimits[category] = now + delay;
                }
              } else {
                updatedRateLimits[category] = now + delay;
              }
            }
          }
        }
      } else if (retryAfterHeader) {
        updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);
      } else if (statusCode === 429) {
        updatedRateLimits.all = now + 60 * 1e3;
      }
      return updatedRateLimits;
    }
    exports.DEFAULT_RETRY_AFTER = DEFAULT_RETRY_AFTER;
    exports.disabledUntil = disabledUntil;
    exports.isRateLimited = isRateLimited;
    exports.parseRetryAfterHeader = parseRetryAfterHeader;
    exports.updateRateLimits = updateRateLimits;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/userIntegrations.js
var require_userIntegrations = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/userIntegrations.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    function setNestedKey(obj, keyPath, value) {
      const match = keyPath.match(/([a-z_]+)\.(.*)/i);
      if (match === null) {
        obj[keyPath] = value;
      } else {
        const innerObj = obj[match[1]];
        setNestedKey(innerObj, match[2], value);
      }
    }
    function addOrUpdateIntegration(defaultIntegrationInstance, userIntegrations, forcedOptions = {}) {
      return Array.isArray(userIntegrations) ? addOrUpdateIntegrationInArray(defaultIntegrationInstance, userIntegrations, forcedOptions) : addOrUpdateIntegrationInFunction(
        defaultIntegrationInstance,
        // Somehow TS can't figure out that not being an array makes this necessarily a function
        userIntegrations,
        forcedOptions
      );
    }
    function addOrUpdateIntegrationInArray(defaultIntegrationInstance, userIntegrations, forcedOptions) {
      const userInstance = userIntegrations.find((integration) => integration.name === defaultIntegrationInstance.name);
      if (userInstance) {
        for (const [keyPath, value] of Object.entries(forcedOptions)) {
          setNestedKey(userInstance, keyPath, value);
        }
        return userIntegrations;
      }
      return [...userIntegrations, defaultIntegrationInstance];
    }
    function addOrUpdateIntegrationInFunction(defaultIntegrationInstance, userIntegrationsFunc, forcedOptions) {
      const wrapper = (defaultIntegrations) => {
        const userFinalIntegrations = userIntegrationsFunc(defaultIntegrations);
        if (defaultIntegrationInstance.allowExclusionByUser) {
          const userFinalInstance = userFinalIntegrations.find(
            (integration) => integration.name === defaultIntegrationInstance.name
          );
          if (!userFinalInstance) {
            return userFinalIntegrations;
          }
        }
        return addOrUpdateIntegrationInArray(defaultIntegrationInstance, userFinalIntegrations, forcedOptions);
      };
      return wrapper;
    }
    exports.addOrUpdateIntegration = addOrUpdateIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/cache.js
var require_cache = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/cache.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    function makeFifoCache(size) {
      let evictionOrder = [];
      let cache = {};
      return {
        add(key, value) {
          while (evictionOrder.length >= size) {
            const evictCandidate = evictionOrder.shift();
            if (evictCandidate !== void 0) {
              delete cache[evictCandidate];
            }
          }
          if (cache[key]) {
            this.delete(key);
          }
          evictionOrder.push(key);
          cache[key] = value;
        },
        clear() {
          cache = {};
          evictionOrder = [];
        },
        get(key) {
          return cache[key];
        },
        size() {
          return evictionOrder.length;
        },
        // Delete cache key and return true if it existed, false otherwise.
        delete(key) {
          if (!cache[key]) {
            return false;
          }
          delete cache[key];
          for (let i2 = 0; i2 < evictionOrder.length; i2++) {
            if (evictionOrder[i2] === key) {
              evictionOrder.splice(i2, 1);
              break;
            }
          }
          return true;
        }
      };
    }
    exports.makeFifoCache = makeFifoCache;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/eventbuilder.js
var require_eventbuilder = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/eventbuilder.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var is = require_is();
    var misc = require_misc();
    var normalize = require_normalize();
    var object = require_object();
    function parseStackFrames(stackParser, error) {
      return stackParser(error.stack || "", 1);
    }
    function exceptionFromError(stackParser, error) {
      const exception = {
        type: error.name || error.constructor.name,
        value: error.message
      };
      const frames = parseStackFrames(stackParser, error);
      if (frames.length) {
        exception.stacktrace = { frames };
      }
      return exception;
    }
    function getMessageForObject(exception) {
      if ("name" in exception && typeof exception.name === "string") {
        let message = `'${exception.name}' captured as exception`;
        if ("message" in exception && typeof exception.message === "string") {
          message += ` with message '${exception.message}'`;
        }
        return message;
      } else if ("message" in exception && typeof exception.message === "string") {
        return exception.message;
      } else {
        return `Object captured as exception with keys: ${object.extractExceptionKeysForMessage(
          exception
        )}`;
      }
    }
    function eventFromUnknownInput(getHubOrClient, stackParser, exception, hint) {
      const client = typeof getHubOrClient === "function" ? (
        // eslint-disable-next-line deprecation/deprecation
        getHubOrClient().getClient()
      ) : getHubOrClient;
      let ex = exception;
      const providedMechanism = hint && hint.data && hint.data.mechanism;
      const mechanism = providedMechanism || {
        handled: true,
        type: "generic"
      };
      let extras;
      if (!is.isError(exception)) {
        if (is.isPlainObject(exception)) {
          const normalizeDepth = client && client.getOptions().normalizeDepth;
          extras = { ["__serialized__"]: normalize.normalizeToSize(exception, normalizeDepth) };
          const message = getMessageForObject(exception);
          ex = hint && hint.syntheticException || new Error(message);
          ex.message = message;
        } else {
          ex = hint && hint.syntheticException || new Error(exception);
          ex.message = exception;
        }
        mechanism.synthetic = true;
      }
      const event = {
        exception: {
          values: [exceptionFromError(stackParser, ex)]
        }
      };
      if (extras) {
        event.extra = extras;
      }
      misc.addExceptionTypeValue(event, void 0, void 0);
      misc.addExceptionMechanism(event, mechanism);
      return {
        ...event,
        event_id: hint && hint.event_id
      };
    }
    function eventFromMessage(stackParser, message, level = "info", hint, attachStacktrace) {
      const event = {
        event_id: hint && hint.event_id,
        level
      };
      if (attachStacktrace && hint && hint.syntheticException) {
        const frames = parseStackFrames(stackParser, hint.syntheticException);
        if (frames.length) {
          event.exception = {
            values: [
              {
                value: message,
                stacktrace: { frames }
              }
            ]
          };
        }
      }
      if (is.isParameterizedString(message)) {
        const { __sentry_template_string__, __sentry_template_values__ } = message;
        event.logentry = {
          message: __sentry_template_string__,
          params: __sentry_template_values__
        };
        return event;
      }
      event.message = message;
      return event;
    }
    exports.eventFromMessage = eventFromMessage;
    exports.eventFromUnknownInput = eventFromUnknownInput;
    exports.exceptionFromError = exceptionFromError;
    exports.parseStackFrames = parseStackFrames;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/anr.js
var require_anr = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/anr.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var object = require_object();
    var nodeStackTrace = require_node_stack_trace();
    function watchdogTimer(createTimer, pollInterval, anrThreshold, callback) {
      const timer = createTimer();
      let triggered = false;
      let enabled = true;
      setInterval(() => {
        const diffMs = timer.getTimeMs();
        if (triggered === false && diffMs > pollInterval + anrThreshold) {
          triggered = true;
          if (enabled) {
            callback();
          }
        }
        if (diffMs < pollInterval + anrThreshold) {
          triggered = false;
        }
      }, 20);
      return {
        poll: () => {
          timer.reset();
        },
        enabled: (state) => {
          enabled = state;
        }
      };
    }
    function callFrameToStackFrame(frame, url, getModuleFromFilename) {
      const filename = url ? url.replace(/^file:\/\//, "") : void 0;
      const colno = frame.location.columnNumber ? frame.location.columnNumber + 1 : void 0;
      const lineno = frame.location.lineNumber ? frame.location.lineNumber + 1 : void 0;
      return object.dropUndefinedKeys({
        filename,
        module: getModuleFromFilename(filename),
        function: frame.functionName || "?",
        colno,
        lineno,
        in_app: filename ? nodeStackTrace.filenameIsInApp(filename) : void 0
      });
    }
    exports.callFrameToStackFrame = callFrameToStackFrame;
    exports.watchdogTimer = watchdogTimer;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/lru.js
var require_lru = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/lru.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var LRUMap = class {
      constructor(_maxSize) {
        this._maxSize = _maxSize;
        this._cache = /* @__PURE__ */ new Map();
      }
      /** Get the current size of the cache */
      get size() {
        return this._cache.size;
      }
      /** Get an entry or undefined if it was not in the cache. Re-inserts to update the recently used order */
      get(key) {
        const value = this._cache.get(key);
        if (value === void 0) {
          return void 0;
        }
        this._cache.delete(key);
        this._cache.set(key, value);
        return value;
      }
      /** Insert an entry and evict an older entry if we've reached maxSize */
      set(key, value) {
        if (this._cache.size >= this._maxSize) {
          this._cache.delete(this._cache.keys().next().value);
        }
        this._cache.set(key, value);
      }
      /** Remove an entry and return the entry if it was in the cache */
      remove(key) {
        const value = this._cache.get(key);
        if (value) {
          this._cache.delete(key);
        }
        return value;
      }
      /** Clear all entries */
      clear() {
        this._cache.clear();
      }
      /** Get all the keys */
      keys() {
        return Array.from(this._cache.keys());
      }
      /** Get all the values */
      values() {
        const values = [];
        this._cache.forEach((value) => values.push(value));
        return values;
      }
    };
    exports.LRUMap = LRUMap;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/buildPolyfills/_nullishCoalesce.js
var require_nullishCoalesce = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/buildPolyfills/_nullishCoalesce.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    function _nullishCoalesce(lhs, rhsFn) {
      return lhs != null ? lhs : rhsFn();
    }
    exports._nullishCoalesce = _nullishCoalesce;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/buildPolyfills/_asyncNullishCoalesce.js
var require_asyncNullishCoalesce = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/buildPolyfills/_asyncNullishCoalesce.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var _nullishCoalesce = require_nullishCoalesce();
    async function _asyncNullishCoalesce(lhs, rhsFn) {
      return _nullishCoalesce._nullishCoalesce(lhs, rhsFn);
    }
    exports._asyncNullishCoalesce = _asyncNullishCoalesce;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/buildPolyfills/_asyncOptionalChain.js
var require_asyncOptionalChain = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/buildPolyfills/_asyncOptionalChain.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    async function _asyncOptionalChain(ops) {
      let lastAccessLHS = void 0;
      let value = ops[0];
      let i2 = 1;
      while (i2 < ops.length) {
        const op = ops[i2];
        const fn = ops[i2 + 1];
        i2 += 2;
        if ((op === "optionalAccess" || op === "optionalCall") && value == null) {
          return;
        }
        if (op === "access" || op === "optionalAccess") {
          lastAccessLHS = value;
          value = await fn(value);
        } else if (op === "call" || op === "optionalCall") {
          value = await fn((...args) => value.call(lastAccessLHS, ...args));
          lastAccessLHS = void 0;
        }
      }
      return value;
    }
    exports._asyncOptionalChain = _asyncOptionalChain;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/buildPolyfills/_asyncOptionalChainDelete.js
var require_asyncOptionalChainDelete = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/buildPolyfills/_asyncOptionalChainDelete.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var _asyncOptionalChain = require_asyncOptionalChain();
    async function _asyncOptionalChainDelete(ops) {
      const result = await _asyncOptionalChain._asyncOptionalChain(ops);
      return result == null ? true : result;
    }
    exports._asyncOptionalChainDelete = _asyncOptionalChainDelete;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/buildPolyfills/_optionalChain.js
var require_optionalChain = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/buildPolyfills/_optionalChain.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    function _optionalChain(ops) {
      let lastAccessLHS = void 0;
      let value = ops[0];
      let i2 = 1;
      while (i2 < ops.length) {
        const op = ops[i2];
        const fn = ops[i2 + 1];
        i2 += 2;
        if ((op === "optionalAccess" || op === "optionalCall") && value == null) {
          return;
        }
        if (op === "access" || op === "optionalAccess") {
          lastAccessLHS = value;
          value = fn(value);
        } else if (op === "call" || op === "optionalCall") {
          value = fn((...args) => value.call(lastAccessLHS, ...args));
          lastAccessLHS = void 0;
        }
      }
      return value;
    }
    exports._optionalChain = _optionalChain;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/buildPolyfills/_optionalChainDelete.js
var require_optionalChainDelete = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/buildPolyfills/_optionalChainDelete.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var _optionalChain = require_optionalChain();
    function _optionalChainDelete(ops) {
      const result = _optionalChain._optionalChain(ops);
      return result == null ? true : result;
    }
    exports._optionalChainDelete = _optionalChainDelete;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/vendor/escapeStringForRegex.js
var require_escapeStringForRegex = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/vendor/escapeStringForRegex.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    function escapeStringForRegex(regexString) {
      return regexString.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d");
    }
    exports.escapeStringForRegex = escapeStringForRegex;
  }
});

// ../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/index.js
var require_cjs = __commonJS({
  "../../node_modules/.pnpm/@sentry+utils@7.120.3/node_modules/@sentry/utils/cjs/index.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var aggregateErrors = require_aggregate_errors();
    var browser = require_browser();
    var dsn = require_dsn();
    var error = require_error2();
    var worldwide = require_worldwide();
    var index = require_instrument();
    var is = require_is();
    var isBrowser = require_isBrowser();
    var logger = require_logger();
    var memo = require_memo();
    var misc = require_misc();
    var node = require_node();
    var normalize = require_normalize();
    var object = require_object();
    var path2 = require_path();
    var promisebuffer = require_promisebuffer();
    var requestdata = require_requestdata();
    var severity = require_severity();
    var stacktrace = require_stacktrace();
    var string = require_string();
    var supports = require_supports();
    var syncpromise = require_syncpromise();
    var time = require_time();
    var tracing = require_tracing();
    var env2 = require_env();
    var envelope = require_envelope();
    var clientreport = require_clientreport();
    var ratelimit = require_ratelimit();
    var baggage = require_baggage();
    var url = require_url();
    var userIntegrations = require_userIntegrations();
    var cache = require_cache();
    var eventbuilder = require_eventbuilder();
    var anr = require_anr();
    var lru = require_lru();
    var _asyncNullishCoalesce = require_asyncNullishCoalesce();
    var _asyncOptionalChain = require_asyncOptionalChain();
    var _asyncOptionalChainDelete = require_asyncOptionalChainDelete();
    var _nullishCoalesce = require_nullishCoalesce();
    var _optionalChain = require_optionalChain();
    var _optionalChainDelete = require_optionalChainDelete();
    var console2 = require_console();
    var dom = require_dom();
    var xhr = require_xhr();
    var fetch2 = require_fetch();
    var history = require_history();
    var globalError = require_globalError();
    var globalUnhandledRejection = require_globalUnhandledRejection();
    var _handlers = require_handlers();
    var nodeStackTrace = require_node_stack_trace();
    var escapeStringForRegex = require_escapeStringForRegex();
    var supportsHistory = require_supportsHistory();
    exports.applyAggregateErrorsToEvent = aggregateErrors.applyAggregateErrorsToEvent;
    exports.getComponentName = browser.getComponentName;
    exports.getDomElement = browser.getDomElement;
    exports.getLocationHref = browser.getLocationHref;
    exports.htmlTreeAsString = browser.htmlTreeAsString;
    exports.dsnFromString = dsn.dsnFromString;
    exports.dsnToString = dsn.dsnToString;
    exports.makeDsn = dsn.makeDsn;
    exports.SentryError = error.SentryError;
    exports.GLOBAL_OBJ = worldwide.GLOBAL_OBJ;
    exports.getGlobalObject = worldwide.getGlobalObject;
    exports.getGlobalSingleton = worldwide.getGlobalSingleton;
    exports.addInstrumentationHandler = index.addInstrumentationHandler;
    exports.isDOMError = is.isDOMError;
    exports.isDOMException = is.isDOMException;
    exports.isElement = is.isElement;
    exports.isError = is.isError;
    exports.isErrorEvent = is.isErrorEvent;
    exports.isEvent = is.isEvent;
    exports.isInstanceOf = is.isInstanceOf;
    exports.isNaN = is.isNaN;
    exports.isParameterizedString = is.isParameterizedString;
    exports.isPlainObject = is.isPlainObject;
    exports.isPrimitive = is.isPrimitive;
    exports.isRegExp = is.isRegExp;
    exports.isString = is.isString;
    exports.isSyntheticEvent = is.isSyntheticEvent;
    exports.isThenable = is.isThenable;
    exports.isVueViewModel = is.isVueViewModel;
    exports.isBrowser = isBrowser.isBrowser;
    exports.CONSOLE_LEVELS = logger.CONSOLE_LEVELS;
    exports.consoleSandbox = logger.consoleSandbox;
    exports.logger = logger.logger;
    exports.originalConsoleMethods = logger.originalConsoleMethods;
    exports.memoBuilder = memo.memoBuilder;
    exports.addContextToFrame = misc.addContextToFrame;
    exports.addExceptionMechanism = misc.addExceptionMechanism;
    exports.addExceptionTypeValue = misc.addExceptionTypeValue;
    exports.arrayify = misc.arrayify;
    exports.checkOrSetAlreadyCaught = misc.checkOrSetAlreadyCaught;
    exports.getEventDescription = misc.getEventDescription;
    exports.parseSemver = misc.parseSemver;
    exports.uuid4 = misc.uuid4;
    exports.dynamicRequire = node.dynamicRequire;
    exports.isNodeEnv = node.isNodeEnv;
    exports.loadModule = node.loadModule;
    exports.normalize = normalize.normalize;
    exports.normalizeToSize = normalize.normalizeToSize;
    exports.normalizeUrlToBase = normalize.normalizeUrlToBase;
    exports.walk = normalize.walk;
    exports.addNonEnumerableProperty = object.addNonEnumerableProperty;
    exports.convertToPlainObject = object.convertToPlainObject;
    exports.dropUndefinedKeys = object.dropUndefinedKeys;
    exports.extractExceptionKeysForMessage = object.extractExceptionKeysForMessage;
    exports.fill = object.fill;
    exports.getOriginalFunction = object.getOriginalFunction;
    exports.markFunctionWrapped = object.markFunctionWrapped;
    exports.objectify = object.objectify;
    exports.urlEncode = object.urlEncode;
    exports.basename = path2.basename;
    exports.dirname = path2.dirname;
    exports.isAbsolute = path2.isAbsolute;
    exports.join = path2.join;
    exports.normalizePath = path2.normalizePath;
    exports.relative = path2.relative;
    exports.resolve = path2.resolve;
    exports.makePromiseBuffer = promisebuffer.makePromiseBuffer;
    exports.DEFAULT_USER_INCLUDES = requestdata.DEFAULT_USER_INCLUDES;
    exports.addRequestDataToEvent = requestdata.addRequestDataToEvent;
    exports.addRequestDataToTransaction = requestdata.addRequestDataToTransaction;
    exports.extractPathForTransaction = requestdata.extractPathForTransaction;
    exports.extractRequestData = requestdata.extractRequestData;
    exports.winterCGHeadersToDict = requestdata.winterCGHeadersToDict;
    exports.winterCGRequestToRequestData = requestdata.winterCGRequestToRequestData;
    exports.severityFromString = severity.severityFromString;
    exports.severityLevelFromString = severity.severityLevelFromString;
    exports.validSeverityLevels = severity.validSeverityLevels;
    exports.createStackParser = stacktrace.createStackParser;
    exports.getFunctionName = stacktrace.getFunctionName;
    exports.nodeStackLineParser = stacktrace.nodeStackLineParser;
    exports.stackParserFromStackParserOptions = stacktrace.stackParserFromStackParserOptions;
    exports.stripSentryFramesAndReverse = stacktrace.stripSentryFramesAndReverse;
    exports.isMatchingPattern = string.isMatchingPattern;
    exports.safeJoin = string.safeJoin;
    exports.snipLine = string.snipLine;
    exports.stringMatchesSomePattern = string.stringMatchesSomePattern;
    exports.truncate = string.truncate;
    exports.isNativeFetch = supports.isNativeFetch;
    exports.supportsDOMError = supports.supportsDOMError;
    exports.supportsDOMException = supports.supportsDOMException;
    exports.supportsErrorEvent = supports.supportsErrorEvent;
    exports.supportsFetch = supports.supportsFetch;
    exports.supportsNativeFetch = supports.supportsNativeFetch;
    exports.supportsReferrerPolicy = supports.supportsReferrerPolicy;
    exports.supportsReportingObserver = supports.supportsReportingObserver;
    exports.SyncPromise = syncpromise.SyncPromise;
    exports.rejectedSyncPromise = syncpromise.rejectedSyncPromise;
    exports.resolvedSyncPromise = syncpromise.resolvedSyncPromise;
    Object.defineProperty(exports, "_browserPerformanceTimeOriginMode", {
      enumerable: true,
      get: () => time._browserPerformanceTimeOriginMode
    });
    exports.browserPerformanceTimeOrigin = time.browserPerformanceTimeOrigin;
    exports.dateTimestampInSeconds = time.dateTimestampInSeconds;
    exports.timestampInSeconds = time.timestampInSeconds;
    exports.timestampWithMs = time.timestampWithMs;
    exports.TRACEPARENT_REGEXP = tracing.TRACEPARENT_REGEXP;
    exports.extractTraceparentData = tracing.extractTraceparentData;
    exports.generateSentryTraceHeader = tracing.generateSentryTraceHeader;
    exports.propagationContextFromHeaders = tracing.propagationContextFromHeaders;
    exports.tracingContextFromHeaders = tracing.tracingContextFromHeaders;
    exports.getSDKSource = env2.getSDKSource;
    exports.isBrowserBundle = env2.isBrowserBundle;
    exports.addItemToEnvelope = envelope.addItemToEnvelope;
    exports.createAttachmentEnvelopeItem = envelope.createAttachmentEnvelopeItem;
    exports.createEnvelope = envelope.createEnvelope;
    exports.createEventEnvelopeHeaders = envelope.createEventEnvelopeHeaders;
    exports.envelopeContainsItemType = envelope.envelopeContainsItemType;
    exports.envelopeItemTypeToDataCategory = envelope.envelopeItemTypeToDataCategory;
    exports.forEachEnvelopeItem = envelope.forEachEnvelopeItem;
    exports.getSdkMetadataForEnvelopeHeader = envelope.getSdkMetadataForEnvelopeHeader;
    exports.parseEnvelope = envelope.parseEnvelope;
    exports.serializeEnvelope = envelope.serializeEnvelope;
    exports.createClientReportEnvelope = clientreport.createClientReportEnvelope;
    exports.DEFAULT_RETRY_AFTER = ratelimit.DEFAULT_RETRY_AFTER;
    exports.disabledUntil = ratelimit.disabledUntil;
    exports.isRateLimited = ratelimit.isRateLimited;
    exports.parseRetryAfterHeader = ratelimit.parseRetryAfterHeader;
    exports.updateRateLimits = ratelimit.updateRateLimits;
    exports.BAGGAGE_HEADER_NAME = baggage.BAGGAGE_HEADER_NAME;
    exports.MAX_BAGGAGE_STRING_LENGTH = baggage.MAX_BAGGAGE_STRING_LENGTH;
    exports.SENTRY_BAGGAGE_KEY_PREFIX = baggage.SENTRY_BAGGAGE_KEY_PREFIX;
    exports.SENTRY_BAGGAGE_KEY_PREFIX_REGEX = baggage.SENTRY_BAGGAGE_KEY_PREFIX_REGEX;
    exports.baggageHeaderToDynamicSamplingContext = baggage.baggageHeaderToDynamicSamplingContext;
    exports.dynamicSamplingContextToSentryBaggageHeader = baggage.dynamicSamplingContextToSentryBaggageHeader;
    exports.getNumberOfUrlSegments = url.getNumberOfUrlSegments;
    exports.getSanitizedUrlString = url.getSanitizedUrlString;
    exports.parseUrl = url.parseUrl;
    exports.stripUrlQueryAndFragment = url.stripUrlQueryAndFragment;
    exports.addOrUpdateIntegration = userIntegrations.addOrUpdateIntegration;
    exports.makeFifoCache = cache.makeFifoCache;
    exports.eventFromMessage = eventbuilder.eventFromMessage;
    exports.eventFromUnknownInput = eventbuilder.eventFromUnknownInput;
    exports.exceptionFromError = eventbuilder.exceptionFromError;
    exports.parseStackFrames = eventbuilder.parseStackFrames;
    exports.callFrameToStackFrame = anr.callFrameToStackFrame;
    exports.watchdogTimer = anr.watchdogTimer;
    exports.LRUMap = lru.LRUMap;
    exports._asyncNullishCoalesce = _asyncNullishCoalesce._asyncNullishCoalesce;
    exports._asyncOptionalChain = _asyncOptionalChain._asyncOptionalChain;
    exports._asyncOptionalChainDelete = _asyncOptionalChainDelete._asyncOptionalChainDelete;
    exports._nullishCoalesce = _nullishCoalesce._nullishCoalesce;
    exports._optionalChain = _optionalChain._optionalChain;
    exports._optionalChainDelete = _optionalChainDelete._optionalChainDelete;
    exports.addConsoleInstrumentationHandler = console2.addConsoleInstrumentationHandler;
    exports.addClickKeypressInstrumentationHandler = dom.addClickKeypressInstrumentationHandler;
    exports.SENTRY_XHR_DATA_KEY = xhr.SENTRY_XHR_DATA_KEY;
    exports.addXhrInstrumentationHandler = xhr.addXhrInstrumentationHandler;
    exports.addFetchInstrumentationHandler = fetch2.addFetchInstrumentationHandler;
    exports.addHistoryInstrumentationHandler = history.addHistoryInstrumentationHandler;
    exports.addGlobalErrorInstrumentationHandler = globalError.addGlobalErrorInstrumentationHandler;
    exports.addGlobalUnhandledRejectionInstrumentationHandler = globalUnhandledRejection.addGlobalUnhandledRejectionInstrumentationHandler;
    exports.resetInstrumentationHandlers = _handlers.resetInstrumentationHandlers;
    exports.filenameIsInApp = nodeStackTrace.filenameIsInApp;
    exports.escapeStringForRegex = escapeStringForRegex.escapeStringForRegex;
    exports.supportsHistory = supportsHistory.supportsHistory;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/debug-build.js
var require_debug_build2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/debug-build.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
    exports.DEBUG_BUILD = DEBUG_BUILD;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/constants.js
var require_constants = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/constants.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var DEFAULT_ENVIRONMENT = "production";
    exports.DEFAULT_ENVIRONMENT = DEFAULT_ENVIRONMENT;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/eventProcessors.js
var require_eventProcessors = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/eventProcessors.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build2();
    function getGlobalEventProcessors() {
      return utils.getGlobalSingleton("globalEventProcessors", () => []);
    }
    function addGlobalEventProcessor(callback) {
      getGlobalEventProcessors().push(callback);
    }
    function notifyEventProcessors(processors, event, hint, index = 0) {
      return new utils.SyncPromise((resolve2, reject) => {
        const processor = processors[index];
        if (event === null || typeof processor !== "function") {
          resolve2(event);
        } else {
          const result = processor({ ...event }, hint);
          debugBuild.DEBUG_BUILD && processor.id && result === null && utils.logger.log(`Event processor "${processor.id}" dropped event`);
          if (utils.isThenable(result)) {
            void result.then((final) => notifyEventProcessors(processors, final, hint, index + 1).then(resolve2)).then(null, reject);
          } else {
            void notifyEventProcessors(processors, result, hint, index + 1).then(resolve2).then(null, reject);
          }
        }
      });
    }
    exports.addGlobalEventProcessor = addGlobalEventProcessor;
    exports.getGlobalEventProcessors = getGlobalEventProcessors;
    exports.notifyEventProcessors = notifyEventProcessors;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/session.js
var require_session = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/session.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    function makeSession(context2) {
      const startingTime = utils.timestampInSeconds();
      const session = {
        sid: utils.uuid4(),
        init: true,
        timestamp: startingTime,
        started: startingTime,
        duration: 0,
        status: "ok",
        errors: 0,
        ignoreDuration: false,
        toJSON: () => sessionToJSON(session)
      };
      if (context2) {
        updateSession(session, context2);
      }
      return session;
    }
    function updateSession(session, context2 = {}) {
      if (context2.user) {
        if (!session.ipAddress && context2.user.ip_address) {
          session.ipAddress = context2.user.ip_address;
        }
        if (!session.did && !context2.did) {
          session.did = context2.user.id || context2.user.email || context2.user.username;
        }
      }
      session.timestamp = context2.timestamp || utils.timestampInSeconds();
      if (context2.abnormal_mechanism) {
        session.abnormal_mechanism = context2.abnormal_mechanism;
      }
      if (context2.ignoreDuration) {
        session.ignoreDuration = context2.ignoreDuration;
      }
      if (context2.sid) {
        session.sid = context2.sid.length === 32 ? context2.sid : utils.uuid4();
      }
      if (context2.init !== void 0) {
        session.init = context2.init;
      }
      if (!session.did && context2.did) {
        session.did = `${context2.did}`;
      }
      if (typeof context2.started === "number") {
        session.started = context2.started;
      }
      if (session.ignoreDuration) {
        session.duration = void 0;
      } else if (typeof context2.duration === "number") {
        session.duration = context2.duration;
      } else {
        const duration = session.timestamp - session.started;
        session.duration = duration >= 0 ? duration : 0;
      }
      if (context2.release) {
        session.release = context2.release;
      }
      if (context2.environment) {
        session.environment = context2.environment;
      }
      if (!session.ipAddress && context2.ipAddress) {
        session.ipAddress = context2.ipAddress;
      }
      if (!session.userAgent && context2.userAgent) {
        session.userAgent = context2.userAgent;
      }
      if (typeof context2.errors === "number") {
        session.errors = context2.errors;
      }
      if (context2.status) {
        session.status = context2.status;
      }
    }
    function closeSession(session, status) {
      let context2 = {};
      if (status) {
        context2 = { status };
      } else if (session.status === "ok") {
        context2 = { status: "exited" };
      }
      updateSession(session, context2);
    }
    function sessionToJSON(session) {
      return utils.dropUndefinedKeys({
        sid: `${session.sid}`,
        init: session.init,
        // Make sure that sec is converted to ms for date constructor
        started: new Date(session.started * 1e3).toISOString(),
        timestamp: new Date(session.timestamp * 1e3).toISOString(),
        status: session.status,
        errors: session.errors,
        did: typeof session.did === "number" || typeof session.did === "string" ? `${session.did}` : void 0,
        duration: session.duration,
        abnormal_mechanism: session.abnormal_mechanism,
        attrs: {
          release: session.release,
          environment: session.environment,
          ip_address: session.ipAddress,
          user_agent: session.userAgent
        }
      });
    }
    exports.closeSession = closeSession;
    exports.makeSession = makeSession;
    exports.updateSession = updateSession;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/utils/spanUtils.js
var require_spanUtils = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/utils/spanUtils.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var TRACE_FLAG_NONE = 0;
    var TRACE_FLAG_SAMPLED = 1;
    function spanToTraceContext(span) {
      const { spanId: span_id, traceId: trace_id } = span.spanContext();
      const { data, op, parent_span_id, status, tags, origin } = spanToJSON(span);
      return utils.dropUndefinedKeys({
        data,
        op,
        parent_span_id,
        span_id,
        status,
        tags,
        trace_id,
        origin
      });
    }
    function spanToTraceHeader(span) {
      const { traceId, spanId } = span.spanContext();
      const sampled = spanIsSampled(span);
      return utils.generateSentryTraceHeader(traceId, spanId, sampled);
    }
    function spanTimeInputToSeconds(input) {
      if (typeof input === "number") {
        return ensureTimestampInSeconds(input);
      }
      if (Array.isArray(input)) {
        return input[0] + input[1] / 1e9;
      }
      if (input instanceof Date) {
        return ensureTimestampInSeconds(input.getTime());
      }
      return utils.timestampInSeconds();
    }
    function ensureTimestampInSeconds(timestamp) {
      const isMs = timestamp > 9999999999;
      return isMs ? timestamp / 1e3 : timestamp;
    }
    function spanToJSON(span) {
      if (spanIsSpanClass(span)) {
        return span.getSpanJSON();
      }
      if (typeof span.toJSON === "function") {
        return span.toJSON();
      }
      return {};
    }
    function spanIsSpanClass(span) {
      return typeof span.getSpanJSON === "function";
    }
    function spanIsSampled(span) {
      const { traceFlags } = span.spanContext();
      return Boolean(traceFlags & TRACE_FLAG_SAMPLED);
    }
    exports.TRACE_FLAG_NONE = TRACE_FLAG_NONE;
    exports.TRACE_FLAG_SAMPLED = TRACE_FLAG_SAMPLED;
    exports.spanIsSampled = spanIsSampled;
    exports.spanTimeInputToSeconds = spanTimeInputToSeconds;
    exports.spanToJSON = spanToJSON;
    exports.spanToTraceContext = spanToTraceContext;
    exports.spanToTraceHeader = spanToTraceHeader;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/utils/prepareEvent.js
var require_prepareEvent = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/utils/prepareEvent.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var constants = require_constants();
    var eventProcessors = require_eventProcessors();
    var scope = require_scope();
    var applyScopeDataToEvent = require_applyScopeDataToEvent();
    var spanUtils = require_spanUtils();
    function prepareEvent(options, event, hint, scope$1, client, isolationScope) {
      const { normalizeDepth = 3, normalizeMaxBreadth = 1e3 } = options;
      const prepared = {
        ...event,
        event_id: event.event_id || hint.event_id || utils.uuid4(),
        timestamp: event.timestamp || utils.dateTimestampInSeconds()
      };
      const integrations = hint.integrations || options.integrations.map((i2) => i2.name);
      applyClientOptions(prepared, options);
      applyIntegrationsMetadata(prepared, integrations);
      if (event.type === void 0) {
        applyDebugIds(prepared, options.stackParser);
      }
      const finalScope = getFinalScope(scope$1, hint.captureContext);
      if (hint.mechanism) {
        utils.addExceptionMechanism(prepared, hint.mechanism);
      }
      const clientEventProcessors = client && client.getEventProcessors ? client.getEventProcessors() : [];
      const data = scope.getGlobalScope().getScopeData();
      if (isolationScope) {
        const isolationData = isolationScope.getScopeData();
        applyScopeDataToEvent.mergeScopeData(data, isolationData);
      }
      if (finalScope) {
        const finalScopeData = finalScope.getScopeData();
        applyScopeDataToEvent.mergeScopeData(data, finalScopeData);
      }
      const attachments = [...hint.attachments || [], ...data.attachments];
      if (attachments.length) {
        hint.attachments = attachments;
      }
      applyScopeDataToEvent.applyScopeDataToEvent(prepared, data);
      const eventProcessors$1 = [
        ...clientEventProcessors,
        // eslint-disable-next-line deprecation/deprecation
        ...eventProcessors.getGlobalEventProcessors(),
        // Run scope event processors _after_ all other processors
        ...data.eventProcessors
      ];
      const result = eventProcessors.notifyEventProcessors(eventProcessors$1, prepared, hint);
      return result.then((evt) => {
        if (evt) {
          applyDebugMeta(evt);
        }
        if (typeof normalizeDepth === "number" && normalizeDepth > 0) {
          return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);
        }
        return evt;
      });
    }
    function applyClientOptions(event, options) {
      const { environment, release, dist, maxValueLength = 250 } = options;
      if (!("environment" in event)) {
        event.environment = "environment" in options ? environment : constants.DEFAULT_ENVIRONMENT;
      }
      if (event.release === void 0 && release !== void 0) {
        event.release = release;
      }
      if (event.dist === void 0 && dist !== void 0) {
        event.dist = dist;
      }
      if (event.message) {
        event.message = utils.truncate(event.message, maxValueLength);
      }
      const exception = event.exception && event.exception.values && event.exception.values[0];
      if (exception && exception.value) {
        exception.value = utils.truncate(exception.value, maxValueLength);
      }
      const request = event.request;
      if (request && request.url) {
        request.url = utils.truncate(request.url, maxValueLength);
      }
    }
    var debugIdStackParserCache = /* @__PURE__ */ new WeakMap();
    function applyDebugIds(event, stackParser) {
      const debugIdMap = utils.GLOBAL_OBJ._sentryDebugIds;
      if (!debugIdMap) {
        return;
      }
      let debugIdStackFramesCache;
      const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser);
      if (cachedDebugIdStackFrameCache) {
        debugIdStackFramesCache = cachedDebugIdStackFrameCache;
      } else {
        debugIdStackFramesCache = /* @__PURE__ */ new Map();
        debugIdStackParserCache.set(stackParser, debugIdStackFramesCache);
      }
      const filenameDebugIdMap = Object.keys(debugIdMap).reduce((acc, debugIdStackTrace) => {
        let parsedStack;
        const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace);
        if (cachedParsedStack) {
          parsedStack = cachedParsedStack;
        } else {
          parsedStack = stackParser(debugIdStackTrace);
          debugIdStackFramesCache.set(debugIdStackTrace, parsedStack);
        }
        for (let i2 = parsedStack.length - 1; i2 >= 0; i2--) {
          const stackFrame = parsedStack[i2];
          if (stackFrame.filename) {
            acc[stackFrame.filename] = debugIdMap[debugIdStackTrace];
            break;
          }
        }
        return acc;
      }, {});
      try {
        event.exception.values.forEach((exception) => {
          exception.stacktrace.frames.forEach((frame) => {
            if (frame.filename) {
              frame.debug_id = filenameDebugIdMap[frame.filename];
            }
          });
        });
      } catch (e2) {
      }
    }
    function applyDebugMeta(event) {
      const filenameDebugIdMap = {};
      try {
        event.exception.values.forEach((exception) => {
          exception.stacktrace.frames.forEach((frame) => {
            if (frame.debug_id) {
              if (frame.abs_path) {
                filenameDebugIdMap[frame.abs_path] = frame.debug_id;
              } else if (frame.filename) {
                filenameDebugIdMap[frame.filename] = frame.debug_id;
              }
              delete frame.debug_id;
            }
          });
        });
      } catch (e2) {
      }
      if (Object.keys(filenameDebugIdMap).length === 0) {
        return;
      }
      event.debug_meta = event.debug_meta || {};
      event.debug_meta.images = event.debug_meta.images || [];
      const images = event.debug_meta.images;
      Object.keys(filenameDebugIdMap).forEach((filename) => {
        images.push({
          type: "sourcemap",
          code_file: filename,
          debug_id: filenameDebugIdMap[filename]
        });
      });
    }
    function applyIntegrationsMetadata(event, integrationNames) {
      if (integrationNames.length > 0) {
        event.sdk = event.sdk || {};
        event.sdk.integrations = [...event.sdk.integrations || [], ...integrationNames];
      }
    }
    function normalizeEvent(event, depth, maxBreadth) {
      if (!event) {
        return null;
      }
      const normalized = {
        ...event,
        ...event.breadcrumbs && {
          breadcrumbs: event.breadcrumbs.map((b) => ({
            ...b,
            ...b.data && {
              data: utils.normalize(b.data, depth, maxBreadth)
            }
          }))
        },
        ...event.user && {
          user: utils.normalize(event.user, depth, maxBreadth)
        },
        ...event.contexts && {
          contexts: utils.normalize(event.contexts, depth, maxBreadth)
        },
        ...event.extra && {
          extra: utils.normalize(event.extra, depth, maxBreadth)
        }
      };
      if (event.contexts && event.contexts.trace && normalized.contexts) {
        normalized.contexts.trace = event.contexts.trace;
        if (event.contexts.trace.data) {
          normalized.contexts.trace.data = utils.normalize(event.contexts.trace.data, depth, maxBreadth);
        }
      }
      if (event.spans) {
        normalized.spans = event.spans.map((span) => {
          const data = spanUtils.spanToJSON(span).data;
          if (data) {
            span.data = utils.normalize(data, depth, maxBreadth);
          }
          return span;
        });
      }
      return normalized;
    }
    function getFinalScope(scope$1, captureContext) {
      if (!captureContext) {
        return scope$1;
      }
      const finalScope = scope$1 ? scope$1.clone() : new scope.Scope();
      finalScope.update(captureContext);
      return finalScope;
    }
    function parseEventHintOrCaptureContext(hint) {
      if (!hint) {
        return void 0;
      }
      if (hintIsScopeOrFunction(hint)) {
        return { captureContext: hint };
      }
      if (hintIsScopeContext(hint)) {
        return {
          captureContext: hint
        };
      }
      return hint;
    }
    function hintIsScopeOrFunction(hint) {
      return hint instanceof scope.Scope || typeof hint === "function";
    }
    var captureContextKeys = [
      "user",
      "level",
      "extra",
      "contexts",
      "tags",
      "fingerprint",
      "requestSession",
      "propagationContext"
    ];
    function hintIsScopeContext(hint) {
      return Object.keys(hint).some((key) => captureContextKeys.includes(key));
    }
    exports.applyDebugIds = applyDebugIds;
    exports.applyDebugMeta = applyDebugMeta;
    exports.parseEventHintOrCaptureContext = parseEventHintOrCaptureContext;
    exports.prepareEvent = prepareEvent;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/exports.js
var require_exports = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/exports.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var constants = require_constants();
    var debugBuild = require_debug_build2();
    var hub = require_hub();
    var session = require_session();
    var prepareEvent = require_prepareEvent();
    function captureException2(exception, hint) {
      return hub.getCurrentHub().captureException(exception, prepareEvent.parseEventHintOrCaptureContext(hint));
    }
    function captureMessage(message, captureContext) {
      const level = typeof captureContext === "string" ? captureContext : void 0;
      const context2 = typeof captureContext !== "string" ? { captureContext } : void 0;
      return hub.getCurrentHub().captureMessage(message, level, context2);
    }
    function captureEvent(event, hint) {
      return hub.getCurrentHub().captureEvent(event, hint);
    }
    function configureScope(callback) {
      hub.getCurrentHub().configureScope(callback);
    }
    function addBreadcrumb(breadcrumb, hint) {
      hub.getCurrentHub().addBreadcrumb(breadcrumb, hint);
    }
    function setContext(name, context2) {
      hub.getCurrentHub().setContext(name, context2);
    }
    function setExtras(extras) {
      hub.getCurrentHub().setExtras(extras);
    }
    function setExtra(key, extra) {
      hub.getCurrentHub().setExtra(key, extra);
    }
    function setTags(tags) {
      hub.getCurrentHub().setTags(tags);
    }
    function setTag(key, value) {
      hub.getCurrentHub().setTag(key, value);
    }
    function setUser(user) {
      hub.getCurrentHub().setUser(user);
    }
    function withScope(...rest) {
      const hub$1 = hub.getCurrentHub();
      if (rest.length === 2) {
        const [scope, callback] = rest;
        if (!scope) {
          return hub$1.withScope(callback);
        }
        return hub$1.withScope(() => {
          hub$1.getStackTop().scope = scope;
          return callback(scope);
        });
      }
      return hub$1.withScope(rest[0]);
    }
    function withIsolationScope(callback) {
      return hub.runWithAsyncContext(() => {
        return callback(hub.getIsolationScope());
      });
    }
    function withActiveSpan(span, callback) {
      return withScope((scope) => {
        scope.setSpan(span);
        return callback(scope);
      });
    }
    function startTransaction(context2, customSamplingContext) {
      return hub.getCurrentHub().startTransaction({ ...context2 }, customSamplingContext);
    }
    function captureCheckIn(checkIn, upsertMonitorConfig) {
      const scope = getCurrentScope();
      const client = getClient();
      if (!client) {
        debugBuild.DEBUG_BUILD && utils.logger.warn("Cannot capture check-in. No client defined.");
      } else if (!client.captureCheckIn) {
        debugBuild.DEBUG_BUILD && utils.logger.warn("Cannot capture check-in. Client does not support sending check-ins.");
      } else {
        return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);
      }
      return utils.uuid4();
    }
    function withMonitor(monitorSlug, callback, upsertMonitorConfig) {
      const checkInId = captureCheckIn({ monitorSlug, status: "in_progress" }, upsertMonitorConfig);
      const now = utils.timestampInSeconds();
      function finishCheckIn(status) {
        captureCheckIn({ monitorSlug, status, checkInId, duration: utils.timestampInSeconds() - now });
      }
      let maybePromiseResult;
      try {
        maybePromiseResult = callback();
      } catch (e2) {
        finishCheckIn("error");
        throw e2;
      }
      if (utils.isThenable(maybePromiseResult)) {
        Promise.resolve(maybePromiseResult).then(
          () => {
            finishCheckIn("ok");
          },
          () => {
            finishCheckIn("error");
          }
        );
      } else {
        finishCheckIn("ok");
      }
      return maybePromiseResult;
    }
    async function flush(timeout) {
      const client = getClient();
      if (client) {
        return client.flush(timeout);
      }
      debugBuild.DEBUG_BUILD && utils.logger.warn("Cannot flush events. No client defined.");
      return Promise.resolve(false);
    }
    async function close(timeout) {
      const client = getClient();
      if (client) {
        return client.close(timeout);
      }
      debugBuild.DEBUG_BUILD && utils.logger.warn("Cannot flush events and disable SDK. No client defined.");
      return Promise.resolve(false);
    }
    function lastEventId() {
      return hub.getCurrentHub().lastEventId();
    }
    function getClient() {
      return hub.getCurrentHub().getClient();
    }
    function isInitialized() {
      return !!getClient();
    }
    function getCurrentScope() {
      return hub.getCurrentHub().getScope();
    }
    function startSession(context2) {
      const client = getClient();
      const isolationScope = hub.getIsolationScope();
      const currentScope = getCurrentScope();
      const { release, environment = constants.DEFAULT_ENVIRONMENT } = client && client.getOptions() || {};
      const { userAgent } = utils.GLOBAL_OBJ.navigator || {};
      const session$1 = session.makeSession({
        release,
        environment,
        user: currentScope.getUser() || isolationScope.getUser(),
        ...userAgent && { userAgent },
        ...context2
      });
      const currentSession = isolationScope.getSession();
      if (currentSession && currentSession.status === "ok") {
        session.updateSession(currentSession, { status: "exited" });
      }
      endSession();
      isolationScope.setSession(session$1);
      currentScope.setSession(session$1);
      return session$1;
    }
    function endSession() {
      const isolationScope = hub.getIsolationScope();
      const currentScope = getCurrentScope();
      const session$1 = currentScope.getSession() || isolationScope.getSession();
      if (session$1) {
        session.closeSession(session$1);
      }
      _sendSessionUpdate();
      isolationScope.setSession();
      currentScope.setSession();
    }
    function _sendSessionUpdate() {
      const isolationScope = hub.getIsolationScope();
      const currentScope = getCurrentScope();
      const client = getClient();
      const session2 = currentScope.getSession() || isolationScope.getSession();
      if (session2 && client && client.captureSession) {
        client.captureSession(session2);
      }
    }
    function captureSession(end = false) {
      if (end) {
        endSession();
        return;
      }
      _sendSessionUpdate();
    }
    exports.addBreadcrumb = addBreadcrumb;
    exports.captureCheckIn = captureCheckIn;
    exports.captureEvent = captureEvent;
    exports.captureException = captureException2;
    exports.captureMessage = captureMessage;
    exports.captureSession = captureSession;
    exports.close = close;
    exports.configureScope = configureScope;
    exports.endSession = endSession;
    exports.flush = flush;
    exports.getClient = getClient;
    exports.getCurrentScope = getCurrentScope;
    exports.isInitialized = isInitialized;
    exports.lastEventId = lastEventId;
    exports.setContext = setContext;
    exports.setExtra = setExtra;
    exports.setExtras = setExtras;
    exports.setTag = setTag;
    exports.setTags = setTags;
    exports.setUser = setUser;
    exports.startSession = startSession;
    exports.startTransaction = startTransaction;
    exports.withActiveSpan = withActiveSpan;
    exports.withIsolationScope = withIsolationScope;
    exports.withMonitor = withMonitor;
    exports.withScope = withScope;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/utils/getRootSpan.js
var require_getRootSpan = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/utils/getRootSpan.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    function getRootSpan(span) {
      return span.transaction;
    }
    exports.getRootSpan = getRootSpan;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/dynamicSamplingContext.js
var require_dynamicSamplingContext = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/dynamicSamplingContext.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var constants = require_constants();
    var exports$1 = require_exports();
    var getRootSpan = require_getRootSpan();
    var spanUtils = require_spanUtils();
    function getDynamicSamplingContextFromClient(trace_id, client, scope) {
      const options = client.getOptions();
      const { publicKey: public_key } = client.getDsn() || {};
      const { segment: user_segment } = scope && scope.getUser() || {};
      const dsc = utils.dropUndefinedKeys({
        environment: options.environment || constants.DEFAULT_ENVIRONMENT,
        release: options.release,
        user_segment,
        public_key,
        trace_id
      });
      client.emit && client.emit("createDsc", dsc);
      return dsc;
    }
    function getDynamicSamplingContextFromSpan(span) {
      const client = exports$1.getClient();
      if (!client) {
        return {};
      }
      const dsc = getDynamicSamplingContextFromClient(spanUtils.spanToJSON(span).trace_id || "", client, exports$1.getCurrentScope());
      const txn = getRootSpan.getRootSpan(span);
      if (!txn) {
        return dsc;
      }
      const v7FrozenDsc = txn && txn._frozenDynamicSamplingContext;
      if (v7FrozenDsc) {
        return v7FrozenDsc;
      }
      const { sampleRate: maybeSampleRate, source } = txn.metadata;
      if (maybeSampleRate != null) {
        dsc.sample_rate = `${maybeSampleRate}`;
      }
      const jsonSpan = spanUtils.spanToJSON(txn);
      if (source && source !== "url") {
        dsc.transaction = jsonSpan.description;
      }
      dsc.sampled = String(spanUtils.spanIsSampled(txn));
      client.emit && client.emit("createDsc", dsc);
      return dsc;
    }
    exports.getDynamicSamplingContextFromClient = getDynamicSamplingContextFromClient;
    exports.getDynamicSamplingContextFromSpan = getDynamicSamplingContextFromSpan;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/utils/applyScopeDataToEvent.js
var require_applyScopeDataToEvent = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/utils/applyScopeDataToEvent.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var dynamicSamplingContext = require_dynamicSamplingContext();
    var getRootSpan = require_getRootSpan();
    var spanUtils = require_spanUtils();
    function applyScopeDataToEvent(event, data) {
      const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;
      applyDataToEvent(event, data);
      if (span) {
        applySpanToEvent(event, span);
      }
      applyFingerprintToEvent(event, fingerprint);
      applyBreadcrumbsToEvent(event, breadcrumbs);
      applySdkMetadataToEvent(event, sdkProcessingMetadata);
    }
    function mergeScopeData(data, mergeData) {
      const {
        extra,
        tags,
        user,
        contexts,
        level,
        sdkProcessingMetadata,
        breadcrumbs,
        fingerprint,
        eventProcessors,
        attachments,
        propagationContext,
        // eslint-disable-next-line deprecation/deprecation
        transactionName,
        span
      } = mergeData;
      mergeAndOverwriteScopeData(data, "extra", extra);
      mergeAndOverwriteScopeData(data, "tags", tags);
      mergeAndOverwriteScopeData(data, "user", user);
      mergeAndOverwriteScopeData(data, "contexts", contexts);
      mergeAndOverwriteScopeData(data, "sdkProcessingMetadata", sdkProcessingMetadata);
      if (level) {
        data.level = level;
      }
      if (transactionName) {
        data.transactionName = transactionName;
      }
      if (span) {
        data.span = span;
      }
      if (breadcrumbs.length) {
        data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];
      }
      if (fingerprint.length) {
        data.fingerprint = [...data.fingerprint, ...fingerprint];
      }
      if (eventProcessors.length) {
        data.eventProcessors = [...data.eventProcessors, ...eventProcessors];
      }
      if (attachments.length) {
        data.attachments = [...data.attachments, ...attachments];
      }
      data.propagationContext = { ...data.propagationContext, ...propagationContext };
    }
    function mergeAndOverwriteScopeData(data, prop, mergeVal) {
      if (mergeVal && Object.keys(mergeVal).length) {
        data[prop] = { ...data[prop] };
        for (const key in mergeVal) {
          if (Object.prototype.hasOwnProperty.call(mergeVal, key)) {
            data[prop][key] = mergeVal[key];
          }
        }
      }
    }
    function applyDataToEvent(event, data) {
      const {
        extra,
        tags,
        user,
        contexts,
        level,
        // eslint-disable-next-line deprecation/deprecation
        transactionName
      } = data;
      const cleanedExtra = utils.dropUndefinedKeys(extra);
      if (cleanedExtra && Object.keys(cleanedExtra).length) {
        event.extra = { ...cleanedExtra, ...event.extra };
      }
      const cleanedTags = utils.dropUndefinedKeys(tags);
      if (cleanedTags && Object.keys(cleanedTags).length) {
        event.tags = { ...cleanedTags, ...event.tags };
      }
      const cleanedUser = utils.dropUndefinedKeys(user);
      if (cleanedUser && Object.keys(cleanedUser).length) {
        event.user = { ...cleanedUser, ...event.user };
      }
      const cleanedContexts = utils.dropUndefinedKeys(contexts);
      if (cleanedContexts && Object.keys(cleanedContexts).length) {
        event.contexts = { ...cleanedContexts, ...event.contexts };
      }
      if (level) {
        event.level = level;
      }
      if (transactionName) {
        event.transaction = transactionName;
      }
    }
    function applyBreadcrumbsToEvent(event, breadcrumbs) {
      const mergedBreadcrumbs = [...event.breadcrumbs || [], ...breadcrumbs];
      event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : void 0;
    }
    function applySdkMetadataToEvent(event, sdkProcessingMetadata) {
      event.sdkProcessingMetadata = {
        ...event.sdkProcessingMetadata,
        ...sdkProcessingMetadata
      };
    }
    function applySpanToEvent(event, span) {
      event.contexts = { trace: spanUtils.spanToTraceContext(span), ...event.contexts };
      const rootSpan = getRootSpan.getRootSpan(span);
      if (rootSpan) {
        event.sdkProcessingMetadata = {
          dynamicSamplingContext: dynamicSamplingContext.getDynamicSamplingContextFromSpan(span),
          ...event.sdkProcessingMetadata
        };
        const transactionName = spanUtils.spanToJSON(rootSpan).description;
        if (transactionName) {
          event.tags = { transaction: transactionName, ...event.tags };
        }
      }
    }
    function applyFingerprintToEvent(event, fingerprint) {
      event.fingerprint = event.fingerprint ? utils.arrayify(event.fingerprint) : [];
      if (fingerprint) {
        event.fingerprint = event.fingerprint.concat(fingerprint);
      }
      if (event.fingerprint && !event.fingerprint.length) {
        delete event.fingerprint;
      }
    }
    exports.applyScopeDataToEvent = applyScopeDataToEvent;
    exports.mergeAndOverwriteScopeData = mergeAndOverwriteScopeData;
    exports.mergeScopeData = mergeScopeData;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/scope.js
var require_scope = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/scope.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var eventProcessors = require_eventProcessors();
    var session = require_session();
    var applyScopeDataToEvent = require_applyScopeDataToEvent();
    var DEFAULT_MAX_BREADCRUMBS = 100;
    var globalScope;
    var Scope = class _Scope {
      /** Flag if notifying is happening. */
      /** Callback for client to receive scope changes. */
      /** Callback list that will be called after {@link applyToEvent}. */
      /** Array of breadcrumbs. */
      /** User */
      /** Tags */
      /** Extra */
      /** Contexts */
      /** Attachments */
      /** Propagation Context for distributed tracing */
      /**
       * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get
       * sent to Sentry
       */
      /** Fingerprint */
      /** Severity */
      // eslint-disable-next-line deprecation/deprecation
      /**
       * Transaction Name
       */
      /** Span */
      /** Session */
      /** Request Mode Session Status */
      /** The client on this scope */
      // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.
      constructor() {
        this._notifyingListeners = false;
        this._scopeListeners = [];
        this._eventProcessors = [];
        this._breadcrumbs = [];
        this._attachments = [];
        this._user = {};
        this._tags = {};
        this._extra = {};
        this._contexts = {};
        this._sdkProcessingMetadata = {};
        this._propagationContext = generatePropagationContext();
      }
      /**
       * Inherit values from the parent scope.
       * @deprecated Use `scope.clone()` and `new Scope()` instead.
       */
      static clone(scope) {
        return scope ? scope.clone() : new _Scope();
      }
      /**
       * Clone this scope instance.
       */
      clone() {
        const newScope = new _Scope();
        newScope._breadcrumbs = [...this._breadcrumbs];
        newScope._tags = { ...this._tags };
        newScope._extra = { ...this._extra };
        newScope._contexts = { ...this._contexts };
        newScope._user = this._user;
        newScope._level = this._level;
        newScope._span = this._span;
        newScope._session = this._session;
        newScope._transactionName = this._transactionName;
        newScope._fingerprint = this._fingerprint;
        newScope._eventProcessors = [...this._eventProcessors];
        newScope._requestSession = this._requestSession;
        newScope._attachments = [...this._attachments];
        newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };
        newScope._propagationContext = { ...this._propagationContext };
        newScope._client = this._client;
        return newScope;
      }
      /** Update the client on the scope. */
      setClient(client) {
        this._client = client;
      }
      /**
       * Get the client assigned to this scope.
       *
       * It is generally recommended to use the global function `Sentry.getClient()` instead, unless you know what you are doing.
       */
      getClient() {
        return this._client;
      }
      /**
       * Add internal on change listener. Used for sub SDKs that need to store the scope.
       * @hidden
       */
      addScopeListener(callback) {
        this._scopeListeners.push(callback);
      }
      /**
       * @inheritDoc
       */
      addEventProcessor(callback) {
        this._eventProcessors.push(callback);
        return this;
      }
      /**
       * @inheritDoc
       */
      setUser(user) {
        this._user = user || {
          email: void 0,
          id: void 0,
          ip_address: void 0,
          segment: void 0,
          username: void 0
        };
        if (this._session) {
          session.updateSession(this._session, { user });
        }
        this._notifyScopeListeners();
        return this;
      }
      /**
       * @inheritDoc
       */
      getUser() {
        return this._user;
      }
      /**
       * @inheritDoc
       */
      getRequestSession() {
        return this._requestSession;
      }
      /**
       * @inheritDoc
       */
      setRequestSession(requestSession) {
        this._requestSession = requestSession;
        return this;
      }
      /**
       * @inheritDoc
       */
      setTags(tags) {
        this._tags = {
          ...this._tags,
          ...tags
        };
        this._notifyScopeListeners();
        return this;
      }
      /**
       * @inheritDoc
       */
      setTag(key, value) {
        this._tags = { ...this._tags, [key]: value };
        this._notifyScopeListeners();
        return this;
      }
      /**
       * @inheritDoc
       */
      setExtras(extras) {
        this._extra = {
          ...this._extra,
          ...extras
        };
        this._notifyScopeListeners();
        return this;
      }
      /**
       * @inheritDoc
       */
      setExtra(key, extra) {
        this._extra = { ...this._extra, [key]: extra };
        this._notifyScopeListeners();
        return this;
      }
      /**
       * @inheritDoc
       */
      setFingerprint(fingerprint) {
        this._fingerprint = fingerprint;
        this._notifyScopeListeners();
        return this;
      }
      /**
       * @inheritDoc
       */
      setLevel(level) {
        this._level = level;
        this._notifyScopeListeners();
        return this;
      }
      /**
       * Sets the transaction name on the scope for future events.
       */
      setTransactionName(name) {
        this._transactionName = name;
        this._notifyScopeListeners();
        return this;
      }
      /**
       * @inheritDoc
       */
      setContext(key, context2) {
        if (context2 === null) {
          delete this._contexts[key];
        } else {
          this._contexts[key] = context2;
        }
        this._notifyScopeListeners();
        return this;
      }
      /**
       * Sets the Span on the scope.
       * @param span Span
       * @deprecated Instead of setting a span on a scope, use `startSpan()`/`startSpanManual()` instead.
       */
      setSpan(span) {
        this._span = span;
        this._notifyScopeListeners();
        return this;
      }
      /**
       * Returns the `Span` if there is one.
       * @deprecated Use `getActiveSpan()` instead.
       */
      getSpan() {
        return this._span;
      }
      /**
       * Returns the `Transaction` attached to the scope (if there is one).
       * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead.
       */
      getTransaction() {
        const span = this._span;
        return span && span.transaction;
      }
      /**
       * @inheritDoc
       */
      setSession(session2) {
        if (!session2) {
          delete this._session;
        } else {
          this._session = session2;
        }
        this._notifyScopeListeners();
        return this;
      }
      /**
       * @inheritDoc
       */
      getSession() {
        return this._session;
      }
      /**
       * @inheritDoc
       */
      update(captureContext) {
        if (!captureContext) {
          return this;
        }
        const scopeToMerge = typeof captureContext === "function" ? captureContext(this) : captureContext;
        if (scopeToMerge instanceof _Scope) {
          const scopeData = scopeToMerge.getScopeData();
          this._tags = { ...this._tags, ...scopeData.tags };
          this._extra = { ...this._extra, ...scopeData.extra };
          this._contexts = { ...this._contexts, ...scopeData.contexts };
          if (scopeData.user && Object.keys(scopeData.user).length) {
            this._user = scopeData.user;
          }
          if (scopeData.level) {
            this._level = scopeData.level;
          }
          if (scopeData.fingerprint.length) {
            this._fingerprint = scopeData.fingerprint;
          }
          if (scopeToMerge.getRequestSession()) {
            this._requestSession = scopeToMerge.getRequestSession();
          }
          if (scopeData.propagationContext) {
            this._propagationContext = scopeData.propagationContext;
          }
        } else if (utils.isPlainObject(scopeToMerge)) {
          const scopeContext = captureContext;
          this._tags = { ...this._tags, ...scopeContext.tags };
          this._extra = { ...this._extra, ...scopeContext.extra };
          this._contexts = { ...this._contexts, ...scopeContext.contexts };
          if (scopeContext.user) {
            this._user = scopeContext.user;
          }
          if (scopeContext.level) {
            this._level = scopeContext.level;
          }
          if (scopeContext.fingerprint) {
            this._fingerprint = scopeContext.fingerprint;
          }
          if (scopeContext.requestSession) {
            this._requestSession = scopeContext.requestSession;
          }
          if (scopeContext.propagationContext) {
            this._propagationContext = scopeContext.propagationContext;
          }
        }
        return this;
      }
      /**
       * @inheritDoc
       */
      clear() {
        this._breadcrumbs = [];
        this._tags = {};
        this._extra = {};
        this._user = {};
        this._contexts = {};
        this._level = void 0;
        this._transactionName = void 0;
        this._fingerprint = void 0;
        this._requestSession = void 0;
        this._span = void 0;
        this._session = void 0;
        this._notifyScopeListeners();
        this._attachments = [];
        this._propagationContext = generatePropagationContext();
        return this;
      }
      /**
       * @inheritDoc
       */
      addBreadcrumb(breadcrumb, maxBreadcrumbs) {
        const maxCrumbs = typeof maxBreadcrumbs === "number" ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;
        if (maxCrumbs <= 0) {
          return this;
        }
        const mergedBreadcrumb = {
          timestamp: utils.dateTimestampInSeconds(),
          ...breadcrumb
        };
        const breadcrumbs = this._breadcrumbs;
        breadcrumbs.push(mergedBreadcrumb);
        this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs;
        this._notifyScopeListeners();
        return this;
      }
      /**
       * @inheritDoc
       */
      getLastBreadcrumb() {
        return this._breadcrumbs[this._breadcrumbs.length - 1];
      }
      /**
       * @inheritDoc
       */
      clearBreadcrumbs() {
        this._breadcrumbs = [];
        this._notifyScopeListeners();
        return this;
      }
      /**
       * @inheritDoc
       */
      addAttachment(attachment) {
        this._attachments.push(attachment);
        return this;
      }
      /**
       * @inheritDoc
       * @deprecated Use `getScopeData()` instead.
       */
      getAttachments() {
        const data = this.getScopeData();
        return data.attachments;
      }
      /**
       * @inheritDoc
       */
      clearAttachments() {
        this._attachments = [];
        return this;
      }
      /** @inheritDoc */
      getScopeData() {
        const {
          _breadcrumbs,
          _attachments,
          _contexts,
          _tags,
          _extra,
          _user,
          _level,
          _fingerprint,
          _eventProcessors,
          _propagationContext,
          _sdkProcessingMetadata,
          _transactionName,
          _span
        } = this;
        return {
          breadcrumbs: _breadcrumbs,
          attachments: _attachments,
          contexts: _contexts,
          tags: _tags,
          extra: _extra,
          user: _user,
          level: _level,
          fingerprint: _fingerprint || [],
          eventProcessors: _eventProcessors,
          propagationContext: _propagationContext,
          sdkProcessingMetadata: _sdkProcessingMetadata,
          transactionName: _transactionName,
          span: _span
        };
      }
      /**
       * Applies data from the scope to the event and runs all event processors on it.
       *
       * @param event Event
       * @param hint Object containing additional information about the original exception, for use by the event processors.
       * @hidden
       * @deprecated Use `applyScopeDataToEvent()` directly
       */
      applyToEvent(event, hint = {}, additionalEventProcessors = []) {
        applyScopeDataToEvent.applyScopeDataToEvent(event, this.getScopeData());
        const eventProcessors$1 = [
          ...additionalEventProcessors,
          // eslint-disable-next-line deprecation/deprecation
          ...eventProcessors.getGlobalEventProcessors(),
          ...this._eventProcessors
        ];
        return eventProcessors.notifyEventProcessors(eventProcessors$1, event, hint);
      }
      /**
       * Add data which will be accessible during event processing but won't get sent to Sentry
       */
      setSDKProcessingMetadata(newData) {
        this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };
        return this;
      }
      /**
       * @inheritDoc
       */
      setPropagationContext(context2) {
        this._propagationContext = context2;
        return this;
      }
      /**
       * @inheritDoc
       */
      getPropagationContext() {
        return this._propagationContext;
      }
      /**
       * Capture an exception for this scope.
       *
       * @param exception The exception to capture.
       * @param hint Optinal additional data to attach to the Sentry event.
       * @returns the id of the captured Sentry event.
       */
      captureException(exception, hint) {
        const eventId = hint && hint.event_id ? hint.event_id : utils.uuid4();
        if (!this._client) {
          utils.logger.warn("No client configured on scope - will not capture exception!");
          return eventId;
        }
        const syntheticException = new Error("Sentry syntheticException");
        this._client.captureException(
          exception,
          {
            originalException: exception,
            syntheticException,
            ...hint,
            event_id: eventId
          },
          this
        );
        return eventId;
      }
      /**
       * Capture a message for this scope.
       *
       * @param message The message to capture.
       * @param level An optional severity level to report the message with.
       * @param hint Optional additional data to attach to the Sentry event.
       * @returns the id of the captured message.
       */
      captureMessage(message, level, hint) {
        const eventId = hint && hint.event_id ? hint.event_id : utils.uuid4();
        if (!this._client) {
          utils.logger.warn("No client configured on scope - will not capture message!");
          return eventId;
        }
        const syntheticException = new Error(message);
        this._client.captureMessage(
          message,
          level,
          {
            originalException: message,
            syntheticException,
            ...hint,
            event_id: eventId
          },
          this
        );
        return eventId;
      }
      /**
       * Captures a manually created event for this scope and sends it to Sentry.
       *
       * @param exception The event to capture.
       * @param hint Optional additional data to attach to the Sentry event.
       * @returns the id of the captured event.
       */
      captureEvent(event, hint) {
        const eventId = hint && hint.event_id ? hint.event_id : utils.uuid4();
        if (!this._client) {
          utils.logger.warn("No client configured on scope - will not capture event!");
          return eventId;
        }
        this._client.captureEvent(event, { ...hint, event_id: eventId }, this);
        return eventId;
      }
      /**
       * This will be called on every set call.
       */
      _notifyScopeListeners() {
        if (!this._notifyingListeners) {
          this._notifyingListeners = true;
          this._scopeListeners.forEach((callback) => {
            callback(this);
          });
          this._notifyingListeners = false;
        }
      }
    };
    function getGlobalScope() {
      if (!globalScope) {
        globalScope = new Scope();
      }
      return globalScope;
    }
    function setGlobalScope(scope) {
      globalScope = scope;
    }
    function generatePropagationContext() {
      return {
        traceId: utils.uuid4(),
        spanId: utils.uuid4().substring(16)
      };
    }
    exports.Scope = Scope;
    exports.getGlobalScope = getGlobalScope;
    exports.setGlobalScope = setGlobalScope;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/version.js
var require_version = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/version.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var SDK_VERSION = "7.120.3";
    exports.SDK_VERSION = SDK_VERSION;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/hub.js
var require_hub = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/hub.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var constants = require_constants();
    var debugBuild = require_debug_build2();
    var scope = require_scope();
    var session = require_session();
    var version2 = require_version();
    var API_VERSION = parseFloat(version2.SDK_VERSION);
    var DEFAULT_BREADCRUMBS = 100;
    var Hub = class {
      /** Is a {@link Layer}[] containing the client and scope */
      /** Contains the last event id of a captured event.  */
      /**
       * Creates a new instance of the hub, will push one {@link Layer} into the
       * internal stack on creation.
       *
       * @param client bound to the hub.
       * @param scope bound to the hub.
       * @param version number, higher number means higher priority.
       *
       * @deprecated Instantiation of Hub objects is deprecated and the constructor will be removed in version 8 of the SDK.
       *
       * If you are currently using the Hub for multi-client use like so:
       *
       * ```
       * // OLD
       * const hub = new Hub();
       * hub.bindClient(client);
       * makeMain(hub)
       * ```
       *
       * instead initialize the client as follows:
       *
       * ```
       * // NEW
       * Sentry.withIsolationScope(() => {
       *    Sentry.setCurrentClient(client);
       *    client.init();
       * });
       * ```
       *
       * If you are using the Hub to capture events like so:
       *
       * ```
       * // OLD
       * const client = new Client();
       * const hub = new Hub(client);
       * hub.captureException()
       * ```
       *
       * instead capture isolated events as follows:
       *
       * ```
       * // NEW
       * const client = new Client();
       * const scope = new Scope();
       * scope.setClient(client);
       * scope.captureException();
       * ```
       */
      constructor(client, scope$1, isolationScope, _version = API_VERSION) {
        this._version = _version;
        let assignedScope;
        if (!scope$1) {
          assignedScope = new scope.Scope();
          assignedScope.setClient(client);
        } else {
          assignedScope = scope$1;
        }
        let assignedIsolationScope;
        if (!isolationScope) {
          assignedIsolationScope = new scope.Scope();
          assignedIsolationScope.setClient(client);
        } else {
          assignedIsolationScope = isolationScope;
        }
        this._stack = [{ scope: assignedScope }];
        if (client) {
          this.bindClient(client);
        }
        this._isolationScope = assignedIsolationScope;
      }
      /**
       * Checks if this hub's version is older than the given version.
       *
       * @param version A version number to compare to.
       * @return True if the given version is newer; otherwise false.
       *
       * @deprecated This will be removed in v8.
       */
      isOlderThan(version3) {
        return this._version < version3;
      }
      /**
       * This binds the given client to the current scope.
       * @param client An SDK client (client) instance.
       *
       * @deprecated Use `initAndBind()` directly, or `setCurrentClient()` and/or `client.init()` instead.
       */
      bindClient(client) {
        const top = this.getStackTop();
        top.client = client;
        top.scope.setClient(client);
        if (client && client.setupIntegrations) {
          client.setupIntegrations();
        }
      }
      /**
       * @inheritDoc
       *
       * @deprecated Use `withScope` instead.
       */
      pushScope() {
        const scope2 = this.getScope().clone();
        this.getStack().push({
          // eslint-disable-next-line deprecation/deprecation
          client: this.getClient(),
          scope: scope2
        });
        return scope2;
      }
      /**
       * @inheritDoc
       *
       * @deprecated Use `withScope` instead.
       */
      popScope() {
        if (this.getStack().length <= 1)
          return false;
        return !!this.getStack().pop();
      }
      /**
       * @inheritDoc
       *
       * @deprecated Use `Sentry.withScope()` instead.
       */
      withScope(callback) {
        const scope2 = this.pushScope();
        let maybePromiseResult;
        try {
          maybePromiseResult = callback(scope2);
        } catch (e2) {
          this.popScope();
          throw e2;
        }
        if (utils.isThenable(maybePromiseResult)) {
          return maybePromiseResult.then(
            (res) => {
              this.popScope();
              return res;
            },
            (e2) => {
              this.popScope();
              throw e2;
            }
          );
        }
        this.popScope();
        return maybePromiseResult;
      }
      /**
       * @inheritDoc
       *
       * @deprecated Use `Sentry.getClient()` instead.
       */
      getClient() {
        return this.getStackTop().client;
      }
      /**
       * Returns the scope of the top stack.
       *
       * @deprecated Use `Sentry.getCurrentScope()` instead.
       */
      getScope() {
        return this.getStackTop().scope;
      }
      /**
       * @deprecated Use `Sentry.getIsolationScope()` instead.
       */
      getIsolationScope() {
        return this._isolationScope;
      }
      /**
       * Returns the scope stack for domains or the process.
       * @deprecated This will be removed in v8.
       */
      getStack() {
        return this._stack;
      }
      /**
       * Returns the topmost scope layer in the order domain > local > process.
       * @deprecated This will be removed in v8.
       */
      getStackTop() {
        return this._stack[this._stack.length - 1];
      }
      /**
       * @inheritDoc
       *
       * @deprecated Use `Sentry.captureException()` instead.
       */
      captureException(exception, hint) {
        const eventId = this._lastEventId = hint && hint.event_id ? hint.event_id : utils.uuid4();
        const syntheticException = new Error("Sentry syntheticException");
        this.getScope().captureException(exception, {
          originalException: exception,
          syntheticException,
          ...hint,
          event_id: eventId
        });
        return eventId;
      }
      /**
       * @inheritDoc
       *
       * @deprecated Use  `Sentry.captureMessage()` instead.
       */
      captureMessage(message, level, hint) {
        const eventId = this._lastEventId = hint && hint.event_id ? hint.event_id : utils.uuid4();
        const syntheticException = new Error(message);
        this.getScope().captureMessage(message, level, {
          originalException: message,
          syntheticException,
          ...hint,
          event_id: eventId
        });
        return eventId;
      }
      /**
       * @inheritDoc
       *
       * @deprecated Use `Sentry.captureEvent()` instead.
       */
      captureEvent(event, hint) {
        const eventId = hint && hint.event_id ? hint.event_id : utils.uuid4();
        if (!event.type) {
          this._lastEventId = eventId;
        }
        this.getScope().captureEvent(event, { ...hint, event_id: eventId });
        return eventId;
      }
      /**
       * @inheritDoc
       *
       * @deprecated This will be removed in v8.
       */
      lastEventId() {
        return this._lastEventId;
      }
      /**
       * @inheritDoc
       *
       * @deprecated Use `Sentry.addBreadcrumb()` instead.
       */
      addBreadcrumb(breadcrumb, hint) {
        const { scope: scope2, client } = this.getStackTop();
        if (!client)
          return;
        const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = client.getOptions && client.getOptions() || {};
        if (maxBreadcrumbs <= 0)
          return;
        const timestamp = utils.dateTimestampInSeconds();
        const mergedBreadcrumb = { timestamp, ...breadcrumb };
        const finalBreadcrumb = beforeBreadcrumb ? utils.consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) : mergedBreadcrumb;
        if (finalBreadcrumb === null)
          return;
        if (client.emit) {
          client.emit("beforeAddBreadcrumb", finalBreadcrumb, hint);
        }
        scope2.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);
      }
      /**
       * @inheritDoc
       * @deprecated Use `Sentry.setUser()` instead.
       */
      setUser(user) {
        this.getScope().setUser(user);
        this.getIsolationScope().setUser(user);
      }
      /**
       * @inheritDoc
       * @deprecated Use `Sentry.setTags()` instead.
       */
      setTags(tags) {
        this.getScope().setTags(tags);
        this.getIsolationScope().setTags(tags);
      }
      /**
       * @inheritDoc
       * @deprecated Use `Sentry.setExtras()` instead.
       */
      setExtras(extras) {
        this.getScope().setExtras(extras);
        this.getIsolationScope().setExtras(extras);
      }
      /**
       * @inheritDoc
       * @deprecated Use `Sentry.setTag()` instead.
       */
      setTag(key, value) {
        this.getScope().setTag(key, value);
        this.getIsolationScope().setTag(key, value);
      }
      /**
       * @inheritDoc
       * @deprecated Use `Sentry.setExtra()` instead.
       */
      setExtra(key, extra) {
        this.getScope().setExtra(key, extra);
        this.getIsolationScope().setExtra(key, extra);
      }
      /**
       * @inheritDoc
       * @deprecated Use `Sentry.setContext()` instead.
       */
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      setContext(name, context2) {
        this.getScope().setContext(name, context2);
        this.getIsolationScope().setContext(name, context2);
      }
      /**
       * @inheritDoc
       *
       * @deprecated Use `getScope()` directly.
       */
      configureScope(callback) {
        const { scope: scope2, client } = this.getStackTop();
        if (client) {
          callback(scope2);
        }
      }
      /**
       * @inheritDoc
       */
      // eslint-disable-next-line deprecation/deprecation
      run(callback) {
        const oldHub = makeMain(this);
        try {
          callback(this);
        } finally {
          makeMain(oldHub);
        }
      }
      /**
       * @inheritDoc
       * @deprecated Use `Sentry.getClient().getIntegrationByName()` instead.
       */
      getIntegration(integration) {
        const client = this.getClient();
        if (!client)
          return null;
        try {
          return client.getIntegration(integration);
        } catch (_oO) {
          debugBuild.DEBUG_BUILD && utils.logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);
          return null;
        }
      }
      /**
       * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.
       *
       * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a
       * new child span within the transaction or any span, call the respective `.startChild()` method.
       *
       * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.
       *
       * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its
       * finished child spans will be sent to Sentry.
       *
       * @param context Properties of the new `Transaction`.
       * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent
       * default values). See {@link Options.tracesSampler}.
       *
       * @returns The transaction which was just started
       *
       * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.
       */
      startTransaction(context2, customSamplingContext) {
        const result = this._callExtensionMethod("startTransaction", context2, customSamplingContext);
        if (debugBuild.DEBUG_BUILD && !result) {
          const client = this.getClient();
          if (!client) {
            utils.logger.warn(
              "Tracing extension 'startTransaction' is missing. You should 'init' the SDK before calling 'startTransaction'"
            );
          } else {
            utils.logger.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':
Sentry.addTracingExtensions();
Sentry.init({...});
`);
          }
        }
        return result;
      }
      /**
       * @inheritDoc
       * @deprecated Use `spanToTraceHeader()` instead.
       */
      traceHeaders() {
        return this._callExtensionMethod("traceHeaders");
      }
      /**
       * @inheritDoc
       *
       * @deprecated Use top level `captureSession` instead.
       */
      captureSession(endSession = false) {
        if (endSession) {
          return this.endSession();
        }
        this._sendSessionUpdate();
      }
      /**
       * @inheritDoc
       * @deprecated Use top level `endSession` instead.
       */
      endSession() {
        const layer = this.getStackTop();
        const scope2 = layer.scope;
        const session$1 = scope2.getSession();
        if (session$1) {
          session.closeSession(session$1);
        }
        this._sendSessionUpdate();
        scope2.setSession();
      }
      /**
       * @inheritDoc
       * @deprecated Use top level `startSession` instead.
       */
      startSession(context2) {
        const { scope: scope2, client } = this.getStackTop();
        const { release, environment = constants.DEFAULT_ENVIRONMENT } = client && client.getOptions() || {};
        const { userAgent } = utils.GLOBAL_OBJ.navigator || {};
        const session$1 = session.makeSession({
          release,
          environment,
          user: scope2.getUser(),
          ...userAgent && { userAgent },
          ...context2
        });
        const currentSession = scope2.getSession && scope2.getSession();
        if (currentSession && currentSession.status === "ok") {
          session.updateSession(currentSession, { status: "exited" });
        }
        this.endSession();
        scope2.setSession(session$1);
        return session$1;
      }
      /**
       * Returns if default PII should be sent to Sentry and propagated in ourgoing requests
       * when Tracing is used.
       *
       * @deprecated Use top-level `getClient().getOptions().sendDefaultPii` instead. This function
       * only unnecessarily increased API surface but only wrapped accessing the option.
       */
      shouldSendDefaultPii() {
        const client = this.getClient();
        const options = client && client.getOptions();
        return Boolean(options && options.sendDefaultPii);
      }
      /**
       * Sends the current Session on the scope
       */
      _sendSessionUpdate() {
        const { scope: scope2, client } = this.getStackTop();
        const session2 = scope2.getSession();
        if (session2 && client && client.captureSession) {
          client.captureSession(session2);
        }
      }
      /**
       * Calls global extension method and binding current instance to the function call
       */
      // @ts-expect-error Function lacks ending return statement and return type does not include 'undefined'. ts(2366)
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      _callExtensionMethod(method, ...args) {
        const carrier = getMainCarrier();
        const sentry = carrier.__SENTRY__;
        if (sentry && sentry.extensions && typeof sentry.extensions[method] === "function") {
          return sentry.extensions[method].apply(this, args);
        }
        debugBuild.DEBUG_BUILD && utils.logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);
      }
    };
    function getMainCarrier() {
      utils.GLOBAL_OBJ.__SENTRY__ = utils.GLOBAL_OBJ.__SENTRY__ || {
        extensions: {},
        hub: void 0
      };
      return utils.GLOBAL_OBJ;
    }
    function makeMain(hub) {
      const registry = getMainCarrier();
      const oldHub = getHubFromCarrier(registry);
      setHubOnCarrier(registry, hub);
      return oldHub;
    }
    function getCurrentHub() {
      const registry = getMainCarrier();
      if (registry.__SENTRY__ && registry.__SENTRY__.acs) {
        const hub = registry.__SENTRY__.acs.getCurrentHub();
        if (hub) {
          return hub;
        }
      }
      return getGlobalHub(registry);
    }
    function getIsolationScope() {
      return getCurrentHub().getIsolationScope();
    }
    function getGlobalHub(registry = getMainCarrier()) {
      if (!hasHubOnCarrier(registry) || // eslint-disable-next-line deprecation/deprecation
      getHubFromCarrier(registry).isOlderThan(API_VERSION)) {
        setHubOnCarrier(registry, new Hub());
      }
      return getHubFromCarrier(registry);
    }
    function ensureHubOnCarrier(carrier, parent = getGlobalHub()) {
      if (!hasHubOnCarrier(carrier) || // eslint-disable-next-line deprecation/deprecation
      getHubFromCarrier(carrier).isOlderThan(API_VERSION)) {
        const client = parent.getClient();
        const scope2 = parent.getScope();
        const isolationScope = parent.getIsolationScope();
        setHubOnCarrier(carrier, new Hub(client, scope2.clone(), isolationScope.clone()));
      }
    }
    function setAsyncContextStrategy(strategy) {
      const registry = getMainCarrier();
      registry.__SENTRY__ = registry.__SENTRY__ || {};
      registry.__SENTRY__.acs = strategy;
    }
    function runWithAsyncContext(callback, options = {}) {
      const registry = getMainCarrier();
      if (registry.__SENTRY__ && registry.__SENTRY__.acs) {
        return registry.__SENTRY__.acs.runWithAsyncContext(callback, options);
      }
      return callback();
    }
    function hasHubOnCarrier(carrier) {
      return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);
    }
    function getHubFromCarrier(carrier) {
      return utils.getGlobalSingleton("hub", () => new Hub(), carrier);
    }
    function setHubOnCarrier(carrier, hub) {
      if (!carrier)
        return false;
      const __SENTRY__ = carrier.__SENTRY__ = carrier.__SENTRY__ || {};
      __SENTRY__.hub = hub;
      return true;
    }
    exports.API_VERSION = API_VERSION;
    exports.Hub = Hub;
    exports.ensureHubOnCarrier = ensureHubOnCarrier;
    exports.getCurrentHub = getCurrentHub;
    exports.getHubFromCarrier = getHubFromCarrier;
    exports.getIsolationScope = getIsolationScope;
    exports.getMainCarrier = getMainCarrier;
    exports.makeMain = makeMain;
    exports.runWithAsyncContext = runWithAsyncContext;
    exports.setAsyncContextStrategy = setAsyncContextStrategy;
    exports.setHubOnCarrier = setHubOnCarrier;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/utils.js
var require_utils = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/utils.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var hub = require_hub();
    function getActiveTransaction(maybeHub) {
      const hub$1 = maybeHub || hub.getCurrentHub();
      const scope = hub$1.getScope();
      return scope.getTransaction();
    }
    var extractTraceparentData = utils.extractTraceparentData;
    exports.stripUrlQueryAndFragment = utils.stripUrlQueryAndFragment;
    exports.extractTraceparentData = extractTraceparentData;
    exports.getActiveTransaction = getActiveTransaction;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/errors.js
var require_errors = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/errors.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build2();
    var utils$1 = require_utils();
    var errorsInstrumented = false;
    function registerErrorInstrumentation() {
      if (errorsInstrumented) {
        return;
      }
      errorsInstrumented = true;
      utils.addGlobalErrorInstrumentationHandler(errorCallback);
      utils.addGlobalUnhandledRejectionInstrumentationHandler(errorCallback);
    }
    function errorCallback() {
      const activeTransaction = utils$1.getActiveTransaction();
      if (activeTransaction) {
        const status = "internal_error";
        debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Transaction: ${status} -> Global error occured`);
        activeTransaction.setStatus(status);
      }
    }
    errorCallback.tag = "sentry_tracingErrorCallback";
    exports.registerErrorInstrumentation = registerErrorInstrumentation;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/spanstatus.js
var require_spanstatus = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/spanstatus.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SpanStatus = void 0;
    (function(SpanStatus) {
      const Ok = "ok";
      SpanStatus["Ok"] = Ok;
      const DeadlineExceeded = "deadline_exceeded";
      SpanStatus["DeadlineExceeded"] = DeadlineExceeded;
      const Unauthenticated = "unauthenticated";
      SpanStatus["Unauthenticated"] = Unauthenticated;
      const PermissionDenied = "permission_denied";
      SpanStatus["PermissionDenied"] = PermissionDenied;
      const NotFound = "not_found";
      SpanStatus["NotFound"] = NotFound;
      const ResourceExhausted = "resource_exhausted";
      SpanStatus["ResourceExhausted"] = ResourceExhausted;
      const InvalidArgument = "invalid_argument";
      SpanStatus["InvalidArgument"] = InvalidArgument;
      const Unimplemented = "unimplemented";
      SpanStatus["Unimplemented"] = Unimplemented;
      const Unavailable = "unavailable";
      SpanStatus["Unavailable"] = Unavailable;
      const InternalError = "internal_error";
      SpanStatus["InternalError"] = InternalError;
      const UnknownError = "unknown_error";
      SpanStatus["UnknownError"] = UnknownError;
      const Cancelled = "cancelled";
      SpanStatus["Cancelled"] = Cancelled;
      const AlreadyExists = "already_exists";
      SpanStatus["AlreadyExists"] = AlreadyExists;
      const FailedPrecondition = "failed_precondition";
      SpanStatus["FailedPrecondition"] = FailedPrecondition;
      const Aborted = "aborted";
      SpanStatus["Aborted"] = Aborted;
      const OutOfRange = "out_of_range";
      SpanStatus["OutOfRange"] = OutOfRange;
      const DataLoss = "data_loss";
      SpanStatus["DataLoss"] = DataLoss;
    })(exports.SpanStatus || (exports.SpanStatus = {}));
    function getSpanStatusFromHttpCode(httpStatus) {
      if (httpStatus < 400 && httpStatus >= 100) {
        return "ok";
      }
      if (httpStatus >= 400 && httpStatus < 500) {
        switch (httpStatus) {
          case 401:
            return "unauthenticated";
          case 403:
            return "permission_denied";
          case 404:
            return "not_found";
          case 409:
            return "already_exists";
          case 413:
            return "failed_precondition";
          case 429:
            return "resource_exhausted";
          default:
            return "invalid_argument";
        }
      }
      if (httpStatus >= 500 && httpStatus < 600) {
        switch (httpStatus) {
          case 501:
            return "unimplemented";
          case 503:
            return "unavailable";
          case 504:
            return "deadline_exceeded";
          default:
            return "internal_error";
        }
      }
      return "unknown_error";
    }
    var spanStatusfromHttpCode = getSpanStatusFromHttpCode;
    function setHttpStatus(span, httpStatus) {
      span.setTag("http.status_code", String(httpStatus));
      span.setData("http.response.status_code", httpStatus);
      const spanStatus = getSpanStatusFromHttpCode(httpStatus);
      if (spanStatus !== "unknown_error") {
        span.setStatus(spanStatus);
      }
    }
    exports.getSpanStatusFromHttpCode = getSpanStatusFromHttpCode;
    exports.setHttpStatus = setHttpStatus;
    exports.spanStatusfromHttpCode = spanStatusfromHttpCode;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/utils/handleCallbackErrors.js
var require_handleCallbackErrors = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/utils/handleCallbackErrors.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    function handleCallbackErrors(fn, onError, onFinally = () => {
    }) {
      let maybePromiseResult;
      try {
        maybePromiseResult = fn();
      } catch (e2) {
        onError(e2);
        onFinally();
        throw e2;
      }
      return maybeHandlePromiseRejection(maybePromiseResult, onError, onFinally);
    }
    function maybeHandlePromiseRejection(value, onError, onFinally) {
      if (utils.isThenable(value)) {
        return value.then(
          (res) => {
            onFinally();
            return res;
          },
          (e2) => {
            onError(e2);
            onFinally();
            throw e2;
          }
        );
      }
      onFinally();
      return value;
    }
    exports.handleCallbackErrors = handleCallbackErrors;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/utils/hasTracingEnabled.js
var require_hasTracingEnabled = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/utils/hasTracingEnabled.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var exports$1 = require_exports();
    function hasTracingEnabled(maybeOptions) {
      if (typeof __SENTRY_TRACING__ === "boolean" && !__SENTRY_TRACING__) {
        return false;
      }
      const client = exports$1.getClient();
      const options = maybeOptions || client && client.getOptions();
      return !!options && (options.enableTracing || "tracesSampleRate" in options || "tracesSampler" in options);
    }
    exports.hasTracingEnabled = hasTracingEnabled;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/trace.js
var require_trace = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/trace.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build2();
    var hub = require_hub();
    var spanUtils = require_spanUtils();
    require_errors();
    require_spanstatus();
    var dynamicSamplingContext = require_dynamicSamplingContext();
    var exports$1 = require_exports();
    var handleCallbackErrors = require_handleCallbackErrors();
    var hasTracingEnabled = require_hasTracingEnabled();
    function trace(context2, callback, onError = () => {
    }, afterFinish = () => {
    }) {
      const hub$1 = hub.getCurrentHub();
      const scope = exports$1.getCurrentScope();
      const parentSpan = scope.getSpan();
      const spanContext = normalizeContext(context2);
      const activeSpan = createChildSpanOrTransaction(hub$1, {
        parentSpan,
        spanContext,
        forceTransaction: false,
        scope
      });
      scope.setSpan(activeSpan);
      return handleCallbackErrors.handleCallbackErrors(
        () => callback(activeSpan),
        (error) => {
          activeSpan && activeSpan.setStatus("internal_error");
          onError(error, activeSpan);
        },
        () => {
          activeSpan && activeSpan.end();
          scope.setSpan(parentSpan);
          afterFinish();
        }
      );
    }
    function startSpan(context2, callback) {
      const spanContext = normalizeContext(context2);
      return hub.runWithAsyncContext(() => {
        return exports$1.withScope(context2.scope, (scope) => {
          const hub$1 = hub.getCurrentHub();
          const parentSpan = scope.getSpan();
          const shouldSkipSpan = context2.onlyIfParent && !parentSpan;
          const activeSpan = shouldSkipSpan ? void 0 : createChildSpanOrTransaction(hub$1, {
            parentSpan,
            spanContext,
            forceTransaction: context2.forceTransaction,
            scope
          });
          return handleCallbackErrors.handleCallbackErrors(
            () => callback(activeSpan),
            () => {
              if (activeSpan) {
                const { status } = spanUtils.spanToJSON(activeSpan);
                if (!status || status === "ok") {
                  activeSpan.setStatus("internal_error");
                }
              }
            },
            () => activeSpan && activeSpan.end()
          );
        });
      });
    }
    var startActiveSpan = startSpan;
    function startSpanManual(context2, callback) {
      const spanContext = normalizeContext(context2);
      return hub.runWithAsyncContext(() => {
        return exports$1.withScope(context2.scope, (scope) => {
          const hub$1 = hub.getCurrentHub();
          const parentSpan = scope.getSpan();
          const shouldSkipSpan = context2.onlyIfParent && !parentSpan;
          const activeSpan = shouldSkipSpan ? void 0 : createChildSpanOrTransaction(hub$1, {
            parentSpan,
            spanContext,
            forceTransaction: context2.forceTransaction,
            scope
          });
          function finishAndSetSpan() {
            activeSpan && activeSpan.end();
          }
          return handleCallbackErrors.handleCallbackErrors(
            () => callback(activeSpan, finishAndSetSpan),
            () => {
              if (activeSpan && activeSpan.isRecording()) {
                const { status } = spanUtils.spanToJSON(activeSpan);
                if (!status || status === "ok") {
                  activeSpan.setStatus("internal_error");
                }
              }
            }
          );
        });
      });
    }
    function startInactiveSpan(context2) {
      if (!hasTracingEnabled.hasTracingEnabled()) {
        return void 0;
      }
      const spanContext = normalizeContext(context2);
      const hub$1 = hub.getCurrentHub();
      const parentSpan = context2.scope ? (
        // eslint-disable-next-line deprecation/deprecation
        context2.scope.getSpan()
      ) : getActiveSpan();
      const shouldSkipSpan = context2.onlyIfParent && !parentSpan;
      if (shouldSkipSpan) {
        return void 0;
      }
      const scope = context2.scope || exports$1.getCurrentScope();
      const temporaryScope = scope.clone();
      return createChildSpanOrTransaction(hub$1, {
        parentSpan,
        spanContext,
        forceTransaction: context2.forceTransaction,
        scope: temporaryScope
      });
    }
    function getActiveSpan() {
      return exports$1.getCurrentScope().getSpan();
    }
    var continueTrace = ({
      sentryTrace,
      baggage
    }, callback) => {
      const currentScope = exports$1.getCurrentScope();
      const { traceparentData, dynamicSamplingContext: dynamicSamplingContext2, propagationContext } = utils.tracingContextFromHeaders(
        sentryTrace,
        baggage
      );
      currentScope.setPropagationContext(propagationContext);
      if (debugBuild.DEBUG_BUILD && traceparentData) {
        utils.logger.log(`[Tracing] Continuing trace ${traceparentData.traceId}.`);
      }
      const transactionContext = {
        ...traceparentData,
        metadata: utils.dropUndefinedKeys({
          dynamicSamplingContext: dynamicSamplingContext2
        })
      };
      if (!callback) {
        return transactionContext;
      }
      return hub.runWithAsyncContext(() => {
        return callback(transactionContext);
      });
    };
    function createChildSpanOrTransaction(hub$1, {
      parentSpan,
      spanContext,
      forceTransaction,
      scope
    }) {
      if (!hasTracingEnabled.hasTracingEnabled()) {
        return void 0;
      }
      const isolationScope = hub.getIsolationScope();
      let span;
      if (parentSpan && !forceTransaction) {
        span = parentSpan.startChild(spanContext);
      } else if (parentSpan) {
        const dsc = dynamicSamplingContext.getDynamicSamplingContextFromSpan(parentSpan);
        const { traceId, spanId: parentSpanId } = parentSpan.spanContext();
        const sampled = spanUtils.spanIsSampled(parentSpan);
        span = hub$1.startTransaction({
          traceId,
          parentSpanId,
          parentSampled: sampled,
          ...spanContext,
          metadata: {
            dynamicSamplingContext: dsc,
            // eslint-disable-next-line deprecation/deprecation
            ...spanContext.metadata
          }
        });
      } else {
        const { traceId, dsc, parentSpanId, sampled } = {
          ...isolationScope.getPropagationContext(),
          ...scope.getPropagationContext()
        };
        span = hub$1.startTransaction({
          traceId,
          parentSpanId,
          parentSampled: sampled,
          ...spanContext,
          metadata: {
            dynamicSamplingContext: dsc,
            // eslint-disable-next-line deprecation/deprecation
            ...spanContext.metadata
          }
        });
      }
      scope.setSpan(span);
      setCapturedScopesOnSpan(span, scope, isolationScope);
      return span;
    }
    function normalizeContext(context2) {
      if (context2.startTime) {
        const ctx = { ...context2 };
        ctx.startTimestamp = spanUtils.spanTimeInputToSeconds(context2.startTime);
        delete ctx.startTime;
        return ctx;
      }
      return context2;
    }
    var SCOPE_ON_START_SPAN_FIELD = "_sentryScope";
    var ISOLATION_SCOPE_ON_START_SPAN_FIELD = "_sentryIsolationScope";
    function setCapturedScopesOnSpan(span, scope, isolationScope) {
      if (span) {
        utils.addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, isolationScope);
        utils.addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope);
      }
    }
    function getCapturedScopesOnSpan(span) {
      return {
        scope: span[SCOPE_ON_START_SPAN_FIELD],
        isolationScope: span[ISOLATION_SCOPE_ON_START_SPAN_FIELD]
      };
    }
    exports.continueTrace = continueTrace;
    exports.getActiveSpan = getActiveSpan;
    exports.getCapturedScopesOnSpan = getCapturedScopesOnSpan;
    exports.startActiveSpan = startActiveSpan;
    exports.startInactiveSpan = startInactiveSpan;
    exports.startSpan = startSpan;
    exports.startSpanManual = startSpanManual;
    exports.trace = trace;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metrics/metric-summary.js
var require_metric_summary = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metrics/metric-summary.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    require_debug_build2();
    require_errors();
    require_spanstatus();
    var trace = require_trace();
    var SPAN_METRIC_SUMMARY;
    function getMetricStorageForSpan(span) {
      return SPAN_METRIC_SUMMARY ? SPAN_METRIC_SUMMARY.get(span) : void 0;
    }
    function getMetricSummaryJsonForSpan(span) {
      const storage = getMetricStorageForSpan(span);
      if (!storage) {
        return void 0;
      }
      const output = {};
      for (const [, [exportKey, summary]] of storage) {
        if (!output[exportKey]) {
          output[exportKey] = [];
        }
        output[exportKey].push(utils.dropUndefinedKeys(summary));
      }
      return output;
    }
    function updateMetricSummaryOnActiveSpan(metricType, sanitizedName, value, unit, tags, bucketKey) {
      const span = trace.getActiveSpan();
      if (span) {
        const storage = getMetricStorageForSpan(span) || /* @__PURE__ */ new Map();
        const exportKey = `${metricType}:${sanitizedName}@${unit}`;
        const bucketItem = storage.get(bucketKey);
        if (bucketItem) {
          const [, summary] = bucketItem;
          storage.set(bucketKey, [
            exportKey,
            {
              min: Math.min(summary.min, value),
              max: Math.max(summary.max, value),
              count: summary.count += 1,
              sum: summary.sum += value,
              tags: summary.tags
            }
          ]);
        } else {
          storage.set(bucketKey, [
            exportKey,
            {
              min: value,
              max: value,
              count: 1,
              sum: value,
              tags
            }
          ]);
        }
        if (!SPAN_METRIC_SUMMARY) {
          SPAN_METRIC_SUMMARY = /* @__PURE__ */ new WeakMap();
        }
        SPAN_METRIC_SUMMARY.set(span, storage);
      }
    }
    exports.getMetricSummaryJsonForSpan = getMetricSummaryJsonForSpan;
    exports.updateMetricSummaryOnActiveSpan = updateMetricSummaryOnActiveSpan;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/semanticAttributes.js
var require_semanticAttributes = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/semanticAttributes.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = "sentry.source";
    var SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = "sentry.sample_rate";
    var SEMANTIC_ATTRIBUTE_SENTRY_OP = "sentry.op";
    var SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = "sentry.origin";
    var SEMANTIC_ATTRIBUTE_PROFILE_ID = "profile_id";
    exports.SEMANTIC_ATTRIBUTE_PROFILE_ID = SEMANTIC_ATTRIBUTE_PROFILE_ID;
    exports.SEMANTIC_ATTRIBUTE_SENTRY_OP = SEMANTIC_ATTRIBUTE_SENTRY_OP;
    exports.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN;
    exports.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE;
    exports.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = SEMANTIC_ATTRIBUTE_SENTRY_SOURCE;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/span.js
var require_span = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/span.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build2();
    var metricSummary = require_metric_summary();
    var semanticAttributes = require_semanticAttributes();
    var getRootSpan = require_getRootSpan();
    var spanUtils = require_spanUtils();
    var spanstatus = require_spanstatus();
    var SpanRecorder = class {
      constructor(maxlen = 1e3) {
        this._maxlen = maxlen;
        this.spans = [];
      }
      /**
       * This is just so that we don't run out of memory while recording a lot
       * of spans. At some point we just stop and flush out the start of the
       * trace tree (i.e.the first n spans with the smallest
       * start_timestamp).
       */
      add(span) {
        if (this.spans.length > this._maxlen) {
          span.spanRecorder = void 0;
        } else {
          this.spans.push(span);
        }
      }
    };
    var Span = class _Span {
      /**
       * Tags for the span.
       * @deprecated Use `spanToJSON(span).atttributes` instead.
       */
      /**
       * Data for the span.
       * @deprecated Use `spanToJSON(span).atttributes` instead.
       */
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      /**
       * List of spans that were finalized
       *
       * @deprecated This property will no longer be public. Span recording will be handled internally.
       */
      /**
       * @inheritDoc
       * @deprecated Use top level `Sentry.getRootSpan()` instead
       */
      /**
       * The instrumenter that created this span.
       *
       * TODO (v8): This can probably be replaced by an `instanceOf` check of the span class.
       *            the instrumenter can only be sentry or otel so we can check the span instance
       *            to verify which one it is and remove this field entirely.
       *
       * @deprecated This field will be removed.
       */
      /** Epoch timestamp in seconds when the span started. */
      /** Epoch timestamp in seconds when the span ended. */
      /** Internal keeper of the status */
      /**
       * You should never call the constructor manually, always use `Sentry.startTransaction()`
       * or call `startChild()` on an existing span.
       * @internal
       * @hideconstructor
       * @hidden
       */
      constructor(spanContext = {}) {
        this._traceId = spanContext.traceId || utils.uuid4();
        this._spanId = spanContext.spanId || utils.uuid4().substring(16);
        this._startTime = spanContext.startTimestamp || utils.timestampInSeconds();
        this.tags = spanContext.tags ? { ...spanContext.tags } : {};
        this.data = spanContext.data ? { ...spanContext.data } : {};
        this.instrumenter = spanContext.instrumenter || "sentry";
        this._attributes = {};
        this.setAttributes({
          [semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanContext.origin || "manual",
          [semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op,
          ...spanContext.attributes
        });
        this._name = spanContext.name || spanContext.description;
        if (spanContext.parentSpanId) {
          this._parentSpanId = spanContext.parentSpanId;
        }
        if ("sampled" in spanContext) {
          this._sampled = spanContext.sampled;
        }
        if (spanContext.status) {
          this._status = spanContext.status;
        }
        if (spanContext.endTimestamp) {
          this._endTime = spanContext.endTimestamp;
        }
        if (spanContext.exclusiveTime !== void 0) {
          this._exclusiveTime = spanContext.exclusiveTime;
        }
        this._measurements = spanContext.measurements ? { ...spanContext.measurements } : {};
      }
      // This rule conflicts with another eslint rule :(
      /* eslint-disable @typescript-eslint/member-ordering */
      /**
       * An alias for `description` of the Span.
       * @deprecated Use `spanToJSON(span).description` instead.
       */
      get name() {
        return this._name || "";
      }
      /**
       * Update the name of the span.
       * @deprecated Use `spanToJSON(span).description` instead.
       */
      set name(name) {
        this.updateName(name);
      }
      /**
       * Get the description of the Span.
       * @deprecated Use `spanToJSON(span).description` instead.
       */
      get description() {
        return this._name;
      }
      /**
       * Get the description of the Span.
       * @deprecated Use `spanToJSON(span).description` instead.
       */
      set description(description) {
        this._name = description;
      }
      /**
       * The ID of the trace.
       * @deprecated Use `spanContext().traceId` instead.
       */
      get traceId() {
        return this._traceId;
      }
      /**
       * The ID of the trace.
       * @deprecated You cannot update the traceId of a span after span creation.
       */
      set traceId(traceId) {
        this._traceId = traceId;
      }
      /**
       * The ID of the span.
       * @deprecated Use `spanContext().spanId` instead.
       */
      get spanId() {
        return this._spanId;
      }
      /**
       * The ID of the span.
       * @deprecated You cannot update the spanId of a span after span creation.
       */
      set spanId(spanId) {
        this._spanId = spanId;
      }
      /**
       * @inheritDoc
       *
       * @deprecated Use `startSpan` functions instead.
       */
      set parentSpanId(string) {
        this._parentSpanId = string;
      }
      /**
       * @inheritDoc
       *
       * @deprecated Use `spanToJSON(span).parent_span_id` instead.
       */
      get parentSpanId() {
        return this._parentSpanId;
      }
      /**
       * Was this span chosen to be sent as part of the sample?
       * @deprecated Use `isRecording()` instead.
       */
      get sampled() {
        return this._sampled;
      }
      /**
       * Was this span chosen to be sent as part of the sample?
       * @deprecated You cannot update the sampling decision of a span after span creation.
       */
      set sampled(sampled) {
        this._sampled = sampled;
      }
      /**
       * Attributes for the span.
       * @deprecated Use `spanToJSON(span).atttributes` instead.
       */
      get attributes() {
        return this._attributes;
      }
      /**
       * Attributes for the span.
       * @deprecated Use `setAttributes()` instead.
       */
      set attributes(attributes) {
        this._attributes = attributes;
      }
      /**
       * Timestamp in seconds (epoch time) indicating when the span started.
       * @deprecated Use `spanToJSON()` instead.
       */
      get startTimestamp() {
        return this._startTime;
      }
      /**
       * Timestamp in seconds (epoch time) indicating when the span started.
       * @deprecated In v8, you will not be able to update the span start time after creation.
       */
      set startTimestamp(startTime) {
        this._startTime = startTime;
      }
      /**
       * Timestamp in seconds when the span ended.
       * @deprecated Use `spanToJSON()` instead.
       */
      get endTimestamp() {
        return this._endTime;
      }
      /**
       * Timestamp in seconds when the span ended.
       * @deprecated Set the end time via `span.end()` instead.
       */
      set endTimestamp(endTime) {
        this._endTime = endTime;
      }
      /**
       * The status of the span.
       *
       * @deprecated Use `spanToJSON().status` instead to get the status.
       */
      get status() {
        return this._status;
      }
      /**
       * The status of the span.
       *
       * @deprecated Use `.setStatus()` instead to set or update the status.
       */
      set status(status) {
        this._status = status;
      }
      /**
       * Operation of the span
       *
       * @deprecated Use `spanToJSON().op` to read the op instead.
       */
      get op() {
        return this._attributes[semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_OP];
      }
      /**
       * Operation of the span
       *
       * @deprecated Use `startSpan()` functions to set or `span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'op')
       *             to update the span instead.
       */
      set op(op) {
        this.setAttribute(semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_OP, op);
      }
      /**
       * The origin of the span, giving context about what created the span.
       *
       * @deprecated Use `spanToJSON().origin` to read the origin instead.
       */
      get origin() {
        return this._attributes[semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN];
      }
      /**
       * The origin of the span, giving context about what created the span.
       *
       * @deprecated Use `startSpan()` functions to set the origin instead.
       */
      set origin(origin) {
        this.setAttribute(semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, origin);
      }
      /* eslint-enable @typescript-eslint/member-ordering */
      /** @inheritdoc */
      spanContext() {
        const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this;
        return {
          spanId,
          traceId,
          traceFlags: sampled ? spanUtils.TRACE_FLAG_SAMPLED : spanUtils.TRACE_FLAG_NONE
        };
      }
      /**
       * Creates a new `Span` while setting the current `Span.id` as `parentSpanId`.
       * Also the `sampled` decision will be inherited.
       *
       * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.
       */
      startChild(spanContext) {
        const childSpan = new _Span({
          ...spanContext,
          parentSpanId: this._spanId,
          sampled: this._sampled,
          traceId: this._traceId
        });
        childSpan.spanRecorder = this.spanRecorder;
        if (childSpan.spanRecorder) {
          childSpan.spanRecorder.add(childSpan);
        }
        const rootSpan = getRootSpan.getRootSpan(this);
        childSpan.transaction = rootSpan;
        if (debugBuild.DEBUG_BUILD && rootSpan) {
          const opStr = spanContext && spanContext.op || "< unknown op >";
          const nameStr = spanUtils.spanToJSON(childSpan).description || "< unknown name >";
          const idStr = rootSpan.spanContext().spanId;
          const logMessage = `[Tracing] Starting '${opStr}' span on transaction '${nameStr}' (${idStr}).`;
          utils.logger.log(logMessage);
          this._logMessage = logMessage;
        }
        return childSpan;
      }
      /**
       * Sets the tag attribute on the current span.
       *
       * Can also be used to unset a tag, by passing `undefined`.
       *
       * @param key Tag key
       * @param value Tag value
       * @deprecated Use `setAttribute()` instead.
       */
      setTag(key, value) {
        this.tags = { ...this.tags, [key]: value };
        return this;
      }
      /**
       * Sets the data attribute on the current span
       * @param key Data key
       * @param value Data value
       * @deprecated Use `setAttribute()` instead.
       */
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      setData(key, value) {
        this.data = { ...this.data, [key]: value };
        return this;
      }
      /** @inheritdoc */
      setAttribute(key, value) {
        if (value === void 0) {
          delete this._attributes[key];
        } else {
          this._attributes[key] = value;
        }
      }
      /** @inheritdoc */
      setAttributes(attributes) {
        Object.keys(attributes).forEach((key) => this.setAttribute(key, attributes[key]));
      }
      /**
       * @inheritDoc
       */
      setStatus(value) {
        this._status = value;
        return this;
      }
      /**
       * @inheritDoc
       * @deprecated Use top-level `setHttpStatus()` instead.
       */
      setHttpStatus(httpStatus) {
        spanstatus.setHttpStatus(this, httpStatus);
        return this;
      }
      /**
       * @inheritdoc
       *
       * @deprecated Use `.updateName()` instead.
       */
      setName(name) {
        this.updateName(name);
      }
      /**
       * @inheritDoc
       */
      updateName(name) {
        this._name = name;
        return this;
      }
      /**
       * @inheritDoc
       *
       * @deprecated Use `spanToJSON(span).status === 'ok'` instead.
       */
      isSuccess() {
        return this._status === "ok";
      }
      /**
       * @inheritDoc
       *
       * @deprecated Use `.end()` instead.
       */
      finish(endTimestamp) {
        return this.end(endTimestamp);
      }
      /** @inheritdoc */
      end(endTimestamp) {
        if (this._endTime) {
          return;
        }
        const rootSpan = getRootSpan.getRootSpan(this);
        if (debugBuild.DEBUG_BUILD && // Don't call this for transactions
        rootSpan && rootSpan.spanContext().spanId !== this._spanId) {
          const logMessage = this._logMessage;
          if (logMessage) {
            utils.logger.log(logMessage.replace("Starting", "Finishing"));
          }
        }
        this._endTime = spanUtils.spanTimeInputToSeconds(endTimestamp);
      }
      /**
       * @inheritDoc
       *
       * @deprecated Use `spanToTraceHeader()` instead.
       */
      toTraceparent() {
        return spanUtils.spanToTraceHeader(this);
      }
      /**
       * @inheritDoc
       *
       * @deprecated Use `spanToJSON()` or access the fields directly instead.
       */
      toContext() {
        return utils.dropUndefinedKeys({
          data: this._getData(),
          description: this._name,
          endTimestamp: this._endTime,
          // eslint-disable-next-line deprecation/deprecation
          op: this.op,
          parentSpanId: this._parentSpanId,
          sampled: this._sampled,
          spanId: this._spanId,
          startTimestamp: this._startTime,
          status: this._status,
          // eslint-disable-next-line deprecation/deprecation
          tags: this.tags,
          traceId: this._traceId
        });
      }
      /**
       * @inheritDoc
       *
       * @deprecated Update the fields directly instead.
       */
      updateWithContext(spanContext) {
        this.data = spanContext.data || {};
        this._name = spanContext.name || spanContext.description;
        this._endTime = spanContext.endTimestamp;
        this.op = spanContext.op;
        this._parentSpanId = spanContext.parentSpanId;
        this._sampled = spanContext.sampled;
        this._spanId = spanContext.spanId || this._spanId;
        this._startTime = spanContext.startTimestamp || this._startTime;
        this._status = spanContext.status;
        this.tags = spanContext.tags || {};
        this._traceId = spanContext.traceId || this._traceId;
        return this;
      }
      /**
       * @inheritDoc
       *
       * @deprecated Use `spanToTraceContext()` util function instead.
       */
      getTraceContext() {
        return spanUtils.spanToTraceContext(this);
      }
      /**
       * Get JSON representation of this span.
       *
       * @hidden
       * @internal This method is purely for internal purposes and should not be used outside
       * of SDK code. If you need to get a JSON representation of a span,
       * use `spanToJSON(span)` instead.
       */
      getSpanJSON() {
        return utils.dropUndefinedKeys({
          data: this._getData(),
          description: this._name,
          op: this._attributes[semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_OP],
          parent_span_id: this._parentSpanId,
          span_id: this._spanId,
          start_timestamp: this._startTime,
          status: this._status,
          // eslint-disable-next-line deprecation/deprecation
          tags: Object.keys(this.tags).length > 0 ? this.tags : void 0,
          timestamp: this._endTime,
          trace_id: this._traceId,
          origin: this._attributes[semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN],
          _metrics_summary: metricSummary.getMetricSummaryJsonForSpan(this),
          profile_id: this._attributes[semanticAttributes.SEMANTIC_ATTRIBUTE_PROFILE_ID],
          exclusive_time: this._exclusiveTime,
          measurements: Object.keys(this._measurements).length > 0 ? this._measurements : void 0
        });
      }
      /** @inheritdoc */
      isRecording() {
        return !this._endTime && !!this._sampled;
      }
      /**
       * Convert the object to JSON.
       * @deprecated Use `spanToJSON(span)` instead.
       */
      toJSON() {
        return this.getSpanJSON();
      }
      /**
       * Get the merged data for this span.
       * For now, this combines `data` and `attributes` together,
       * until eventually we can ingest `attributes` directly.
       */
      _getData() {
        const { data, _attributes: attributes } = this;
        const hasData = Object.keys(data).length > 0;
        const hasAttributes = Object.keys(attributes).length > 0;
        if (!hasData && !hasAttributes) {
          return void 0;
        }
        if (hasData && hasAttributes) {
          return {
            ...data,
            ...attributes
          };
        }
        return hasData ? data : attributes;
      }
    };
    exports.Span = Span;
    exports.SpanRecorder = SpanRecorder;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/transaction.js
var require_transaction = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/transaction.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build2();
    var hub = require_hub();
    var metricSummary = require_metric_summary();
    var semanticAttributes = require_semanticAttributes();
    var spanUtils = require_spanUtils();
    var dynamicSamplingContext = require_dynamicSamplingContext();
    var span = require_span();
    var trace = require_trace();
    var Transaction2 = class extends span.Span {
      /**
       * The reference to the current hub.
       */
      // eslint-disable-next-line deprecation/deprecation
      // DO NOT yet remove this property, it is used in a hack for v7 backwards compatibility.
      /**
       * This constructor should never be called manually. Those instrumenting tracing should use
       * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.
       * @internal
       * @hideconstructor
       * @hidden
       *
       * @deprecated Transactions will be removed in v8. Use spans instead.
       */
      // eslint-disable-next-line deprecation/deprecation
      constructor(transactionContext, hub$1) {
        super(transactionContext);
        this._contexts = {};
        this._hub = hub$1 || hub.getCurrentHub();
        this._name = transactionContext.name || "";
        this._metadata = {
          // eslint-disable-next-line deprecation/deprecation
          ...transactionContext.metadata
        };
        this._trimEnd = transactionContext.trimEnd;
        this.transaction = this;
        const incomingDynamicSamplingContext = this._metadata.dynamicSamplingContext;
        if (incomingDynamicSamplingContext) {
          this._frozenDynamicSamplingContext = { ...incomingDynamicSamplingContext };
        }
      }
      // This sadly conflicts with the getter/setter ordering :(
      /* eslint-disable @typescript-eslint/member-ordering */
      /**
       * Getter for `name` property.
       * @deprecated Use `spanToJSON(span).description` instead.
       */
      get name() {
        return this._name;
      }
      /**
       * Setter for `name` property, which also sets `source` as custom.
       * @deprecated Use `updateName()` and `setMetadata()` instead.
       */
      set name(newName) {
        this.setName(newName);
      }
      /**
       * Get the metadata for this transaction.
       * @deprecated Use `spanGetMetadata(transaction)` instead.
       */
      get metadata() {
        return {
          // Defaults
          // eslint-disable-next-line deprecation/deprecation
          source: "custom",
          spanMetadata: {},
          // Legacy metadata
          ...this._metadata,
          // From attributes
          ...this._attributes[semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] && {
            source: this._attributes[semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]
          },
          ...this._attributes[semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] && {
            sampleRate: this._attributes[semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]
          }
        };
      }
      /**
       * Update the metadata for this transaction.
       * @deprecated Use `spanGetMetadata(transaction)` instead.
       */
      set metadata(metadata) {
        this._metadata = metadata;
      }
      /* eslint-enable @typescript-eslint/member-ordering */
      /**
       * Setter for `name` property, which also sets `source` on the metadata.
       *
       * @deprecated Use `.updateName()` and `.setAttribute()` instead.
       */
      setName(name, source = "custom") {
        this._name = name;
        this.setAttribute(semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source);
      }
      /** @inheritdoc */
      updateName(name) {
        this._name = name;
        return this;
      }
      /**
       * Attaches SpanRecorder to the span itself
       * @param maxlen maximum number of spans that can be recorded
       */
      initSpanRecorder(maxlen = 1e3) {
        if (!this.spanRecorder) {
          this.spanRecorder = new span.SpanRecorder(maxlen);
        }
        this.spanRecorder.add(this);
      }
      /**
       * Set the context of a transaction event.
       * @deprecated Use either `.setAttribute()`, or set the context on the scope before creating the transaction.
       */
      setContext(key, context2) {
        if (context2 === null) {
          delete this._contexts[key];
        } else {
          this._contexts[key] = context2;
        }
      }
      /**
       * @inheritDoc
       *
       * @deprecated Use top-level `setMeasurement()` instead.
       */
      setMeasurement(name, value, unit = "") {
        this._measurements[name] = { value, unit };
      }
      /**
       * Store metadata on this transaction.
       * @deprecated Use attributes or store data on the scope instead.
       */
      setMetadata(newMetadata) {
        this._metadata = { ...this._metadata, ...newMetadata };
      }
      /**
       * @inheritDoc
       */
      end(endTimestamp) {
        const timestampInS = spanUtils.spanTimeInputToSeconds(endTimestamp);
        const transaction = this._finishTransaction(timestampInS);
        if (!transaction) {
          return void 0;
        }
        return this._hub.captureEvent(transaction);
      }
      /**
       * @inheritDoc
       */
      toContext() {
        const spanContext = super.toContext();
        return utils.dropUndefinedKeys({
          ...spanContext,
          name: this._name,
          trimEnd: this._trimEnd
        });
      }
      /**
       * @inheritDoc
       */
      updateWithContext(transactionContext) {
        super.updateWithContext(transactionContext);
        this._name = transactionContext.name || "";
        this._trimEnd = transactionContext.trimEnd;
        return this;
      }
      /**
       * @inheritdoc
       *
       * @experimental
       *
       * @deprecated Use top-level `getDynamicSamplingContextFromSpan` instead.
       */
      getDynamicSamplingContext() {
        return dynamicSamplingContext.getDynamicSamplingContextFromSpan(this);
      }
      /**
       * Override the current hub with a new one.
       * Used if you want another hub to finish the transaction.
       *
       * @internal
       */
      // eslint-disable-next-line deprecation/deprecation
      setHub(hub2) {
        this._hub = hub2;
      }
      /**
       * Get the profile id of the transaction.
       */
      getProfileId() {
        if (this._contexts !== void 0 && this._contexts["profile"] !== void 0) {
          return this._contexts["profile"].profile_id;
        }
        return void 0;
      }
      /**
       * Finish the transaction & prepare the event to send to Sentry.
       */
      _finishTransaction(endTimestamp) {
        if (this._endTime !== void 0) {
          return void 0;
        }
        if (!this._name) {
          debugBuild.DEBUG_BUILD && utils.logger.warn("Transaction has no name, falling back to `<unlabeled transaction>`.");
          this._name = "<unlabeled transaction>";
        }
        super.end(endTimestamp);
        const client = this._hub.getClient();
        if (client && client.emit) {
          client.emit("finishTransaction", this);
        }
        if (this._sampled !== true) {
          debugBuild.DEBUG_BUILD && utils.logger.log("[Tracing] Discarding transaction because its trace was not chosen to be sampled.");
          if (client) {
            client.recordDroppedEvent("sample_rate", "transaction");
          }
          return void 0;
        }
        const finishedSpans = this.spanRecorder ? (
          // eslint-disable-next-line deprecation/deprecation
          this.spanRecorder.spans.filter((span2) => span2 !== this && spanUtils.spanToJSON(span2).timestamp)
        ) : [];
        if (this._trimEnd && finishedSpans.length > 0) {
          const endTimes = finishedSpans.map((span2) => spanUtils.spanToJSON(span2).timestamp).filter(Boolean);
          this._endTime = endTimes.reduce((prev, current) => {
            return prev > current ? prev : current;
          });
        }
        const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = trace.getCapturedScopesOnSpan(this);
        const { metadata } = this;
        const { source } = metadata;
        const transaction = {
          contexts: {
            ...this._contexts,
            // We don't want to override trace context
            trace: spanUtils.spanToTraceContext(this)
          },
          // TODO: Pass spans serialized via `spanToJSON()` here instead in v8.
          spans: finishedSpans,
          start_timestamp: this._startTime,
          // eslint-disable-next-line deprecation/deprecation
          tags: this.tags,
          timestamp: this._endTime,
          transaction: this._name,
          type: "transaction",
          sdkProcessingMetadata: {
            ...metadata,
            capturedSpanScope,
            capturedSpanIsolationScope,
            ...utils.dropUndefinedKeys({
              dynamicSamplingContext: dynamicSamplingContext.getDynamicSamplingContextFromSpan(this)
            })
          },
          _metrics_summary: metricSummary.getMetricSummaryJsonForSpan(this),
          ...source && {
            transaction_info: {
              source
            }
          }
        };
        const hasMeasurements = Object.keys(this._measurements).length > 0;
        if (hasMeasurements) {
          debugBuild.DEBUG_BUILD && utils.logger.log(
            "[Measurements] Adding measurements to transaction",
            JSON.stringify(this._measurements, void 0, 2)
          );
          transaction.measurements = this._measurements;
        }
        debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Finishing ${this.op} transaction: ${this._name}.`);
        return transaction;
      }
    };
    exports.Transaction = Transaction2;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/idletransaction.js
var require_idletransaction = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/idletransaction.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build2();
    var spanUtils = require_spanUtils();
    var span = require_span();
    var transaction = require_transaction();
    var TRACING_DEFAULTS = {
      idleTimeout: 1e3,
      finalTimeout: 3e4,
      heartbeatInterval: 5e3
    };
    var FINISH_REASON_TAG = "finishReason";
    var IDLE_TRANSACTION_FINISH_REASONS = [
      "heartbeatFailed",
      "idleTimeout",
      "documentHidden",
      "finalTimeout",
      "externalFinish",
      "cancelled"
    ];
    var IdleTransactionSpanRecorder = class extends span.SpanRecorder {
      constructor(_pushActivity, _popActivity, transactionSpanId, maxlen) {
        super(maxlen);
        this._pushActivity = _pushActivity;
        this._popActivity = _popActivity;
        this.transactionSpanId = transactionSpanId;
      }
      /**
       * @inheritDoc
       */
      add(span2) {
        if (span2.spanContext().spanId !== this.transactionSpanId) {
          const originalEnd = span2.end;
          span2.end = (...rest) => {
            this._popActivity(span2.spanContext().spanId);
            return originalEnd.apply(span2, rest);
          };
          if (spanUtils.spanToJSON(span2).timestamp === void 0) {
            this._pushActivity(span2.spanContext().spanId);
          }
        }
        super.add(span2);
      }
    };
    var IdleTransaction = class extends transaction.Transaction {
      // Activities store a list of active spans
      // Track state of activities in previous heartbeat
      // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.
      // We should not use heartbeat if we finished a transaction
      // Idle timeout was canceled and we should finish the transaction with the last span end.
      /**
       * Timer that tracks Transaction idleTimeout
       */
      /**
       * @deprecated Transactions will be removed in v8. Use spans instead.
       */
      constructor(transactionContext, _idleHub, _idleTimeout = TRACING_DEFAULTS.idleTimeout, _finalTimeout = TRACING_DEFAULTS.finalTimeout, _heartbeatInterval = TRACING_DEFAULTS.heartbeatInterval, _onScope = false, delayAutoFinishUntilSignal = false) {
        super(transactionContext, _idleHub);
        this._idleHub = _idleHub;
        this._idleTimeout = _idleTimeout;
        this._finalTimeout = _finalTimeout;
        this._heartbeatInterval = _heartbeatInterval;
        this._onScope = _onScope;
        this.activities = {};
        this._heartbeatCounter = 0;
        this._finished = false;
        this._idleTimeoutCanceledPermanently = false;
        this._beforeFinishCallbacks = [];
        this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[4];
        this._autoFinishAllowed = !delayAutoFinishUntilSignal;
        if (_onScope) {
          debugBuild.DEBUG_BUILD && utils.logger.log(`Setting idle transaction on scope. Span ID: ${this.spanContext().spanId}`);
          _idleHub.getScope().setSpan(this);
        }
        if (!delayAutoFinishUntilSignal) {
          this._restartIdleTimeout();
        }
        setTimeout(() => {
          if (!this._finished) {
            this.setStatus("deadline_exceeded");
            this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[3];
            this.end();
          }
        }, this._finalTimeout);
      }
      /** {@inheritDoc} */
      end(endTimestamp) {
        const endTimestampInS = spanUtils.spanTimeInputToSeconds(endTimestamp);
        this._finished = true;
        this.activities = {};
        if (this.op === "ui.action.click") {
          this.setAttribute(FINISH_REASON_TAG, this._finishReason);
        }
        if (this.spanRecorder) {
          debugBuild.DEBUG_BUILD && // eslint-disable-next-line deprecation/deprecation
          utils.logger.log("[Tracing] finishing IdleTransaction", new Date(endTimestampInS * 1e3).toISOString(), this.op);
          for (const callback of this._beforeFinishCallbacks) {
            callback(this, endTimestampInS);
          }
          this.spanRecorder.spans = this.spanRecorder.spans.filter((span2) => {
            if (span2.spanContext().spanId === this.spanContext().spanId) {
              return true;
            }
            if (!spanUtils.spanToJSON(span2).timestamp) {
              span2.setStatus("cancelled");
              span2.end(endTimestampInS);
              debugBuild.DEBUG_BUILD && utils.logger.log("[Tracing] cancelling span since transaction ended early", JSON.stringify(span2, void 0, 2));
            }
            const { start_timestamp: startTime, timestamp: endTime } = spanUtils.spanToJSON(span2);
            const spanStartedBeforeTransactionFinish = startTime && startTime < endTimestampInS;
            const timeoutWithMarginOfError = (this._finalTimeout + this._idleTimeout) / 1e3;
            const spanEndedBeforeFinalTimeout = endTime && startTime && endTime - startTime < timeoutWithMarginOfError;
            if (debugBuild.DEBUG_BUILD) {
              const stringifiedSpan = JSON.stringify(span2, void 0, 2);
              if (!spanStartedBeforeTransactionFinish) {
                utils.logger.log("[Tracing] discarding Span since it happened after Transaction was finished", stringifiedSpan);
              } else if (!spanEndedBeforeFinalTimeout) {
                utils.logger.log("[Tracing] discarding Span since it finished after Transaction final timeout", stringifiedSpan);
              }
            }
            return spanStartedBeforeTransactionFinish && spanEndedBeforeFinalTimeout;
          });
          debugBuild.DEBUG_BUILD && utils.logger.log("[Tracing] flushing IdleTransaction");
        } else {
          debugBuild.DEBUG_BUILD && utils.logger.log("[Tracing] No active IdleTransaction");
        }
        if (this._onScope) {
          const scope = this._idleHub.getScope();
          if (scope.getTransaction() === this) {
            scope.setSpan(void 0);
          }
        }
        return super.end(endTimestamp);
      }
      /**
       * Register a callback function that gets executed before the transaction finishes.
       * Useful for cleanup or if you want to add any additional spans based on current context.
       *
       * This is exposed because users have no other way of running something before an idle transaction
       * finishes.
       */
      registerBeforeFinishCallback(callback) {
        this._beforeFinishCallbacks.push(callback);
      }
      /**
       * @inheritDoc
       */
      initSpanRecorder(maxlen) {
        if (!this.spanRecorder) {
          const pushActivity = (id) => {
            if (this._finished) {
              return;
            }
            this._pushActivity(id);
          };
          const popActivity = (id) => {
            if (this._finished) {
              return;
            }
            this._popActivity(id);
          };
          this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanContext().spanId, maxlen);
          debugBuild.DEBUG_BUILD && utils.logger.log("Starting heartbeat");
          this._pingHeartbeat();
        }
        this.spanRecorder.add(this);
      }
      /**
       * Cancels the existing idle timeout, if there is one.
       * @param restartOnChildSpanChange Default is `true`.
       *                                 If set to false the transaction will end
       *                                 with the last child span.
       */
      cancelIdleTimeout(endTimestamp, {
        restartOnChildSpanChange
      } = {
        restartOnChildSpanChange: true
      }) {
        this._idleTimeoutCanceledPermanently = restartOnChildSpanChange === false;
        if (this._idleTimeoutID) {
          clearTimeout(this._idleTimeoutID);
          this._idleTimeoutID = void 0;
          if (Object.keys(this.activities).length === 0 && this._idleTimeoutCanceledPermanently) {
            this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];
            this.end(endTimestamp);
          }
        }
      }
      /**
       * Temporary method used to externally set the transaction's `finishReason`
       *
       * ** WARNING**
       * This is for the purpose of experimentation only and will be removed in the near future, do not use!
       *
       * @internal
       *
       */
      setFinishReason(reason) {
        this._finishReason = reason;
      }
      /**
       * Permits the IdleTransaction to automatically end itself via the idle timeout and heartbeat mechanisms when the `delayAutoFinishUntilSignal` option was set to `true`.
       */
      sendAutoFinishSignal() {
        if (!this._autoFinishAllowed) {
          debugBuild.DEBUG_BUILD && utils.logger.log("[Tracing] Received finish signal for idle transaction.");
          this._restartIdleTimeout();
          this._autoFinishAllowed = true;
        }
      }
      /**
       * Restarts idle timeout, if there is no running idle timeout it will start one.
       */
      _restartIdleTimeout(endTimestamp) {
        this.cancelIdleTimeout();
        this._idleTimeoutID = setTimeout(() => {
          if (!this._finished && Object.keys(this.activities).length === 0) {
            this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[1];
            this.end(endTimestamp);
          }
        }, this._idleTimeout);
      }
      /**
       * Start tracking a specific activity.
       * @param spanId The span id that represents the activity
       */
      _pushActivity(spanId) {
        this.cancelIdleTimeout(void 0, { restartOnChildSpanChange: !this._idleTimeoutCanceledPermanently });
        debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] pushActivity: ${spanId}`);
        this.activities[spanId] = true;
        debugBuild.DEBUG_BUILD && utils.logger.log("[Tracing] new activities count", Object.keys(this.activities).length);
      }
      /**
       * Remove an activity from usage
       * @param spanId The span id that represents the activity
       */
      _popActivity(spanId) {
        if (this.activities[spanId]) {
          debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] popActivity ${spanId}`);
          delete this.activities[spanId];
          debugBuild.DEBUG_BUILD && utils.logger.log("[Tracing] new activities count", Object.keys(this.activities).length);
        }
        if (Object.keys(this.activities).length === 0) {
          const endTimestamp = utils.timestampInSeconds();
          if (this._idleTimeoutCanceledPermanently) {
            if (this._autoFinishAllowed) {
              this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];
              this.end(endTimestamp);
            }
          } else {
            this._restartIdleTimeout(endTimestamp + this._idleTimeout / 1e3);
          }
        }
      }
      /**
       * Checks when entries of this.activities are not changing for 3 beats.
       * If this occurs we finish the transaction.
       */
      _beat() {
        if (this._finished) {
          return;
        }
        const heartbeatString = Object.keys(this.activities).join("");
        if (heartbeatString === this._prevHeartbeatString) {
          this._heartbeatCounter++;
        } else {
          this._heartbeatCounter = 1;
        }
        this._prevHeartbeatString = heartbeatString;
        if (this._heartbeatCounter >= 3) {
          if (this._autoFinishAllowed) {
            debugBuild.DEBUG_BUILD && utils.logger.log("[Tracing] Transaction finished because of no change for 3 heart beats");
            this.setStatus("deadline_exceeded");
            this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[0];
            this.end();
          }
        } else {
          this._pingHeartbeat();
        }
      }
      /**
       * Pings the heartbeat
       */
      _pingHeartbeat() {
        debugBuild.DEBUG_BUILD && utils.logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`);
        setTimeout(() => {
          this._beat();
        }, this._heartbeatInterval);
      }
    };
    exports.IdleTransaction = IdleTransaction;
    exports.IdleTransactionSpanRecorder = IdleTransactionSpanRecorder;
    exports.TRACING_DEFAULTS = TRACING_DEFAULTS;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/sampling.js
var require_sampling = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/sampling.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build2();
    var semanticAttributes = require_semanticAttributes();
    var hasTracingEnabled = require_hasTracingEnabled();
    var spanUtils = require_spanUtils();
    function sampleTransaction(transaction, options, samplingContext) {
      if (!hasTracingEnabled.hasTracingEnabled(options)) {
        transaction.sampled = false;
        return transaction;
      }
      if (transaction.sampled !== void 0) {
        transaction.setAttribute(semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(transaction.sampled));
        return transaction;
      }
      let sampleRate;
      if (typeof options.tracesSampler === "function") {
        sampleRate = options.tracesSampler(samplingContext);
        transaction.setAttribute(semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(sampleRate));
      } else if (samplingContext.parentSampled !== void 0) {
        sampleRate = samplingContext.parentSampled;
      } else if (typeof options.tracesSampleRate !== "undefined") {
        sampleRate = options.tracesSampleRate;
        transaction.setAttribute(semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(sampleRate));
      } else {
        sampleRate = 1;
        transaction.setAttribute(semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, sampleRate);
      }
      if (!isValidSampleRate(sampleRate)) {
        debugBuild.DEBUG_BUILD && utils.logger.warn("[Tracing] Discarding transaction because of invalid sample rate.");
        transaction.sampled = false;
        return transaction;
      }
      if (!sampleRate) {
        debugBuild.DEBUG_BUILD && utils.logger.log(
          `[Tracing] Discarding transaction because ${typeof options.tracesSampler === "function" ? "tracesSampler returned 0 or false" : "a negative sampling decision was inherited or tracesSampleRate is set to 0"}`
        );
        transaction.sampled = false;
        return transaction;
      }
      transaction.sampled = Math.random() < sampleRate;
      if (!transaction.sampled) {
        debugBuild.DEBUG_BUILD && utils.logger.log(
          `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(
            sampleRate
          )})`
        );
        return transaction;
      }
      debugBuild.DEBUG_BUILD && // eslint-disable-next-line deprecation/deprecation
      utils.logger.log(`[Tracing] starting ${transaction.op} transaction - ${spanUtils.spanToJSON(transaction).description}`);
      return transaction;
    }
    function isValidSampleRate(rate) {
      if (utils.isNaN(rate) || !(typeof rate === "number" || typeof rate === "boolean")) {
        debugBuild.DEBUG_BUILD && utils.logger.warn(
          `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(
            rate
          )} of type ${JSON.stringify(typeof rate)}.`
        );
        return false;
      }
      if (rate < 0 || rate > 1) {
        debugBuild.DEBUG_BUILD && utils.logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);
        return false;
      }
      return true;
    }
    exports.isValidSampleRate = isValidSampleRate;
    exports.sampleTransaction = sampleTransaction;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/hubextensions.js
var require_hubextensions = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/hubextensions.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build2();
    var hub = require_hub();
    var spanUtils = require_spanUtils();
    var errors = require_errors();
    var idletransaction = require_idletransaction();
    var sampling = require_sampling();
    var transaction = require_transaction();
    function traceHeaders() {
      const scope = this.getScope();
      const span = scope.getSpan();
      return span ? {
        "sentry-trace": spanUtils.spanToTraceHeader(span)
      } : {};
    }
    function _startTransaction(transactionContext, customSamplingContext) {
      const client = this.getClient();
      const options = client && client.getOptions() || {};
      const configInstrumenter = options.instrumenter || "sentry";
      const transactionInstrumenter = transactionContext.instrumenter || "sentry";
      if (configInstrumenter !== transactionInstrumenter) {
        debugBuild.DEBUG_BUILD && utils.logger.error(
          `A transaction was started with instrumenter=\`${transactionInstrumenter}\`, but the SDK is configured with the \`${configInstrumenter}\` instrumenter.
The transaction will not be sampled. Please use the ${configInstrumenter} instrumentation to start transactions.`
        );
        transactionContext.sampled = false;
      }
      let transaction$1 = new transaction.Transaction(transactionContext, this);
      transaction$1 = sampling.sampleTransaction(transaction$1, options, {
        name: transactionContext.name,
        parentSampled: transactionContext.parentSampled,
        transactionContext,
        attributes: {
          // eslint-disable-next-line deprecation/deprecation
          ...transactionContext.data,
          ...transactionContext.attributes
        },
        ...customSamplingContext
      });
      if (transaction$1.isRecording()) {
        transaction$1.initSpanRecorder(options._experiments && options._experiments.maxSpans);
      }
      if (client && client.emit) {
        client.emit("startTransaction", transaction$1);
      }
      return transaction$1;
    }
    function startIdleTransaction(hub2, transactionContext, idleTimeout, finalTimeout, onScope, customSamplingContext, heartbeatInterval, delayAutoFinishUntilSignal = false) {
      const client = hub2.getClient();
      const options = client && client.getOptions() || {};
      let transaction2 = new idletransaction.IdleTransaction(
        transactionContext,
        hub2,
        idleTimeout,
        finalTimeout,
        heartbeatInterval,
        onScope,
        delayAutoFinishUntilSignal
      );
      transaction2 = sampling.sampleTransaction(transaction2, options, {
        name: transactionContext.name,
        parentSampled: transactionContext.parentSampled,
        transactionContext,
        attributes: {
          // eslint-disable-next-line deprecation/deprecation
          ...transactionContext.data,
          ...transactionContext.attributes
        },
        ...customSamplingContext
      });
      if (transaction2.isRecording()) {
        transaction2.initSpanRecorder(options._experiments && options._experiments.maxSpans);
      }
      if (client && client.emit) {
        client.emit("startTransaction", transaction2);
      }
      return transaction2;
    }
    function addTracingExtensions() {
      const carrier = hub.getMainCarrier();
      if (!carrier.__SENTRY__) {
        return;
      }
      carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};
      if (!carrier.__SENTRY__.extensions.startTransaction) {
        carrier.__SENTRY__.extensions.startTransaction = _startTransaction;
      }
      if (!carrier.__SENTRY__.extensions.traceHeaders) {
        carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;
      }
      errors.registerErrorInstrumentation();
    }
    exports.addTracingExtensions = addTracingExtensions;
    exports.startIdleTransaction = startIdleTransaction;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/measurement.js
var require_measurement = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/tracing/measurement.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_utils();
    function setMeasurement(name, value, unit) {
      const transaction = utils.getActiveTransaction();
      if (transaction) {
        transaction.setMeasurement(name, value, unit);
      }
    }
    exports.setMeasurement = setMeasurement;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/envelope.js
var require_envelope2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/envelope.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    function enhanceEventWithSdkInfo(event, sdkInfo) {
      if (!sdkInfo) {
        return event;
      }
      event.sdk = event.sdk || {};
      event.sdk.name = event.sdk.name || sdkInfo.name;
      event.sdk.version = event.sdk.version || sdkInfo.version;
      event.sdk.integrations = [...event.sdk.integrations || [], ...sdkInfo.integrations || []];
      event.sdk.packages = [...event.sdk.packages || [], ...sdkInfo.packages || []];
      return event;
    }
    function createSessionEnvelope(session, dsn, metadata, tunnel) {
      const sdkInfo = utils.getSdkMetadataForEnvelopeHeader(metadata);
      const envelopeHeaders = {
        sent_at: (/* @__PURE__ */ new Date()).toISOString(),
        ...sdkInfo && { sdk: sdkInfo },
        ...!!tunnel && dsn && { dsn: utils.dsnToString(dsn) }
      };
      const envelopeItem = "aggregates" in session ? [{ type: "sessions" }, session] : [{ type: "session" }, session.toJSON()];
      return utils.createEnvelope(envelopeHeaders, [envelopeItem]);
    }
    function createEventEnvelope(event, dsn, metadata, tunnel) {
      const sdkInfo = utils.getSdkMetadataForEnvelopeHeader(metadata);
      const eventType = event.type && event.type !== "replay_event" ? event.type : "event";
      enhanceEventWithSdkInfo(event, metadata && metadata.sdk);
      const envelopeHeaders = utils.createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn);
      delete event.sdkProcessingMetadata;
      const eventItem = [{ type: eventType }, event];
      return utils.createEnvelope(envelopeHeaders, [eventItem]);
    }
    exports.createEventEnvelope = createEventEnvelope;
    exports.createSessionEnvelope = createSessionEnvelope;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/sessionflusher.js
var require_sessionflusher = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/sessionflusher.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var exports$1 = require_exports();
    var SessionFlusher = class {
      // Cast to any so that it can use Node.js timeout
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      constructor(client, attrs) {
        this._client = client;
        this.flushTimeout = 60;
        this._pendingAggregates = {};
        this._isEnabled = true;
        this._intervalId = setInterval(() => this.flush(), this.flushTimeout * 1e3);
        if (this._intervalId.unref) {
          this._intervalId.unref();
        }
        this._sessionAttrs = attrs;
      }
      /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSession` */
      flush() {
        const sessionAggregates = this.getSessionAggregates();
        if (sessionAggregates.aggregates.length === 0) {
          return;
        }
        this._pendingAggregates = {};
        this._client.sendSession(sessionAggregates);
      }
      /** Massages the entries in `pendingAggregates` and returns aggregated sessions */
      getSessionAggregates() {
        const aggregates = Object.keys(this._pendingAggregates).map((key) => {
          return this._pendingAggregates[parseInt(key)];
        });
        const sessionAggregates = {
          attrs: this._sessionAttrs,
          aggregates
        };
        return utils.dropUndefinedKeys(sessionAggregates);
      }
      /** JSDoc */
      close() {
        clearInterval(this._intervalId);
        this._isEnabled = false;
        this.flush();
      }
      /**
       * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then
       * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to
       * `_incrementSessionStatusCount` along with the start date
       */
      incrementSessionStatusCount() {
        if (!this._isEnabled) {
          return;
        }
        const scope = exports$1.getCurrentScope();
        const requestSession = scope.getRequestSession();
        if (requestSession && requestSession.status) {
          this._incrementSessionStatusCount(requestSession.status, /* @__PURE__ */ new Date());
          scope.setRequestSession(void 0);
        }
      }
      /**
       * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of
       * the session received
       */
      _incrementSessionStatusCount(status, date) {
        const sessionStartedTrunc = new Date(date).setSeconds(0, 0);
        this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {};
        const aggregationCounts = this._pendingAggregates[sessionStartedTrunc];
        if (!aggregationCounts.started) {
          aggregationCounts.started = new Date(sessionStartedTrunc).toISOString();
        }
        switch (status) {
          case "errored":
            aggregationCounts.errored = (aggregationCounts.errored || 0) + 1;
            return aggregationCounts.errored;
          case "ok":
            aggregationCounts.exited = (aggregationCounts.exited || 0) + 1;
            return aggregationCounts.exited;
          default:
            aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1;
            return aggregationCounts.crashed;
        }
      }
    };
    exports.SessionFlusher = SessionFlusher;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/api.js
var require_api = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/api.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var SENTRY_API_VERSION = "7";
    function getBaseApiEndpoint(dsn) {
      const protocol = dsn.protocol ? `${dsn.protocol}:` : "";
      const port = dsn.port ? `:${dsn.port}` : "";
      return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ""}/api/`;
    }
    function _getIngestEndpoint(dsn) {
      return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;
    }
    function _encodedAuth(dsn, sdkInfo) {
      return utils.urlEncode({
        // We send only the minimum set of required information. See
        // https://github.com/getsentry/sentry-javascript/issues/2572.
        sentry_key: dsn.publicKey,
        sentry_version: SENTRY_API_VERSION,
        ...sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }
      });
    }
    function getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnelOrOptions = {}) {
      const tunnel = typeof tunnelOrOptions === "string" ? tunnelOrOptions : tunnelOrOptions.tunnel;
      const sdkInfo = typeof tunnelOrOptions === "string" || !tunnelOrOptions._metadata ? void 0 : tunnelOrOptions._metadata.sdk;
      return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;
    }
    function getReportDialogEndpoint(dsnLike, dialogOptions) {
      const dsn = utils.makeDsn(dsnLike);
      if (!dsn) {
        return "";
      }
      const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;
      let encodedOptions = `dsn=${utils.dsnToString(dsn)}`;
      for (const key in dialogOptions) {
        if (key === "dsn") {
          continue;
        }
        if (key === "onClose") {
          continue;
        }
        if (key === "user") {
          const user = dialogOptions.user;
          if (!user) {
            continue;
          }
          if (user.name) {
            encodedOptions += `&name=${encodeURIComponent(user.name)}`;
          }
          if (user.email) {
            encodedOptions += `&email=${encodeURIComponent(user.email)}`;
          }
        } else {
          encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key])}`;
        }
      }
      return `${endpoint}?${encodedOptions}`;
    }
    exports.getEnvelopeEndpointWithUrlEncodedAuth = getEnvelopeEndpointWithUrlEncodedAuth;
    exports.getReportDialogEndpoint = getReportDialogEndpoint;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/integration.js
var require_integration = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/integration.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build2();
    var eventProcessors = require_eventProcessors();
    var exports$1 = require_exports();
    var hub = require_hub();
    var installedIntegrations = [];
    function filterDuplicates(integrations) {
      const integrationsByName = {};
      integrations.forEach((currentInstance) => {
        const { name } = currentInstance;
        const existingInstance = integrationsByName[name];
        if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {
          return;
        }
        integrationsByName[name] = currentInstance;
      });
      return Object.keys(integrationsByName).map((k2) => integrationsByName[k2]);
    }
    function getIntegrationsToSetup(options) {
      const defaultIntegrations = options.defaultIntegrations || [];
      const userIntegrations = options.integrations;
      defaultIntegrations.forEach((integration) => {
        integration.isDefaultInstance = true;
      });
      let integrations;
      if (Array.isArray(userIntegrations)) {
        integrations = [...defaultIntegrations, ...userIntegrations];
      } else if (typeof userIntegrations === "function") {
        integrations = utils.arrayify(userIntegrations(defaultIntegrations));
      } else {
        integrations = defaultIntegrations;
      }
      const finalIntegrations = filterDuplicates(integrations);
      const debugIndex = findIndex(finalIntegrations, (integration) => integration.name === "Debug");
      if (debugIndex !== -1) {
        const [debugInstance] = finalIntegrations.splice(debugIndex, 1);
        finalIntegrations.push(debugInstance);
      }
      return finalIntegrations;
    }
    function setupIntegrations(client, integrations) {
      const integrationIndex = {};
      integrations.forEach((integration) => {
        if (integration) {
          setupIntegration(client, integration, integrationIndex);
        }
      });
      return integrationIndex;
    }
    function afterSetupIntegrations(client, integrations) {
      for (const integration of integrations) {
        if (integration && integration.afterAllSetup) {
          integration.afterAllSetup(client);
        }
      }
    }
    function setupIntegration(client, integration, integrationIndex) {
      if (integrationIndex[integration.name]) {
        debugBuild.DEBUG_BUILD && utils.logger.log(`Integration skipped because it was already installed: ${integration.name}`);
        return;
      }
      integrationIndex[integration.name] = integration;
      if (installedIntegrations.indexOf(integration.name) === -1) {
        integration.setupOnce(eventProcessors.addGlobalEventProcessor, hub.getCurrentHub);
        installedIntegrations.push(integration.name);
      }
      if (integration.setup && typeof integration.setup === "function") {
        integration.setup(client);
      }
      if (client.on && typeof integration.preprocessEvent === "function") {
        const callback = integration.preprocessEvent.bind(integration);
        client.on("preprocessEvent", (event, hint) => callback(event, hint, client));
      }
      if (client.addEventProcessor && typeof integration.processEvent === "function") {
        const callback = integration.processEvent.bind(integration);
        const processor = Object.assign((event, hint) => callback(event, hint, client), {
          id: integration.name
        });
        client.addEventProcessor(processor);
      }
      debugBuild.DEBUG_BUILD && utils.logger.log(`Integration installed: ${integration.name}`);
    }
    function addIntegration(integration) {
      const client = exports$1.getClient();
      if (!client || !client.addIntegration) {
        debugBuild.DEBUG_BUILD && utils.logger.warn(`Cannot add integration "${integration.name}" because no SDK Client is available.`);
        return;
      }
      client.addIntegration(integration);
    }
    function findIndex(arr, callback) {
      for (let i2 = 0; i2 < arr.length; i2++) {
        if (callback(arr[i2]) === true) {
          return i2;
        }
      }
      return -1;
    }
    function convertIntegrationFnToClass(name, fn) {
      return Object.assign(
        function ConvertedIntegration(...args) {
          return fn(...args);
        },
        { id: name }
      );
    }
    function defineIntegration(fn) {
      return fn;
    }
    exports.addIntegration = addIntegration;
    exports.afterSetupIntegrations = afterSetupIntegrations;
    exports.convertIntegrationFnToClass = convertIntegrationFnToClass;
    exports.defineIntegration = defineIntegration;
    exports.getIntegrationsToSetup = getIntegrationsToSetup;
    exports.installedIntegrations = installedIntegrations;
    exports.setupIntegration = setupIntegration;
    exports.setupIntegrations = setupIntegrations;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metrics/utils.js
var require_utils2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metrics/utils.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    function getBucketKey(metricType, name, unit, tags) {
      const stringifiedTags = Object.entries(utils.dropUndefinedKeys(tags)).sort((a3, b) => a3[0].localeCompare(b[0]));
      return `${metricType}${name}${unit}${stringifiedTags}`;
    }
    function simpleHash(s2) {
      let rv = 0;
      for (let i2 = 0; i2 < s2.length; i2++) {
        const c3 = s2.charCodeAt(i2);
        rv = (rv << 5) - rv + c3;
        rv &= rv;
      }
      return rv >>> 0;
    }
    function serializeMetricBuckets(metricBucketItems) {
      let out = "";
      for (const item of metricBucketItems) {
        const tagEntries = Object.entries(item.tags);
        const maybeTags = tagEntries.length > 0 ? `|#${tagEntries.map(([key, value]) => `${key}:${value}`).join(",")}` : "";
        out += `${item.name}@${item.unit}:${item.metric}|${item.metricType}${maybeTags}|T${item.timestamp}
`;
      }
      return out;
    }
    function sanitizeUnit(unit) {
      return unit.replace(/[^\w]+/gi, "_");
    }
    function sanitizeMetricKey(key) {
      return key.replace(/[^\w\-.]+/gi, "_");
    }
    function sanitizeTagKey(key) {
      return key.replace(/[^\w\-./]+/gi, "");
    }
    var tagValueReplacements = [
      ["\n", "\\n"],
      ["\r", "\\r"],
      ["	", "\\t"],
      ["\\", "\\\\"],
      ["|", "\\u{7c}"],
      [",", "\\u{2c}"]
    ];
    function getCharOrReplacement(input) {
      for (const [search, replacement] of tagValueReplacements) {
        if (input === search) {
          return replacement;
        }
      }
      return input;
    }
    function sanitizeTagValue(value) {
      return [...value].reduce((acc, char) => acc + getCharOrReplacement(char), "");
    }
    function sanitizeTags(unsanitizedTags) {
      const tags = {};
      for (const key in unsanitizedTags) {
        if (Object.prototype.hasOwnProperty.call(unsanitizedTags, key)) {
          const sanitizedKey = sanitizeTagKey(key);
          tags[sanitizedKey] = sanitizeTagValue(String(unsanitizedTags[key]));
        }
      }
      return tags;
    }
    exports.getBucketKey = getBucketKey;
    exports.sanitizeMetricKey = sanitizeMetricKey;
    exports.sanitizeTags = sanitizeTags;
    exports.sanitizeUnit = sanitizeUnit;
    exports.serializeMetricBuckets = serializeMetricBuckets;
    exports.simpleHash = simpleHash;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metrics/envelope.js
var require_envelope3 = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metrics/envelope.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var utils$1 = require_utils2();
    function createMetricEnvelope(metricBucketItems, dsn, metadata, tunnel) {
      const headers = {
        sent_at: (/* @__PURE__ */ new Date()).toISOString()
      };
      if (metadata && metadata.sdk) {
        headers.sdk = {
          name: metadata.sdk.name,
          version: metadata.sdk.version
        };
      }
      if (!!tunnel && dsn) {
        headers.dsn = utils.dsnToString(dsn);
      }
      const item = createMetricEnvelopeItem(metricBucketItems);
      return utils.createEnvelope(headers, [item]);
    }
    function createMetricEnvelopeItem(metricBucketItems) {
      const payload = utils$1.serializeMetricBuckets(metricBucketItems);
      const metricHeaders = {
        type: "statsd",
        length: payload.length
      };
      return [metricHeaders, payload];
    }
    exports.createMetricEnvelope = createMetricEnvelope;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/baseclient.js
var require_baseclient = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/baseclient.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var api = require_api();
    var debugBuild = require_debug_build2();
    var envelope = require_envelope2();
    var exports$1 = require_exports();
    var hub = require_hub();
    var integration = require_integration();
    var envelope$1 = require_envelope3();
    var session = require_session();
    var dynamicSamplingContext = require_dynamicSamplingContext();
    var prepareEvent = require_prepareEvent();
    var ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured.";
    var BaseClient = class {
      /**
       * A reference to a metrics aggregator
       *
       * @experimental Note this is alpha API. It may experience breaking changes in the future.
       */
      /** Options passed to the SDK. */
      /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */
      /** Array of set up integrations. */
      /** Indicates whether this client's integrations have been set up. */
      /** Number of calls being processed */
      /** Holds flushable  */
      // eslint-disable-next-line @typescript-eslint/ban-types
      /**
       * Initializes this client instance.
       *
       * @param options Options for the client.
       */
      constructor(options) {
        this._options = options;
        this._integrations = {};
        this._integrationsInitialized = false;
        this._numProcessing = 0;
        this._outcomes = {};
        this._hooks = {};
        this._eventProcessors = [];
        if (options.dsn) {
          this._dsn = utils.makeDsn(options.dsn);
        } else {
          debugBuild.DEBUG_BUILD && utils.logger.warn("No DSN provided, client will not send events.");
        }
        if (this._dsn) {
          const url = api.getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options);
          this._transport = options.transport({
            tunnel: this._options.tunnel,
            recordDroppedEvent: this.recordDroppedEvent.bind(this),
            ...options.transportOptions,
            url
          });
        }
      }
      /**
       * @inheritDoc
       */
      // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
      captureException(exception, hint, scope) {
        if (utils.checkOrSetAlreadyCaught(exception)) {
          debugBuild.DEBUG_BUILD && utils.logger.log(ALREADY_SEEN_ERROR);
          return;
        }
        let eventId = hint && hint.event_id;
        this._process(
          this.eventFromException(exception, hint).then((event) => this._captureEvent(event, hint, scope)).then((result) => {
            eventId = result;
          })
        );
        return eventId;
      }
      /**
       * @inheritDoc
       */
      captureMessage(message, level, hint, scope) {
        let eventId = hint && hint.event_id;
        const eventMessage = utils.isParameterizedString(message) ? message : String(message);
        const promisedEvent = utils.isPrimitive(message) ? this.eventFromMessage(eventMessage, level, hint) : this.eventFromException(message, hint);
        this._process(
          promisedEvent.then((event) => this._captureEvent(event, hint, scope)).then((result) => {
            eventId = result;
          })
        );
        return eventId;
      }
      /**
       * @inheritDoc
       */
      captureEvent(event, hint, scope) {
        if (hint && hint.originalException && utils.checkOrSetAlreadyCaught(hint.originalException)) {
          debugBuild.DEBUG_BUILD && utils.logger.log(ALREADY_SEEN_ERROR);
          return;
        }
        let eventId = hint && hint.event_id;
        const sdkProcessingMetadata = event.sdkProcessingMetadata || {};
        const capturedSpanScope = sdkProcessingMetadata.capturedSpanScope;
        this._process(
          this._captureEvent(event, hint, capturedSpanScope || scope).then((result) => {
            eventId = result;
          })
        );
        return eventId;
      }
      /**
       * @inheritDoc
       */
      captureSession(session$1) {
        if (!(typeof session$1.release === "string")) {
          debugBuild.DEBUG_BUILD && utils.logger.warn("Discarded session because of missing or non-string release");
        } else {
          this.sendSession(session$1);
          session.updateSession(session$1, { init: false });
        }
      }
      /**
       * @inheritDoc
       */
      getDsn() {
        return this._dsn;
      }
      /**
       * @inheritDoc
       */
      getOptions() {
        return this._options;
      }
      /**
       * @see SdkMetadata in @sentry/types
       *
       * @return The metadata of the SDK
       */
      getSdkMetadata() {
        return this._options._metadata;
      }
      /**
       * @inheritDoc
       */
      getTransport() {
        return this._transport;
      }
      /**
       * @inheritDoc
       */
      flush(timeout) {
        const transport = this._transport;
        if (transport) {
          if (this.metricsAggregator) {
            this.metricsAggregator.flush();
          }
          return this._isClientDoneProcessing(timeout).then((clientFinished) => {
            return transport.flush(timeout).then((transportFlushed) => clientFinished && transportFlushed);
          });
        } else {
          return utils.resolvedSyncPromise(true);
        }
      }
      /**
       * @inheritDoc
       */
      close(timeout) {
        return this.flush(timeout).then((result) => {
          this.getOptions().enabled = false;
          if (this.metricsAggregator) {
            this.metricsAggregator.close();
          }
          return result;
        });
      }
      /** Get all installed event processors. */
      getEventProcessors() {
        return this._eventProcessors;
      }
      /** @inheritDoc */
      addEventProcessor(eventProcessor) {
        this._eventProcessors.push(eventProcessor);
      }
      /**
       * This is an internal function to setup all integrations that should run on the client.
       * @deprecated Use `client.init()` instead.
       */
      setupIntegrations(forceInitialize) {
        if (forceInitialize && !this._integrationsInitialized || this._isEnabled() && !this._integrationsInitialized) {
          this._setupIntegrations();
        }
      }
      /** @inheritdoc */
      init() {
        if (this._isEnabled()) {
          this._setupIntegrations();
        }
      }
      /**
       * Gets an installed integration by its `id`.
       *
       * @returns The installed integration or `undefined` if no integration with that `id` was installed.
       * @deprecated Use `getIntegrationByName()` instead.
       */
      getIntegrationById(integrationId) {
        return this.getIntegrationByName(integrationId);
      }
      /**
       * Gets an installed integration by its name.
       *
       * @returns The installed integration or `undefined` if no integration with that `name` was installed.
       */
      getIntegrationByName(integrationName) {
        return this._integrations[integrationName];
      }
      /**
       * Returns the client's instance of the given integration class, it any.
       * @deprecated Use `getIntegrationByName()` instead.
       */
      getIntegration(integration2) {
        try {
          return this._integrations[integration2.id] || null;
        } catch (_oO) {
          debugBuild.DEBUG_BUILD && utils.logger.warn(`Cannot retrieve integration ${integration2.id} from the current Client`);
          return null;
        }
      }
      /**
       * @inheritDoc
       */
      addIntegration(integration$1) {
        const isAlreadyInstalled = this._integrations[integration$1.name];
        integration.setupIntegration(this, integration$1, this._integrations);
        if (!isAlreadyInstalled) {
          integration.afterSetupIntegrations(this, [integration$1]);
        }
      }
      /**
       * @inheritDoc
       */
      sendEvent(event, hint = {}) {
        this.emit("beforeSendEvent", event, hint);
        let env2 = envelope.createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);
        for (const attachment of hint.attachments || []) {
          env2 = utils.addItemToEnvelope(
            env2,
            utils.createAttachmentEnvelopeItem(
              attachment,
              this._options.transportOptions && this._options.transportOptions.textEncoder
            )
          );
        }
        const promise = this._sendEnvelope(env2);
        if (promise) {
          promise.then((sendResponse) => this.emit("afterSendEvent", event, sendResponse), null);
        }
      }
      /**
       * @inheritDoc
       */
      sendSession(session2) {
        const env2 = envelope.createSessionEnvelope(session2, this._dsn, this._options._metadata, this._options.tunnel);
        this._sendEnvelope(env2);
      }
      /**
       * @inheritDoc
       */
      recordDroppedEvent(reason, category, eventOrCount) {
        if (this._options.sendClientReports) {
          const count = typeof eventOrCount === "number" ? eventOrCount : 1;
          const key = `${reason}:${category}`;
          debugBuild.DEBUG_BUILD && utils.logger.log(`Recording outcome: "${key}"${count > 1 ? ` (${count} times)` : ""}`);
          this._outcomes[key] = (this._outcomes[key] || 0) + count;
        }
      }
      /**
       * @inheritDoc
       */
      captureAggregateMetrics(metricBucketItems) {
        debugBuild.DEBUG_BUILD && utils.logger.log(`Flushing aggregated metrics, number of metrics: ${metricBucketItems.length}`);
        const metricsEnvelope = envelope$1.createMetricEnvelope(
          metricBucketItems,
          this._dsn,
          this._options._metadata,
          this._options.tunnel
        );
        this._sendEnvelope(metricsEnvelope);
      }
      // Keep on() & emit() signatures in sync with types' client.ts interface
      /* eslint-disable @typescript-eslint/unified-signatures */
      /** @inheritdoc */
      /** @inheritdoc */
      on(hook, callback) {
        if (!this._hooks[hook]) {
          this._hooks[hook] = [];
        }
        this._hooks[hook].push(callback);
      }
      /** @inheritdoc */
      /** @inheritdoc */
      emit(hook, ...rest) {
        if (this._hooks[hook]) {
          this._hooks[hook].forEach((callback) => callback(...rest));
        }
      }
      /* eslint-enable @typescript-eslint/unified-signatures */
      /** Setup integrations for this client. */
      _setupIntegrations() {
        const { integrations } = this._options;
        this._integrations = integration.setupIntegrations(this, integrations);
        integration.afterSetupIntegrations(this, integrations);
        this._integrationsInitialized = true;
      }
      /** Updates existing session based on the provided event */
      _updateSessionFromEvent(session$1, event) {
        let crashed = false;
        let errored = false;
        const exceptions = event.exception && event.exception.values;
        if (exceptions) {
          errored = true;
          for (const ex of exceptions) {
            const mechanism = ex.mechanism;
            if (mechanism && mechanism.handled === false) {
              crashed = true;
              break;
            }
          }
        }
        const sessionNonTerminal = session$1.status === "ok";
        const shouldUpdateAndSend = sessionNonTerminal && session$1.errors === 0 || sessionNonTerminal && crashed;
        if (shouldUpdateAndSend) {
          session.updateSession(session$1, {
            ...crashed && { status: "crashed" },
            errors: session$1.errors || Number(errored || crashed)
          });
          this.captureSession(session$1);
        }
      }
      /**
       * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying
       * "no" (resolving to `false`) in order to give the client a chance to potentially finish first.
       *
       * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not
       * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to
       * `true`.
       * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and
       * `false` otherwise
       */
      _isClientDoneProcessing(timeout) {
        return new utils.SyncPromise((resolve2) => {
          let ticked = 0;
          const tick = 1;
          const interval = setInterval(() => {
            if (this._numProcessing == 0) {
              clearInterval(interval);
              resolve2(true);
            } else {
              ticked += tick;
              if (timeout && ticked >= timeout) {
                clearInterval(interval);
                resolve2(false);
              }
            }
          }, tick);
        });
      }
      /** Determines whether this SDK is enabled and a transport is present. */
      _isEnabled() {
        return this.getOptions().enabled !== false && this._transport !== void 0;
      }
      /**
       * Adds common information to events.
       *
       * The information includes release and environment from `options`,
       * breadcrumbs and context (extra, tags and user) from the scope.
       *
       * Information that is already present in the event is never overwritten. For
       * nested objects, such as the context, keys are merged.
       *
       * @param event The original event.
       * @param hint May contain additional information about the original exception.
       * @param scope A scope containing event metadata.
       * @returns A new event with more information.
       */
      _prepareEvent(event, hint, scope, isolationScope = hub.getIsolationScope()) {
        const options = this.getOptions();
        const integrations = Object.keys(this._integrations);
        if (!hint.integrations && integrations.length > 0) {
          hint.integrations = integrations;
        }
        this.emit("preprocessEvent", event, hint);
        return prepareEvent.prepareEvent(options, event, hint, scope, this, isolationScope).then((evt) => {
          if (evt === null) {
            return evt;
          }
          const propagationContext = {
            ...isolationScope.getPropagationContext(),
            ...scope ? scope.getPropagationContext() : void 0
          };
          const trace = evt.contexts && evt.contexts.trace;
          if (!trace && propagationContext) {
            const { traceId: trace_id, spanId, parentSpanId, dsc } = propagationContext;
            evt.contexts = {
              trace: {
                trace_id,
                span_id: spanId,
                parent_span_id: parentSpanId
              },
              ...evt.contexts
            };
            const dynamicSamplingContext$1 = dsc ? dsc : dynamicSamplingContext.getDynamicSamplingContextFromClient(trace_id, this, scope);
            evt.sdkProcessingMetadata = {
              dynamicSamplingContext: dynamicSamplingContext$1,
              ...evt.sdkProcessingMetadata
            };
          }
          return evt;
        });
      }
      /**
       * Processes the event and logs an error in case of rejection
       * @param event
       * @param hint
       * @param scope
       */
      _captureEvent(event, hint = {}, scope) {
        return this._processEvent(event, hint, scope).then(
          (finalEvent) => {
            return finalEvent.event_id;
          },
          (reason) => {
            if (debugBuild.DEBUG_BUILD) {
              const sentryError = reason;
              if (sentryError.logLevel === "log") {
                utils.logger.log(sentryError.message);
              } else {
                utils.logger.warn(sentryError);
              }
            }
            return void 0;
          }
        );
      }
      /**
       * Processes an event (either error or message) and sends it to Sentry.
       *
       * This also adds breadcrumbs and context information to the event. However,
       * platform specific meta data (such as the User's IP address) must be added
       * by the SDK implementor.
       *
       *
       * @param event The event to send to Sentry.
       * @param hint May contain additional information about the original exception.
       * @param scope A scope containing event metadata.
       * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.
       */
      _processEvent(event, hint, scope) {
        const options = this.getOptions();
        const { sampleRate } = options;
        const isTransaction = isTransactionEvent(event);
        const isError = isErrorEvent(event);
        const eventType = event.type || "error";
        const beforeSendLabel = `before send for type \`${eventType}\``;
        if (isError && typeof sampleRate === "number" && Math.random() > sampleRate) {
          this.recordDroppedEvent("sample_rate", "error", event);
          return utils.rejectedSyncPromise(
            new utils.SentryError(
              `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,
              "log"
            )
          );
        }
        const dataCategory = eventType === "replay_event" ? "replay" : eventType;
        const sdkProcessingMetadata = event.sdkProcessingMetadata || {};
        const capturedSpanIsolationScope = sdkProcessingMetadata.capturedSpanIsolationScope;
        return this._prepareEvent(event, hint, scope, capturedSpanIsolationScope).then((prepared) => {
          if (prepared === null) {
            this.recordDroppedEvent("event_processor", dataCategory, event);
            throw new utils.SentryError("An event processor returned `null`, will not send event.", "log");
          }
          const isInternalException = hint.data && hint.data.__sentry__ === true;
          if (isInternalException) {
            return prepared;
          }
          const result = processBeforeSend(options, prepared, hint);
          return _validateBeforeSendResult(result, beforeSendLabel);
        }).then((processedEvent) => {
          if (processedEvent === null) {
            this.recordDroppedEvent("before_send", dataCategory, event);
            if (isTransaction) {
              const spans = event.spans || [];
              const spanCount = 1 + spans.length;
              this.recordDroppedEvent("before_send", "span", spanCount);
            }
            throw new utils.SentryError(`${beforeSendLabel} returned \`null\`, will not send event.`, "log");
          }
          const session2 = scope && scope.getSession();
          if (!isTransaction && session2) {
            this._updateSessionFromEvent(session2, processedEvent);
          }
          if (isTransaction) {
            const spanCountBefore = processedEvent.sdkProcessingMetadata && processedEvent.sdkProcessingMetadata.spanCountBeforeProcessing || 0;
            const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0;
            const droppedSpanCount = spanCountBefore - spanCountAfter;
            if (droppedSpanCount > 0) {
              this.recordDroppedEvent("before_send", "span", droppedSpanCount);
            }
          }
          const transactionInfo = processedEvent.transaction_info;
          if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {
            const source = "custom";
            processedEvent.transaction_info = {
              ...transactionInfo,
              source
            };
          }
          this.sendEvent(processedEvent, hint);
          return processedEvent;
        }).then(null, (reason) => {
          if (reason instanceof utils.SentryError) {
            throw reason;
          }
          this.captureException(reason, {
            data: {
              __sentry__: true
            },
            originalException: reason
          });
          throw new utils.SentryError(
            `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
Reason: ${reason}`
          );
        });
      }
      /**
       * Occupies the client with processing and event
       */
      _process(promise) {
        this._numProcessing++;
        void promise.then(
          (value) => {
            this._numProcessing--;
            return value;
          },
          (reason) => {
            this._numProcessing--;
            return reason;
          }
        );
      }
      /**
       * @inheritdoc
       */
      _sendEnvelope(envelope2) {
        this.emit("beforeEnvelope", envelope2);
        if (this._isEnabled() && this._transport) {
          return this._transport.send(envelope2).then(null, (reason) => {
            debugBuild.DEBUG_BUILD && utils.logger.error("Error while sending event:", reason);
          });
        } else {
          debugBuild.DEBUG_BUILD && utils.logger.error("Transport disabled");
        }
      }
      /**
       * Clears outcomes on this client and returns them.
       */
      _clearOutcomes() {
        const outcomes = this._outcomes;
        this._outcomes = {};
        return Object.keys(outcomes).map((key) => {
          const [reason, category] = key.split(":");
          return {
            reason,
            category,
            quantity: outcomes[key]
          };
        });
      }
      /**
       * @inheritDoc
       */
      // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
    };
    function _validateBeforeSendResult(beforeSendResult, beforeSendLabel) {
      const invalidValueError = `${beforeSendLabel} must return \`null\` or a valid event.`;
      if (utils.isThenable(beforeSendResult)) {
        return beforeSendResult.then(
          (event) => {
            if (!utils.isPlainObject(event) && event !== null) {
              throw new utils.SentryError(invalidValueError);
            }
            return event;
          },
          (e2) => {
            throw new utils.SentryError(`${beforeSendLabel} rejected with ${e2}`);
          }
        );
      } else if (!utils.isPlainObject(beforeSendResult) && beforeSendResult !== null) {
        throw new utils.SentryError(invalidValueError);
      }
      return beforeSendResult;
    }
    function processBeforeSend(options, event, hint) {
      const { beforeSend, beforeSendTransaction } = options;
      if (isErrorEvent(event) && beforeSend) {
        return beforeSend(event, hint);
      }
      if (isTransactionEvent(event) && beforeSendTransaction) {
        if (event.spans) {
          const spanCountBefore = event.spans.length;
          event.sdkProcessingMetadata = {
            ...event.sdkProcessingMetadata,
            spanCountBeforeProcessing: spanCountBefore
          };
        }
        return beforeSendTransaction(event, hint);
      }
      return event;
    }
    function isErrorEvent(event) {
      return event.type === void 0;
    }
    function isTransactionEvent(event) {
      return event.type === "transaction";
    }
    function addEventProcessor(callback) {
      const client = exports$1.getClient();
      if (!client || !client.addEventProcessor) {
        return;
      }
      client.addEventProcessor(callback);
    }
    exports.BaseClient = BaseClient;
    exports.addEventProcessor = addEventProcessor;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/checkin.js
var require_checkin = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/checkin.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    function createCheckInEnvelope(checkIn, dynamicSamplingContext, metadata, tunnel, dsn) {
      const headers = {
        sent_at: (/* @__PURE__ */ new Date()).toISOString()
      };
      if (metadata && metadata.sdk) {
        headers.sdk = {
          name: metadata.sdk.name,
          version: metadata.sdk.version
        };
      }
      if (!!tunnel && !!dsn) {
        headers.dsn = utils.dsnToString(dsn);
      }
      if (dynamicSamplingContext) {
        headers.trace = utils.dropUndefinedKeys(dynamicSamplingContext);
      }
      const item = createCheckInEnvelopeItem(checkIn);
      return utils.createEnvelope(headers, [item]);
    }
    function createCheckInEnvelopeItem(checkIn) {
      const checkInHeaders = {
        type: "check_in"
      };
      return [checkInHeaders, checkIn];
    }
    exports.createCheckInEnvelope = createCheckInEnvelope;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metrics/constants.js
var require_constants2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metrics/constants.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var COUNTER_METRIC_TYPE = "c";
    var GAUGE_METRIC_TYPE = "g";
    var SET_METRIC_TYPE = "s";
    var DISTRIBUTION_METRIC_TYPE = "d";
    var DEFAULT_BROWSER_FLUSH_INTERVAL = 5e3;
    var DEFAULT_FLUSH_INTERVAL = 1e4;
    var MAX_WEIGHT = 1e4;
    exports.COUNTER_METRIC_TYPE = COUNTER_METRIC_TYPE;
    exports.DEFAULT_BROWSER_FLUSH_INTERVAL = DEFAULT_BROWSER_FLUSH_INTERVAL;
    exports.DEFAULT_FLUSH_INTERVAL = DEFAULT_FLUSH_INTERVAL;
    exports.DISTRIBUTION_METRIC_TYPE = DISTRIBUTION_METRIC_TYPE;
    exports.GAUGE_METRIC_TYPE = GAUGE_METRIC_TYPE;
    exports.MAX_WEIGHT = MAX_WEIGHT;
    exports.SET_METRIC_TYPE = SET_METRIC_TYPE;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metrics/instance.js
var require_instance = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metrics/instance.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var constants = require_constants2();
    var utils = require_utils2();
    var CounterMetric = class {
      constructor(_value) {
        this._value = _value;
      }
      /** @inheritDoc */
      get weight() {
        return 1;
      }
      /** @inheritdoc */
      add(value) {
        this._value += value;
      }
      /** @inheritdoc */
      toString() {
        return `${this._value}`;
      }
    };
    var GaugeMetric = class {
      constructor(value) {
        this._last = value;
        this._min = value;
        this._max = value;
        this._sum = value;
        this._count = 1;
      }
      /** @inheritDoc */
      get weight() {
        return 5;
      }
      /** @inheritdoc */
      add(value) {
        this._last = value;
        if (value < this._min) {
          this._min = value;
        }
        if (value > this._max) {
          this._max = value;
        }
        this._sum += value;
        this._count++;
      }
      /** @inheritdoc */
      toString() {
        return `${this._last}:${this._min}:${this._max}:${this._sum}:${this._count}`;
      }
    };
    var DistributionMetric = class {
      constructor(first) {
        this._value = [first];
      }
      /** @inheritDoc */
      get weight() {
        return this._value.length;
      }
      /** @inheritdoc */
      add(value) {
        this._value.push(value);
      }
      /** @inheritdoc */
      toString() {
        return this._value.join(":");
      }
    };
    var SetMetric = class {
      constructor(first) {
        this.first = first;
        this._value = /* @__PURE__ */ new Set([first]);
      }
      /** @inheritDoc */
      get weight() {
        return this._value.size;
      }
      /** @inheritdoc */
      add(value) {
        this._value.add(value);
      }
      /** @inheritdoc */
      toString() {
        return Array.from(this._value).map((val) => typeof val === "string" ? utils.simpleHash(val) : val).join(":");
      }
    };
    var METRIC_MAP = {
      [constants.COUNTER_METRIC_TYPE]: CounterMetric,
      [constants.GAUGE_METRIC_TYPE]: GaugeMetric,
      [constants.DISTRIBUTION_METRIC_TYPE]: DistributionMetric,
      [constants.SET_METRIC_TYPE]: SetMetric
    };
    exports.CounterMetric = CounterMetric;
    exports.DistributionMetric = DistributionMetric;
    exports.GaugeMetric = GaugeMetric;
    exports.METRIC_MAP = METRIC_MAP;
    exports.SetMetric = SetMetric;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metrics/aggregator.js
var require_aggregator = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metrics/aggregator.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils$1 = require_cjs();
    var constants = require_constants2();
    var instance = require_instance();
    var metricSummary = require_metric_summary();
    var utils = require_utils2();
    var MetricsAggregator = class {
      // TODO(@anonrig): Use FinalizationRegistry to have a proper way of flushing the buckets
      // when the aggregator is garbage collected.
      // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
      // Different metrics have different weights. We use this to limit the number of metrics
      // that we store in memory.
      // Cast to any so that it can use Node.js timeout
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      // SDKs are required to shift the flush interval by random() * rollup_in_seconds.
      // That shift is determined once per startup to create jittering.
      // An SDK is required to perform force flushing ahead of scheduled time if the memory
      // pressure is too high. There is no rule for this other than that SDKs should be tracking
      // abstract aggregation complexity (eg: a counter only carries a single float, whereas a
      // distribution is a float per emission).
      //
      // Force flush is used on either shutdown, flush() or when we exceed the max weight.
      constructor(_client) {
        this._client = _client;
        this._buckets = /* @__PURE__ */ new Map();
        this._bucketsTotalWeight = 0;
        this._interval = setInterval(() => this._flush(), constants.DEFAULT_FLUSH_INTERVAL);
        if (this._interval.unref) {
          this._interval.unref();
        }
        this._flushShift = Math.floor(Math.random() * constants.DEFAULT_FLUSH_INTERVAL / 1e3);
        this._forceFlush = false;
      }
      /**
       * @inheritDoc
       */
      add(metricType, unsanitizedName, value, unsanitizedUnit = "none", unsanitizedTags = {}, maybeFloatTimestamp = utils$1.timestampInSeconds()) {
        const timestamp = Math.floor(maybeFloatTimestamp);
        const name = utils.sanitizeMetricKey(unsanitizedName);
        const tags = utils.sanitizeTags(unsanitizedTags);
        const unit = utils.sanitizeUnit(unsanitizedUnit);
        const bucketKey = utils.getBucketKey(metricType, name, unit, tags);
        let bucketItem = this._buckets.get(bucketKey);
        const previousWeight = bucketItem && metricType === constants.SET_METRIC_TYPE ? bucketItem.metric.weight : 0;
        if (bucketItem) {
          bucketItem.metric.add(value);
          if (bucketItem.timestamp < timestamp) {
            bucketItem.timestamp = timestamp;
          }
        } else {
          bucketItem = {
            // @ts-expect-error we don't need to narrow down the type of value here, saves bundle size.
            metric: new instance.METRIC_MAP[metricType](value),
            timestamp,
            metricType,
            name,
            unit,
            tags
          };
          this._buckets.set(bucketKey, bucketItem);
        }
        const val = typeof value === "string" ? bucketItem.metric.weight - previousWeight : value;
        metricSummary.updateMetricSummaryOnActiveSpan(metricType, name, val, unit, unsanitizedTags, bucketKey);
        this._bucketsTotalWeight += bucketItem.metric.weight;
        if (this._bucketsTotalWeight >= constants.MAX_WEIGHT) {
          this.flush();
        }
      }
      /**
       * Flushes the current metrics to the transport via the transport.
       */
      flush() {
        this._forceFlush = true;
        this._flush();
      }
      /**
       * Shuts down metrics aggregator and clears all metrics.
       */
      close() {
        this._forceFlush = true;
        clearInterval(this._interval);
        this._flush();
      }
      /**
       * Flushes the buckets according to the internal state of the aggregator.
       * If it is a force flush, which happens on shutdown, it will flush all buckets.
       * Otherwise, it will only flush buckets that are older than the flush interval,
       * and according to the flush shift.
       *
       * This function mutates `_forceFlush` and `_bucketsTotalWeight` properties.
       */
      _flush() {
        if (this._forceFlush) {
          this._forceFlush = false;
          this._bucketsTotalWeight = 0;
          this._captureMetrics(this._buckets);
          this._buckets.clear();
          return;
        }
        const cutoffSeconds = Math.floor(utils$1.timestampInSeconds()) - constants.DEFAULT_FLUSH_INTERVAL / 1e3 - this._flushShift;
        const flushedBuckets = /* @__PURE__ */ new Map();
        for (const [key, bucket] of this._buckets) {
          if (bucket.timestamp <= cutoffSeconds) {
            flushedBuckets.set(key, bucket);
            this._bucketsTotalWeight -= bucket.metric.weight;
          }
        }
        for (const [key] of flushedBuckets) {
          this._buckets.delete(key);
        }
        this._captureMetrics(flushedBuckets);
      }
      /**
       * Only captures a subset of the buckets passed to this function.
       * @param flushedBuckets
       */
      _captureMetrics(flushedBuckets) {
        if (flushedBuckets.size > 0 && this._client.captureAggregateMetrics) {
          const buckets = Array.from(flushedBuckets).map(([, bucketItem]) => bucketItem);
          this._client.captureAggregateMetrics(buckets);
        }
      }
    };
    exports.MetricsAggregator = MetricsAggregator;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/server-runtime-client.js
var require_server_runtime_client = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/server-runtime-client.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var baseclient = require_baseclient();
    var checkin = require_checkin();
    var debugBuild = require_debug_build2();
    var exports$1 = require_exports();
    var aggregator = require_aggregator();
    var sessionflusher = require_sessionflusher();
    var hubextensions = require_hubextensions();
    var spanUtils = require_spanUtils();
    var getRootSpan = require_getRootSpan();
    require_spanstatus();
    var dynamicSamplingContext = require_dynamicSamplingContext();
    var ServerRuntimeClient = class extends baseclient.BaseClient {
      /**
       * Creates a new Edge SDK instance.
       * @param options Configuration options for this SDK.
       */
      constructor(options) {
        hubextensions.addTracingExtensions();
        super(options);
        if (options._experiments && options._experiments["metricsAggregator"]) {
          this.metricsAggregator = new aggregator.MetricsAggregator(this);
        }
      }
      /**
       * @inheritDoc
       */
      eventFromException(exception, hint) {
        return utils.resolvedSyncPromise(utils.eventFromUnknownInput(exports$1.getClient(), this._options.stackParser, exception, hint));
      }
      /**
       * @inheritDoc
       */
      eventFromMessage(message, level = "info", hint) {
        return utils.resolvedSyncPromise(
          utils.eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace)
        );
      }
      /**
       * @inheritDoc
       */
      // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
      captureException(exception, hint, scope) {
        if (this._options.autoSessionTracking && this._sessionFlusher && scope) {
          const requestSession = scope.getRequestSession();
          if (requestSession && requestSession.status === "ok") {
            requestSession.status = "errored";
          }
        }
        return super.captureException(exception, hint, scope);
      }
      /**
       * @inheritDoc
       */
      captureEvent(event, hint, scope) {
        if (this._options.autoSessionTracking && this._sessionFlusher && scope) {
          const eventType = event.type || "exception";
          const isException = eventType === "exception" && event.exception && event.exception.values && event.exception.values.length > 0;
          if (isException) {
            const requestSession = scope.getRequestSession();
            if (requestSession && requestSession.status === "ok") {
              requestSession.status = "errored";
            }
          }
        }
        return super.captureEvent(event, hint, scope);
      }
      /**
       *
       * @inheritdoc
       */
      close(timeout) {
        if (this._sessionFlusher) {
          this._sessionFlusher.close();
        }
        return super.close(timeout);
      }
      /** Method that initialises an instance of SessionFlusher on Client */
      initSessionFlusher() {
        const { release, environment } = this._options;
        if (!release) {
          debugBuild.DEBUG_BUILD && utils.logger.warn("Cannot initialise an instance of SessionFlusher if no release is provided!");
        } else {
          this._sessionFlusher = new sessionflusher.SessionFlusher(this, {
            release,
            environment
          });
        }
      }
      /**
       * Create a cron monitor check in and send it to Sentry.
       *
       * @param checkIn An object that describes a check in.
       * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want
       * to create a monitor automatically when sending a check in.
       */
      captureCheckIn(checkIn, monitorConfig, scope) {
        const id = "checkInId" in checkIn && checkIn.checkInId ? checkIn.checkInId : utils.uuid4();
        if (!this._isEnabled()) {
          debugBuild.DEBUG_BUILD && utils.logger.warn("SDK not enabled, will not capture checkin.");
          return id;
        }
        const options = this.getOptions();
        const { release, environment, tunnel } = options;
        const serializedCheckIn = {
          check_in_id: id,
          monitor_slug: checkIn.monitorSlug,
          status: checkIn.status,
          release,
          environment
        };
        if ("duration" in checkIn) {
          serializedCheckIn.duration = checkIn.duration;
        }
        if (monitorConfig) {
          serializedCheckIn.monitor_config = {
            schedule: monitorConfig.schedule,
            checkin_margin: monitorConfig.checkinMargin,
            max_runtime: monitorConfig.maxRuntime,
            timezone: monitorConfig.timezone
          };
        }
        const [dynamicSamplingContext2, traceContext] = this._getTraceInfoFromScope(scope);
        if (traceContext) {
          serializedCheckIn.contexts = {
            trace: traceContext
          };
        }
        const envelope = checkin.createCheckInEnvelope(
          serializedCheckIn,
          dynamicSamplingContext2,
          this.getSdkMetadata(),
          tunnel,
          this.getDsn()
        );
        debugBuild.DEBUG_BUILD && utils.logger.info("Sending checkin:", checkIn.monitorSlug, checkIn.status);
        this._sendEnvelope(envelope);
        return id;
      }
      /**
       * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment
       * appropriate session aggregates bucket
       */
      _captureRequestSession() {
        if (!this._sessionFlusher) {
          debugBuild.DEBUG_BUILD && utils.logger.warn("Discarded request mode session because autoSessionTracking option was disabled");
        } else {
          this._sessionFlusher.incrementSessionStatusCount();
        }
      }
      /**
       * @inheritDoc
       */
      _prepareEvent(event, hint, scope, isolationScope) {
        if (this._options.platform) {
          event.platform = event.platform || this._options.platform;
        }
        if (this._options.runtime) {
          event.contexts = {
            ...event.contexts,
            runtime: (event.contexts || {}).runtime || this._options.runtime
          };
        }
        if (this._options.serverName) {
          event.server_name = event.server_name || this._options.serverName;
        }
        return super._prepareEvent(event, hint, scope, isolationScope);
      }
      /** Extract trace information from scope */
      _getTraceInfoFromScope(scope) {
        if (!scope) {
          return [void 0, void 0];
        }
        const span = scope.getSpan();
        if (span) {
          const samplingContext = getRootSpan.getRootSpan(span) ? dynamicSamplingContext.getDynamicSamplingContextFromSpan(span) : void 0;
          return [samplingContext, spanUtils.spanToTraceContext(span)];
        }
        const { traceId, spanId, parentSpanId, dsc } = scope.getPropagationContext();
        const traceContext = {
          trace_id: traceId,
          span_id: spanId,
          parent_span_id: parentSpanId
        };
        if (dsc) {
          return [dsc, traceContext];
        }
        return [dynamicSamplingContext.getDynamicSamplingContextFromClient(traceId, this, scope), traceContext];
      }
    };
    exports.ServerRuntimeClient = ServerRuntimeClient;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/sdk.js
var require_sdk = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/sdk.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build2();
    var exports$1 = require_exports();
    var hub = require_hub();
    function initAndBind(clientClass, options) {
      if (options.debug === true) {
        if (debugBuild.DEBUG_BUILD) {
          utils.logger.enable();
        } else {
          utils.consoleSandbox(() => {
            console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.");
          });
        }
      }
      const scope = exports$1.getCurrentScope();
      scope.update(options.initialScope);
      const client = new clientClass(options);
      setCurrentClient(client);
      initializeClient(client);
    }
    function setCurrentClient(client) {
      const hub$1 = hub.getCurrentHub();
      const top = hub$1.getStackTop();
      top.client = client;
      top.scope.setClient(client);
    }
    function initializeClient(client) {
      if (client.init) {
        client.init();
      } else if (client.setupIntegrations) {
        client.setupIntegrations();
      }
    }
    exports.initAndBind = initAndBind;
    exports.setCurrentClient = setCurrentClient;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/transports/base.js
var require_base = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/transports/base.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build2();
    var DEFAULT_TRANSPORT_BUFFER_SIZE = 30;
    function createTransport(options, makeRequest, buffer = utils.makePromiseBuffer(
      options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE
    )) {
      let rateLimits = {};
      const flush = (timeout) => buffer.drain(timeout);
      function send(envelope) {
        const filteredEnvelopeItems = [];
        utils.forEachEnvelopeItem(envelope, (item, type) => {
          const dataCategory = utils.envelopeItemTypeToDataCategory(type);
          if (utils.isRateLimited(rateLimits, dataCategory)) {
            const event = getEventForEnvelopeItem(item, type);
            options.recordDroppedEvent("ratelimit_backoff", dataCategory, event);
          } else {
            filteredEnvelopeItems.push(item);
          }
        });
        if (filteredEnvelopeItems.length === 0) {
          return utils.resolvedSyncPromise();
        }
        const filteredEnvelope = utils.createEnvelope(envelope[0], filteredEnvelopeItems);
        const recordEnvelopeLoss = (reason) => {
          utils.forEachEnvelopeItem(filteredEnvelope, (item, type) => {
            const event = getEventForEnvelopeItem(item, type);
            options.recordDroppedEvent(reason, utils.envelopeItemTypeToDataCategory(type), event);
          });
        };
        const requestTask = () => makeRequest({ body: utils.serializeEnvelope(filteredEnvelope, options.textEncoder) }).then(
          (response) => {
            if (response.statusCode !== void 0 && (response.statusCode < 200 || response.statusCode >= 300)) {
              debugBuild.DEBUG_BUILD && utils.logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);
            }
            rateLimits = utils.updateRateLimits(rateLimits, response);
            return response;
          },
          (error) => {
            recordEnvelopeLoss("network_error");
            throw error;
          }
        );
        return buffer.add(requestTask).then(
          (result) => result,
          (error) => {
            if (error instanceof utils.SentryError) {
              debugBuild.DEBUG_BUILD && utils.logger.error("Skipped sending event because buffer is full.");
              recordEnvelopeLoss("queue_overflow");
              return utils.resolvedSyncPromise();
            } else {
              throw error;
            }
          }
        );
      }
      send.__sentry__baseTransport__ = true;
      return {
        send,
        flush
      };
    }
    function getEventForEnvelopeItem(item, type) {
      if (type !== "event" && type !== "transaction") {
        return void 0;
      }
      return Array.isArray(item) ? item[1] : void 0;
    }
    exports.DEFAULT_TRANSPORT_BUFFER_SIZE = DEFAULT_TRANSPORT_BUFFER_SIZE;
    exports.createTransport = createTransport;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/transports/offline.js
var require_offline = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/transports/offline.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build2();
    var MIN_DELAY = 100;
    var START_DELAY = 5e3;
    var MAX_DELAY = 36e5;
    function log2(msg, error) {
      debugBuild.DEBUG_BUILD && utils.logger.info(`[Offline]: ${msg}`, error);
    }
    function makeOfflineTransport(createTransport) {
      return (options) => {
        const transport = createTransport(options);
        const store = options.createStore ? options.createStore(options) : void 0;
        let retryDelay = START_DELAY;
        let flushTimer;
        function shouldQueue(env2, error, retryDelay2) {
          if (utils.envelopeContainsItemType(env2, ["replay_event", "replay_recording", "client_report"])) {
            return false;
          }
          if (options.shouldStore) {
            return options.shouldStore(env2, error, retryDelay2);
          }
          return true;
        }
        function flushIn(delay) {
          if (!store) {
            return;
          }
          if (flushTimer) {
            clearTimeout(flushTimer);
          }
          flushTimer = setTimeout(async () => {
            flushTimer = void 0;
            const found = await store.pop();
            if (found) {
              log2("Attempting to send previously queued event");
              void send(found).catch((e2) => {
                log2("Failed to retry sending", e2);
              });
            }
          }, delay);
          if (typeof flushTimer !== "number" && flushTimer.unref) {
            flushTimer.unref();
          }
        }
        function flushWithBackOff() {
          if (flushTimer) {
            return;
          }
          flushIn(retryDelay);
          retryDelay = Math.min(retryDelay * 2, MAX_DELAY);
        }
        async function send(envelope) {
          try {
            const result = await transport.send(envelope);
            let delay = MIN_DELAY;
            if (result) {
              if (result.headers && result.headers["retry-after"]) {
                delay = utils.parseRetryAfterHeader(result.headers["retry-after"]);
              } else if ((result.statusCode || 0) >= 400) {
                return result;
              }
            }
            flushIn(delay);
            retryDelay = START_DELAY;
            return result;
          } catch (e2) {
            if (store && await shouldQueue(envelope, e2, retryDelay)) {
              await store.insert(envelope);
              flushWithBackOff();
              log2("Error sending. Event queued", e2);
              return {};
            } else {
              throw e2;
            }
          }
        }
        if (options.flushAtStartup) {
          flushWithBackOff();
        }
        return {
          send,
          flush: (t2) => transport.flush(t2)
        };
      };
    }
    exports.MIN_DELAY = MIN_DELAY;
    exports.START_DELAY = START_DELAY;
    exports.makeOfflineTransport = makeOfflineTransport;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/transports/multiplexed.js
var require_multiplexed = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/transports/multiplexed.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var api = require_api();
    function eventFromEnvelope(env2, types) {
      let event;
      utils.forEachEnvelopeItem(env2, (item, type) => {
        if (types.includes(type)) {
          event = Array.isArray(item) ? item[1] : void 0;
        }
        return !!event;
      });
      return event;
    }
    function makeOverrideReleaseTransport(createTransport, release) {
      return (options) => {
        const transport = createTransport(options);
        return {
          ...transport,
          send: async (envelope) => {
            const event = eventFromEnvelope(envelope, ["event", "transaction", "profile", "replay_event"]);
            if (event) {
              event.release = release;
            }
            return transport.send(envelope);
          }
        };
      };
    }
    function overrideDsn(envelope, dsn) {
      return utils.createEnvelope(
        dsn ? {
          ...envelope[0],
          dsn
        } : envelope[0],
        envelope[1]
      );
    }
    function makeMultiplexedTransport(createTransport, matcher) {
      return (options) => {
        const fallbackTransport = createTransport(options);
        const otherTransports = /* @__PURE__ */ new Map();
        function getTransport(dsn, release) {
          const key = release ? `${dsn}:${release}` : dsn;
          let transport = otherTransports.get(key);
          if (!transport) {
            const validatedDsn = utils.dsnFromString(dsn);
            if (!validatedDsn) {
              return void 0;
            }
            const url = api.getEnvelopeEndpointWithUrlEncodedAuth(validatedDsn, options.tunnel);
            transport = release ? makeOverrideReleaseTransport(createTransport, release)({ ...options, url }) : createTransport({ ...options, url });
            otherTransports.set(key, transport);
          }
          return [dsn, transport];
        }
        async function send(envelope) {
          function getEvent(types) {
            const eventTypes = types && types.length ? types : ["event"];
            return eventFromEnvelope(envelope, eventTypes);
          }
          const transports = matcher({ envelope, getEvent }).map((result) => {
            if (typeof result === "string") {
              return getTransport(result, void 0);
            } else {
              return getTransport(result.dsn, result.release);
            }
          }).filter((t2) => !!t2);
          if (transports.length === 0) {
            transports.push(["", fallbackTransport]);
          }
          const results = await Promise.all(
            transports.map(([dsn, transport]) => transport.send(overrideDsn(envelope, dsn)))
          );
          return results[0];
        }
        async function flush(timeout) {
          const promises = [await fallbackTransport.flush(timeout)];
          for (const [, transport] of otherTransports) {
            promises.push(await transport.flush(timeout));
          }
          return promises.every((r3) => r3);
        }
        return {
          send,
          flush
        };
      };
    }
    exports.eventFromEnvelope = eventFromEnvelope;
    exports.makeMultiplexedTransport = makeMultiplexedTransport;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/span.js
var require_span2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/span.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    function createSpanEnvelope(spans, dsn) {
      const headers = {
        sent_at: (/* @__PURE__ */ new Date()).toISOString()
      };
      if (dsn) {
        headers.dsn = utils.dsnToString(dsn);
      }
      const items = spans.map(createSpanItem);
      return utils.createEnvelope(headers, items);
    }
    function createSpanItem(span) {
      const spanHeaders = {
        type: "span"
      };
      return [spanHeaders, span];
    }
    exports.createSpanEnvelope = createSpanEnvelope;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/utils/isSentryRequestUrl.js
var require_isSentryRequestUrl = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/utils/isSentryRequestUrl.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    function isSentryRequestUrl(url, hubOrClient) {
      const client = hubOrClient && isHub(hubOrClient) ? (
        // eslint-disable-next-line deprecation/deprecation
        hubOrClient.getClient()
      ) : hubOrClient;
      const dsn = client && client.getDsn();
      const tunnel = client && client.getOptions().tunnel;
      return checkDsn(url, dsn) || checkTunnel(url, tunnel);
    }
    function checkTunnel(url, tunnel) {
      if (!tunnel) {
        return false;
      }
      return removeTrailingSlash(url) === removeTrailingSlash(tunnel);
    }
    function checkDsn(url, dsn) {
      return dsn ? url.includes(dsn.host) : false;
    }
    function removeTrailingSlash(str) {
      return str[str.length - 1] === "/" ? str.slice(0, -1) : str;
    }
    function isHub(hubOrClient) {
      return hubOrClient.getClient !== void 0;
    }
    exports.isSentryRequestUrl = isSentryRequestUrl;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/utils/parameterize.js
var require_parameterize = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/utils/parameterize.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    function parameterize(strings, ...values) {
      const formatted = new String(String.raw(strings, ...values));
      formatted.__sentry_template_string__ = strings.join("\0").replace(/%/g, "%%").replace(/\0/g, "%s");
      formatted.__sentry_template_values__ = values;
      return formatted;
    }
    exports.parameterize = parameterize;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/utils/sdkMetadata.js
var require_sdkMetadata = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/utils/sdkMetadata.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var version2 = require_version();
    function applySdkMetadata(options, name, names = [name], source = "npm") {
      const metadata = options._metadata || {};
      if (!metadata.sdk) {
        metadata.sdk = {
          name: `sentry.javascript.${name}`,
          packages: names.map((name2) => ({
            name: `${source}:@sentry/${name2}`,
            version: version2.SDK_VERSION
          })),
          version: version2.SDK_VERSION
        };
      }
      options._metadata = metadata;
    }
    exports.applySdkMetadata = applySdkMetadata;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metadata.js
var require_metadata = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metadata.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var filenameMetadataMap = /* @__PURE__ */ new Map();
    var parsedStacks = /* @__PURE__ */ new Set();
    function ensureMetadataStacksAreParsed(parser) {
      if (!utils.GLOBAL_OBJ._sentryModuleMetadata) {
        return;
      }
      for (const stack of Object.keys(utils.GLOBAL_OBJ._sentryModuleMetadata)) {
        const metadata = utils.GLOBAL_OBJ._sentryModuleMetadata[stack];
        if (parsedStacks.has(stack)) {
          continue;
        }
        parsedStacks.add(stack);
        const frames = parser(stack);
        for (const frame of frames.reverse()) {
          if (frame.filename) {
            filenameMetadataMap.set(frame.filename, metadata);
            break;
          }
        }
      }
    }
    function getMetadataForUrl(parser, filename) {
      ensureMetadataStacksAreParsed(parser);
      return filenameMetadataMap.get(filename);
    }
    function addMetadataToStackFrames(parser, event) {
      try {
        event.exception.values.forEach((exception) => {
          if (!exception.stacktrace) {
            return;
          }
          for (const frame of exception.stacktrace.frames || []) {
            if (!frame.filename) {
              continue;
            }
            const metadata = getMetadataForUrl(parser, frame.filename);
            if (metadata) {
              frame.module_metadata = metadata;
            }
          }
        });
      } catch (_3) {
      }
    }
    function stripMetadataFromStackFrames(event) {
      try {
        event.exception.values.forEach((exception) => {
          if (!exception.stacktrace) {
            return;
          }
          for (const frame of exception.stacktrace.frames || []) {
            delete frame.module_metadata;
          }
        });
      } catch (_3) {
      }
    }
    exports.addMetadataToStackFrames = addMetadataToStackFrames;
    exports.getMetadataForUrl = getMetadataForUrl;
    exports.stripMetadataFromStackFrames = stripMetadataFromStackFrames;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/integrations/metadata.js
var require_metadata2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/integrations/metadata.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var integration = require_integration();
    var metadata = require_metadata();
    var INTEGRATION_NAME = "ModuleMetadata";
    var _moduleMetadataIntegration = () => {
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        setup(client) {
          if (typeof client.on !== "function") {
            return;
          }
          client.on("beforeEnvelope", (envelope) => {
            utils.forEachEnvelopeItem(envelope, (item, type) => {
              if (type === "event") {
                const event = Array.isArray(item) ? item[1] : void 0;
                if (event) {
                  metadata.stripMetadataFromStackFrames(event);
                  item[1] = event;
                }
              }
            });
          });
        },
        processEvent(event, _hint, client) {
          const stackParser = client.getOptions().stackParser;
          metadata.addMetadataToStackFrames(stackParser, event);
          return event;
        }
      };
    };
    var moduleMetadataIntegration = integration.defineIntegration(_moduleMetadataIntegration);
    var ModuleMetadata = integration.convertIntegrationFnToClass(
      INTEGRATION_NAME,
      moduleMetadataIntegration
    );
    exports.ModuleMetadata = ModuleMetadata;
    exports.moduleMetadataIntegration = moduleMetadataIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/integrations/requestdata.js
var require_requestdata2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/integrations/requestdata.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var integration = require_integration();
    var spanUtils = require_spanUtils();
    var DEFAULT_OPTIONS = {
      include: {
        cookies: true,
        data: true,
        headers: true,
        ip: false,
        query_string: true,
        url: true,
        user: {
          id: true,
          username: true,
          email: true
        }
      },
      transactionNamingScheme: "methodPath"
    };
    var INTEGRATION_NAME = "RequestData";
    var _requestDataIntegration = (options = {}) => {
      const _addRequestData = utils.addRequestDataToEvent;
      const _options = {
        ...DEFAULT_OPTIONS,
        ...options,
        include: {
          // @ts-expect-error It's mad because `method` isn't a known `include` key. (It's only here and not set by default in
          // `addRequestDataToEvent` for legacy reasons. TODO (v8): Change that.)
          method: true,
          ...DEFAULT_OPTIONS.include,
          ...options.include,
          user: options.include && typeof options.include.user === "boolean" ? options.include.user : {
            ...DEFAULT_OPTIONS.include.user,
            // Unclear why TS still thinks `options.include.user` could be a boolean at this point
            ...(options.include || {}).user
          }
        }
      };
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        processEvent(event, _hint, client) {
          const { transactionNamingScheme } = _options;
          const { sdkProcessingMetadata = {} } = event;
          const req = sdkProcessingMetadata.request;
          if (!req) {
            return event;
          }
          const addRequestDataOptions = sdkProcessingMetadata.requestDataOptionsFromExpressHandler || sdkProcessingMetadata.requestDataOptionsFromGCPWrapper || convertReqDataIntegrationOptsToAddReqDataOpts(_options);
          const processedEvent = _addRequestData(event, req, addRequestDataOptions);
          if (event.type === "transaction" || transactionNamingScheme === "handler") {
            return processedEvent;
          }
          const reqWithTransaction = req;
          const transaction = reqWithTransaction._sentryTransaction;
          if (transaction) {
            const name = spanUtils.spanToJSON(transaction).description || "";
            const shouldIncludeMethodInTransactionName = getSDKName(client) === "sentry.javascript.nextjs" ? name.startsWith("/api") : transactionNamingScheme !== "path";
            const [transactionValue] = utils.extractPathForTransaction(req, {
              path: true,
              method: shouldIncludeMethodInTransactionName,
              customRoute: name
            });
            processedEvent.transaction = transactionValue;
          }
          return processedEvent;
        }
      };
    };
    var requestDataIntegration = integration.defineIntegration(_requestDataIntegration);
    var RequestData = integration.convertIntegrationFnToClass(INTEGRATION_NAME, requestDataIntegration);
    function convertReqDataIntegrationOptsToAddReqDataOpts(integrationOptions) {
      const {
        transactionNamingScheme,
        include: { ip, user, ...requestOptions }
      } = integrationOptions;
      const requestIncludeKeys = [];
      for (const [key, value] of Object.entries(requestOptions)) {
        if (value) {
          requestIncludeKeys.push(key);
        }
      }
      let addReqDataUserOpt;
      if (user === void 0) {
        addReqDataUserOpt = true;
      } else if (typeof user === "boolean") {
        addReqDataUserOpt = user;
      } else {
        const userIncludeKeys = [];
        for (const [key, value] of Object.entries(user)) {
          if (value) {
            userIncludeKeys.push(key);
          }
        }
        addReqDataUserOpt = userIncludeKeys;
      }
      return {
        include: {
          ip,
          user: addReqDataUserOpt,
          request: requestIncludeKeys.length !== 0 ? requestIncludeKeys : void 0,
          transaction: transactionNamingScheme
        }
      };
    }
    function getSDKName(client) {
      try {
        return client.getOptions()._metadata.sdk.name;
      } catch (err) {
        return void 0;
      }
    }
    exports.RequestData = RequestData;
    exports.requestDataIntegration = requestDataIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/integrations/inboundfilters.js
var require_inboundfilters = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/integrations/inboundfilters.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build2();
    var integration = require_integration();
    var DEFAULT_IGNORE_ERRORS = [
      /^Script error\.?$/,
      /^Javascript error: Script error\.? on line 0$/,
      /^ResizeObserver loop completed with undelivered notifications.$/,
      /^Cannot redefine property: googletag$/
    ];
    var DEFAULT_IGNORE_TRANSACTIONS = [
      /^.*\/healthcheck$/,
      /^.*\/healthy$/,
      /^.*\/live$/,
      /^.*\/ready$/,
      /^.*\/heartbeat$/,
      /^.*\/health$/,
      /^.*\/healthz$/
    ];
    var INTEGRATION_NAME = "InboundFilters";
    var _inboundFiltersIntegration = (options = {}) => {
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        processEvent(event, _hint, client) {
          const clientOptions = client.getOptions();
          const mergedOptions = _mergeOptions(options, clientOptions);
          return _shouldDropEvent(event, mergedOptions) ? null : event;
        }
      };
    };
    var inboundFiltersIntegration = integration.defineIntegration(_inboundFiltersIntegration);
    var InboundFilters = integration.convertIntegrationFnToClass(
      INTEGRATION_NAME,
      inboundFiltersIntegration
    );
    function _mergeOptions(internalOptions = {}, clientOptions = {}) {
      return {
        allowUrls: [...internalOptions.allowUrls || [], ...clientOptions.allowUrls || []],
        denyUrls: [...internalOptions.denyUrls || [], ...clientOptions.denyUrls || []],
        ignoreErrors: [
          ...internalOptions.ignoreErrors || [],
          ...clientOptions.ignoreErrors || [],
          ...internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS
        ],
        ignoreTransactions: [
          ...internalOptions.ignoreTransactions || [],
          ...clientOptions.ignoreTransactions || [],
          ...internalOptions.disableTransactionDefaults ? [] : DEFAULT_IGNORE_TRANSACTIONS
        ],
        ignoreInternal: internalOptions.ignoreInternal !== void 0 ? internalOptions.ignoreInternal : true
      };
    }
    function _shouldDropEvent(event, options) {
      if (options.ignoreInternal && _isSentryError(event)) {
        debugBuild.DEBUG_BUILD && utils.logger.warn(`Event dropped due to being internal Sentry Error.
Event: ${utils.getEventDescription(event)}`);
        return true;
      }
      if (_isIgnoredError(event, options.ignoreErrors)) {
        debugBuild.DEBUG_BUILD && utils.logger.warn(
          `Event dropped due to being matched by \`ignoreErrors\` option.
Event: ${utils.getEventDescription(event)}`
        );
        return true;
      }
      if (_isIgnoredTransaction(event, options.ignoreTransactions)) {
        debugBuild.DEBUG_BUILD && utils.logger.warn(
          `Event dropped due to being matched by \`ignoreTransactions\` option.
Event: ${utils.getEventDescription(event)}`
        );
        return true;
      }
      if (_isDeniedUrl(event, options.denyUrls)) {
        debugBuild.DEBUG_BUILD && utils.logger.warn(
          `Event dropped due to being matched by \`denyUrls\` option.
Event: ${utils.getEventDescription(
            event
          )}.
Url: ${_getEventFilterUrl(event)}`
        );
        return true;
      }
      if (!_isAllowedUrl(event, options.allowUrls)) {
        debugBuild.DEBUG_BUILD && utils.logger.warn(
          `Event dropped due to not being matched by \`allowUrls\` option.
Event: ${utils.getEventDescription(
            event
          )}.
Url: ${_getEventFilterUrl(event)}`
        );
        return true;
      }
      return false;
    }
    function _isIgnoredError(event, ignoreErrors) {
      if (event.type || !ignoreErrors || !ignoreErrors.length) {
        return false;
      }
      return _getPossibleEventMessages(event).some((message) => utils.stringMatchesSomePattern(message, ignoreErrors));
    }
    function _isIgnoredTransaction(event, ignoreTransactions) {
      if (event.type !== "transaction" || !ignoreTransactions || !ignoreTransactions.length) {
        return false;
      }
      const name = event.transaction;
      return name ? utils.stringMatchesSomePattern(name, ignoreTransactions) : false;
    }
    function _isDeniedUrl(event, denyUrls) {
      if (!denyUrls || !denyUrls.length) {
        return false;
      }
      const url = _getEventFilterUrl(event);
      return !url ? false : utils.stringMatchesSomePattern(url, denyUrls);
    }
    function _isAllowedUrl(event, allowUrls) {
      if (!allowUrls || !allowUrls.length) {
        return true;
      }
      const url = _getEventFilterUrl(event);
      return !url ? true : utils.stringMatchesSomePattern(url, allowUrls);
    }
    function _getPossibleEventMessages(event) {
      const possibleMessages = [];
      if (event.message) {
        possibleMessages.push(event.message);
      }
      let lastException;
      try {
        lastException = event.exception.values[event.exception.values.length - 1];
      } catch (e2) {
      }
      if (lastException) {
        if (lastException.value) {
          possibleMessages.push(lastException.value);
          if (lastException.type) {
            possibleMessages.push(`${lastException.type}: ${lastException.value}`);
          }
        }
      }
      if (debugBuild.DEBUG_BUILD && possibleMessages.length === 0) {
        utils.logger.error(`Could not extract message for event ${utils.getEventDescription(event)}`);
      }
      return possibleMessages;
    }
    function _isSentryError(event) {
      try {
        return event.exception.values[0].type === "SentryError";
      } catch (e2) {
      }
      return false;
    }
    function _getLastValidUrl(frames = []) {
      for (let i2 = frames.length - 1; i2 >= 0; i2--) {
        const frame = frames[i2];
        if (frame && frame.filename !== "<anonymous>" && frame.filename !== "[native code]") {
          return frame.filename || null;
        }
      }
      return null;
    }
    function _getEventFilterUrl(event) {
      try {
        let frames;
        try {
          frames = event.exception.values[0].stacktrace.frames;
        } catch (e2) {
        }
        return frames ? _getLastValidUrl(frames) : null;
      } catch (oO) {
        debugBuild.DEBUG_BUILD && utils.logger.error(`Cannot extract url for event ${utils.getEventDescription(event)}`);
        return null;
      }
    }
    exports.InboundFilters = InboundFilters;
    exports.inboundFiltersIntegration = inboundFiltersIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/integrations/functiontostring.js
var require_functiontostring = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/integrations/functiontostring.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var exports$1 = require_exports();
    var integration = require_integration();
    var originalFunctionToString;
    var INTEGRATION_NAME = "FunctionToString";
    var SETUP_CLIENTS = /* @__PURE__ */ new WeakMap();
    var _functionToStringIntegration = () => {
      return {
        name: INTEGRATION_NAME,
        setupOnce() {
          originalFunctionToString = Function.prototype.toString;
          try {
            Function.prototype.toString = function(...args) {
              const originalFunction = utils.getOriginalFunction(this);
              const context2 = SETUP_CLIENTS.has(exports$1.getClient()) && originalFunction !== void 0 ? originalFunction : this;
              return originalFunctionToString.apply(context2, args);
            };
          } catch (e2) {
          }
        },
        setup(client) {
          SETUP_CLIENTS.set(client, true);
        }
      };
    };
    var functionToStringIntegration = integration.defineIntegration(_functionToStringIntegration);
    var FunctionToString = integration.convertIntegrationFnToClass(
      INTEGRATION_NAME,
      functionToStringIntegration
    );
    exports.FunctionToString = FunctionToString;
    exports.functionToStringIntegration = functionToStringIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/integrations/linkederrors.js
var require_linkederrors = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/integrations/linkederrors.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var integration = require_integration();
    var DEFAULT_KEY = "cause";
    var DEFAULT_LIMIT = 5;
    var INTEGRATION_NAME = "LinkedErrors";
    var _linkedErrorsIntegration = (options = {}) => {
      const limit = options.limit || DEFAULT_LIMIT;
      const key = options.key || DEFAULT_KEY;
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        preprocessEvent(event, hint, client) {
          const options2 = client.getOptions();
          utils.applyAggregateErrorsToEvent(
            utils.exceptionFromError,
            options2.stackParser,
            options2.maxValueLength,
            key,
            limit,
            event,
            hint
          );
        }
      };
    };
    var linkedErrorsIntegration = integration.defineIntegration(_linkedErrorsIntegration);
    var LinkedErrors = integration.convertIntegrationFnToClass(INTEGRATION_NAME, linkedErrorsIntegration);
    exports.LinkedErrors = LinkedErrors;
    exports.linkedErrorsIntegration = linkedErrorsIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/integrations/index.js
var require_integrations = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/integrations/index.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var functiontostring = require_functiontostring();
    var inboundfilters = require_inboundfilters();
    var linkederrors = require_linkederrors();
    exports.FunctionToString = functiontostring.FunctionToString;
    exports.InboundFilters = inboundfilters.InboundFilters;
    exports.LinkedErrors = linkederrors.LinkedErrors;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metrics/browser-aggregator.js
var require_browser_aggregator = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metrics/browser-aggregator.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils$1 = require_cjs();
    var constants = require_constants2();
    var instance = require_instance();
    var metricSummary = require_metric_summary();
    var utils = require_utils2();
    var BrowserMetricsAggregator = class {
      // TODO(@anonrig): Use FinalizationRegistry to have a proper way of flushing the buckets
      // when the aggregator is garbage collected.
      // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
      constructor(_client) {
        this._client = _client;
        this._buckets = /* @__PURE__ */ new Map();
        this._interval = setInterval(() => this.flush(), constants.DEFAULT_BROWSER_FLUSH_INTERVAL);
      }
      /**
       * @inheritDoc
       */
      add(metricType, unsanitizedName, value, unsanitizedUnit = "none", unsanitizedTags = {}, maybeFloatTimestamp = utils$1.timestampInSeconds()) {
        const timestamp = Math.floor(maybeFloatTimestamp);
        const name = utils.sanitizeMetricKey(unsanitizedName);
        const tags = utils.sanitizeTags(unsanitizedTags);
        const unit = utils.sanitizeUnit(unsanitizedUnit);
        const bucketKey = utils.getBucketKey(metricType, name, unit, tags);
        let bucketItem = this._buckets.get(bucketKey);
        const previousWeight = bucketItem && metricType === constants.SET_METRIC_TYPE ? bucketItem.metric.weight : 0;
        if (bucketItem) {
          bucketItem.metric.add(value);
          if (bucketItem.timestamp < timestamp) {
            bucketItem.timestamp = timestamp;
          }
        } else {
          bucketItem = {
            // @ts-expect-error we don't need to narrow down the type of value here, saves bundle size.
            metric: new instance.METRIC_MAP[metricType](value),
            timestamp,
            metricType,
            name,
            unit,
            tags
          };
          this._buckets.set(bucketKey, bucketItem);
        }
        const val = typeof value === "string" ? bucketItem.metric.weight - previousWeight : value;
        metricSummary.updateMetricSummaryOnActiveSpan(metricType, name, val, unit, unsanitizedTags, bucketKey);
      }
      /**
       * @inheritDoc
       */
      flush() {
        if (this._buckets.size === 0) {
          return;
        }
        if (this._client.captureAggregateMetrics) {
          const metricBuckets = Array.from(this._buckets).map(([, bucketItem]) => bucketItem);
          this._client.captureAggregateMetrics(metricBuckets);
        }
        this._buckets.clear();
      }
      /**
       * @inheritDoc
       */
      close() {
        clearInterval(this._interval);
        this.flush();
      }
    };
    exports.BrowserMetricsAggregator = BrowserMetricsAggregator;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metrics/integration.js
var require_integration2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metrics/integration.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var integration = require_integration();
    var browserAggregator = require_browser_aggregator();
    var INTEGRATION_NAME = "MetricsAggregator";
    var _metricsAggregatorIntegration = () => {
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        setup(client) {
          client.metricsAggregator = new browserAggregator.BrowserMetricsAggregator(client);
        }
      };
    };
    var metricsAggregatorIntegration = integration.defineIntegration(_metricsAggregatorIntegration);
    var MetricsAggregator = integration.convertIntegrationFnToClass(
      INTEGRATION_NAME,
      metricsAggregatorIntegration
    );
    exports.MetricsAggregator = MetricsAggregator;
    exports.metricsAggregatorIntegration = metricsAggregatorIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metrics/exports.js
var require_exports2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/metrics/exports.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build2();
    var exports$1 = require_exports();
    var spanUtils = require_spanUtils();
    var constants = require_constants2();
    var integration = require_integration2();
    function addToMetricsAggregator(metricType, name, value, data = {}) {
      const client = exports$1.getClient();
      const scope = exports$1.getCurrentScope();
      if (client) {
        if (!client.metricsAggregator) {
          debugBuild.DEBUG_BUILD && utils.logger.warn("No metrics aggregator enabled. Please add the MetricsAggregator integration to use metrics APIs");
          return;
        }
        const { unit, tags, timestamp } = data;
        const { release, environment } = client.getOptions();
        const transaction = scope.getTransaction();
        const metricTags = {};
        if (release) {
          metricTags.release = release;
        }
        if (environment) {
          metricTags.environment = environment;
        }
        if (transaction) {
          metricTags.transaction = spanUtils.spanToJSON(transaction).description || "";
        }
        debugBuild.DEBUG_BUILD && utils.logger.log(`Adding value of ${value} to ${metricType} metric ${name}`);
        client.metricsAggregator.add(metricType, name, value, unit, { ...metricTags, ...tags }, timestamp);
      }
    }
    function increment(name, value = 1, data) {
      addToMetricsAggregator(constants.COUNTER_METRIC_TYPE, name, value, data);
    }
    function distribution(name, value, data) {
      addToMetricsAggregator(constants.DISTRIBUTION_METRIC_TYPE, name, value, data);
    }
    function set(name, value, data) {
      addToMetricsAggregator(constants.SET_METRIC_TYPE, name, value, data);
    }
    function gauge(name, value, data) {
      addToMetricsAggregator(constants.GAUGE_METRIC_TYPE, name, value, data);
    }
    var metrics = {
      increment,
      distribution,
      set,
      gauge,
      /** @deprecated Use `metrics.metricsAggregratorIntegration()` instead. */
      // eslint-disable-next-line deprecation/deprecation
      MetricsAggregator: integration.MetricsAggregator,
      metricsAggregatorIntegration: integration.metricsAggregatorIntegration
    };
    exports.distribution = distribution;
    exports.gauge = gauge;
    exports.increment = increment;
    exports.metrics = metrics;
    exports.set = set;
  }
});

// ../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/index.js
var require_cjs2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+core@7.120.3/node_modules/@sentry/core/cjs/index.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var hubextensions = require_hubextensions();
    var idletransaction = require_idletransaction();
    var span$1 = require_span();
    var transaction = require_transaction();
    var utils = require_utils();
    var spanstatus = require_spanstatus();
    var trace = require_trace();
    var dynamicSamplingContext = require_dynamicSamplingContext();
    var measurement = require_measurement();
    var sampling = require_sampling();
    var semanticAttributes = require_semanticAttributes();
    var envelope = require_envelope2();
    var exports$1 = require_exports();
    var hub = require_hub();
    var session = require_session();
    var sessionflusher = require_sessionflusher();
    var scope = require_scope();
    var eventProcessors = require_eventProcessors();
    var api = require_api();
    var baseclient = require_baseclient();
    var serverRuntimeClient = require_server_runtime_client();
    var sdk = require_sdk();
    var base = require_base();
    var offline = require_offline();
    var multiplexed = require_multiplexed();
    var version2 = require_version();
    var integration = require_integration();
    var applyScopeDataToEvent = require_applyScopeDataToEvent();
    var prepareEvent = require_prepareEvent();
    var checkin = require_checkin();
    var span = require_span2();
    var hasTracingEnabled = require_hasTracingEnabled();
    var isSentryRequestUrl = require_isSentryRequestUrl();
    var handleCallbackErrors = require_handleCallbackErrors();
    var parameterize = require_parameterize();
    var spanUtils = require_spanUtils();
    var getRootSpan = require_getRootSpan();
    var sdkMetadata = require_sdkMetadata();
    var constants = require_constants();
    var metadata = require_metadata2();
    var requestdata = require_requestdata2();
    var inboundfilters = require_inboundfilters();
    var functiontostring = require_functiontostring();
    var linkederrors = require_linkederrors();
    var index = require_integrations();
    var exports$2 = require_exports2();
    var Integrations = index;
    exports.addTracingExtensions = hubextensions.addTracingExtensions;
    exports.startIdleTransaction = hubextensions.startIdleTransaction;
    exports.IdleTransaction = idletransaction.IdleTransaction;
    exports.TRACING_DEFAULTS = idletransaction.TRACING_DEFAULTS;
    exports.Span = span$1.Span;
    exports.Transaction = transaction.Transaction;
    exports.extractTraceparentData = utils.extractTraceparentData;
    exports.getActiveTransaction = utils.getActiveTransaction;
    Object.defineProperty(exports, "SpanStatus", {
      enumerable: true,
      get: () => spanstatus.SpanStatus
    });
    exports.getSpanStatusFromHttpCode = spanstatus.getSpanStatusFromHttpCode;
    exports.setHttpStatus = spanstatus.setHttpStatus;
    exports.spanStatusfromHttpCode = spanstatus.spanStatusfromHttpCode;
    exports.continueTrace = trace.continueTrace;
    exports.getActiveSpan = trace.getActiveSpan;
    exports.startActiveSpan = trace.startActiveSpan;
    exports.startInactiveSpan = trace.startInactiveSpan;
    exports.startSpan = trace.startSpan;
    exports.startSpanManual = trace.startSpanManual;
    exports.trace = trace.trace;
    exports.getDynamicSamplingContextFromClient = dynamicSamplingContext.getDynamicSamplingContextFromClient;
    exports.getDynamicSamplingContextFromSpan = dynamicSamplingContext.getDynamicSamplingContextFromSpan;
    exports.setMeasurement = measurement.setMeasurement;
    exports.isValidSampleRate = sampling.isValidSampleRate;
    exports.SEMANTIC_ATTRIBUTE_PROFILE_ID = semanticAttributes.SEMANTIC_ATTRIBUTE_PROFILE_ID;
    exports.SEMANTIC_ATTRIBUTE_SENTRY_OP = semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_OP;
    exports.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN;
    exports.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE;
    exports.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE;
    exports.createEventEnvelope = envelope.createEventEnvelope;
    exports.createSessionEnvelope = envelope.createSessionEnvelope;
    exports.addBreadcrumb = exports$1.addBreadcrumb;
    exports.captureCheckIn = exports$1.captureCheckIn;
    exports.captureEvent = exports$1.captureEvent;
    exports.captureException = exports$1.captureException;
    exports.captureMessage = exports$1.captureMessage;
    exports.captureSession = exports$1.captureSession;
    exports.close = exports$1.close;
    exports.configureScope = exports$1.configureScope;
    exports.endSession = exports$1.endSession;
    exports.flush = exports$1.flush;
    exports.getClient = exports$1.getClient;
    exports.getCurrentScope = exports$1.getCurrentScope;
    exports.isInitialized = exports$1.isInitialized;
    exports.lastEventId = exports$1.lastEventId;
    exports.setContext = exports$1.setContext;
    exports.setExtra = exports$1.setExtra;
    exports.setExtras = exports$1.setExtras;
    exports.setTag = exports$1.setTag;
    exports.setTags = exports$1.setTags;
    exports.setUser = exports$1.setUser;
    exports.startSession = exports$1.startSession;
    exports.startTransaction = exports$1.startTransaction;
    exports.withActiveSpan = exports$1.withActiveSpan;
    exports.withIsolationScope = exports$1.withIsolationScope;
    exports.withMonitor = exports$1.withMonitor;
    exports.withScope = exports$1.withScope;
    exports.Hub = hub.Hub;
    exports.ensureHubOnCarrier = hub.ensureHubOnCarrier;
    exports.getCurrentHub = hub.getCurrentHub;
    exports.getHubFromCarrier = hub.getHubFromCarrier;
    exports.getIsolationScope = hub.getIsolationScope;
    exports.getMainCarrier = hub.getMainCarrier;
    exports.makeMain = hub.makeMain;
    exports.runWithAsyncContext = hub.runWithAsyncContext;
    exports.setAsyncContextStrategy = hub.setAsyncContextStrategy;
    exports.setHubOnCarrier = hub.setHubOnCarrier;
    exports.closeSession = session.closeSession;
    exports.makeSession = session.makeSession;
    exports.updateSession = session.updateSession;
    exports.SessionFlusher = sessionflusher.SessionFlusher;
    exports.Scope = scope.Scope;
    exports.getGlobalScope = scope.getGlobalScope;
    exports.setGlobalScope = scope.setGlobalScope;
    exports.addGlobalEventProcessor = eventProcessors.addGlobalEventProcessor;
    exports.notifyEventProcessors = eventProcessors.notifyEventProcessors;
    exports.getEnvelopeEndpointWithUrlEncodedAuth = api.getEnvelopeEndpointWithUrlEncodedAuth;
    exports.getReportDialogEndpoint = api.getReportDialogEndpoint;
    exports.BaseClient = baseclient.BaseClient;
    exports.addEventProcessor = baseclient.addEventProcessor;
    exports.ServerRuntimeClient = serverRuntimeClient.ServerRuntimeClient;
    exports.initAndBind = sdk.initAndBind;
    exports.setCurrentClient = sdk.setCurrentClient;
    exports.createTransport = base.createTransport;
    exports.makeOfflineTransport = offline.makeOfflineTransport;
    exports.makeMultiplexedTransport = multiplexed.makeMultiplexedTransport;
    exports.SDK_VERSION = version2.SDK_VERSION;
    exports.addIntegration = integration.addIntegration;
    exports.convertIntegrationFnToClass = integration.convertIntegrationFnToClass;
    exports.defineIntegration = integration.defineIntegration;
    exports.getIntegrationsToSetup = integration.getIntegrationsToSetup;
    exports.applyScopeDataToEvent = applyScopeDataToEvent.applyScopeDataToEvent;
    exports.mergeScopeData = applyScopeDataToEvent.mergeScopeData;
    exports.prepareEvent = prepareEvent.prepareEvent;
    exports.createCheckInEnvelope = checkin.createCheckInEnvelope;
    exports.createSpanEnvelope = span.createSpanEnvelope;
    exports.hasTracingEnabled = hasTracingEnabled.hasTracingEnabled;
    exports.isSentryRequestUrl = isSentryRequestUrl.isSentryRequestUrl;
    exports.handleCallbackErrors = handleCallbackErrors.handleCallbackErrors;
    exports.parameterize = parameterize.parameterize;
    exports.spanIsSampled = spanUtils.spanIsSampled;
    exports.spanToJSON = spanUtils.spanToJSON;
    exports.spanToTraceContext = spanUtils.spanToTraceContext;
    exports.spanToTraceHeader = spanUtils.spanToTraceHeader;
    exports.getRootSpan = getRootSpan.getRootSpan;
    exports.applySdkMetadata = sdkMetadata.applySdkMetadata;
    exports.DEFAULT_ENVIRONMENT = constants.DEFAULT_ENVIRONMENT;
    exports.ModuleMetadata = metadata.ModuleMetadata;
    exports.moduleMetadataIntegration = metadata.moduleMetadataIntegration;
    exports.RequestData = requestdata.RequestData;
    exports.requestDataIntegration = requestdata.requestDataIntegration;
    exports.InboundFilters = inboundfilters.InboundFilters;
    exports.inboundFiltersIntegration = inboundfilters.inboundFiltersIntegration;
    exports.FunctionToString = functiontostring.FunctionToString;
    exports.functionToStringIntegration = functiontostring.functionToStringIntegration;
    exports.LinkedErrors = linkederrors.LinkedErrors;
    exports.linkedErrorsIntegration = linkederrors.linkedErrorsIntegration;
    exports.metrics = exports$2.metrics;
    exports.Integrations = Integrations;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/common/debug-build.js
var require_debug_build3 = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/common/debug-build.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
    exports.DEBUG_BUILD = DEBUG_BUILD;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/node/integrations/utils/node-utils.js
var require_node_utils = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/node/integrations/utils/node-utils.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    function shouldDisableAutoInstrumentation(getCurrentHub) {
      const clientOptions = _optionalChain([getCurrentHub, "call", (_3) => _3(), "access", (_22) => _22.getClient, "call", (_3) => _3(), "optionalAccess", (_4) => _4.getOptions, "call", (_5) => _5()]);
      const instrumenter = _optionalChain([clientOptions, "optionalAccess", (_6) => _6.instrumenter]) || "sentry";
      return instrumenter !== "sentry";
    }
    exports.shouldDisableAutoInstrumentation = shouldDisableAutoInstrumentation;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/node/integrations/express.js
var require_express = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/node/integrations/express.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var debugBuild = require_debug_build3();
    var nodeUtils = require_node_utils();
    var Express = class _Express {
      /**
       * @inheritDoc
       */
      static __initStatic() {
        this.id = "Express";
      }
      /**
       * @inheritDoc
       */
      /**
       * Express App instance
       */
      /**
       * @inheritDoc
       */
      constructor(options = {}) {
        this.name = _Express.id;
        this._router = options.router || options.app;
        this._methods = (Array.isArray(options.methods) ? options.methods : []).concat("use");
      }
      /**
       * @inheritDoc
       */
      // eslint-disable-next-line deprecation/deprecation
      setupOnce(_3, getCurrentHub) {
        if (!this._router) {
          debugBuild.DEBUG_BUILD && utils.logger.error("ExpressIntegration is missing an Express instance");
          return;
        }
        if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) {
          debugBuild.DEBUG_BUILD && utils.logger.log("Express Integration is skipped because of instrumenter configuration.");
          return;
        }
        instrumentMiddlewares(this._router, this._methods);
        instrumentRouter(this._router);
      }
    };
    Express.__initStatic();
    function wrap(fn, method) {
      const arity = fn.length;
      switch (arity) {
        case 2: {
          return function(req, res) {
            const transaction = res.__sentry_transaction;
            if (transaction) {
              const span = transaction.startChild({
                description: fn.name,
                op: `middleware.express.${method}`,
                origin: "auto.middleware.express"
              });
              res.once("finish", () => {
                span.end();
              });
            }
            return fn.call(this, req, res);
          };
        }
        case 3: {
          return function(req, res, next) {
            const transaction = res.__sentry_transaction;
            const span = _optionalChain([transaction, "optionalAccess", (_22) => _22.startChild, "call", (_3) => _3({
              description: fn.name,
              op: `middleware.express.${method}`,
              origin: "auto.middleware.express"
            })]);
            fn.call(this, req, res, function(...args) {
              _optionalChain([span, "optionalAccess", (_4) => _4.end, "call", (_5) => _5()]);
              next.call(this, ...args);
            });
          };
        }
        case 4: {
          return function(err, req, res, next) {
            const transaction = res.__sentry_transaction;
            const span = _optionalChain([transaction, "optionalAccess", (_6) => _6.startChild, "call", (_7) => _7({
              description: fn.name,
              op: `middleware.express.${method}`,
              origin: "auto.middleware.express"
            })]);
            fn.call(this, err, req, res, function(...args) {
              _optionalChain([span, "optionalAccess", (_8) => _8.end, "call", (_9) => _9()]);
              next.call(this, ...args);
            });
          };
        }
        default: {
          throw new Error(`Express middleware takes 2-4 arguments. Got: ${arity}`);
        }
      }
    }
    function wrapMiddlewareArgs(args, method) {
      return args.map((arg) => {
        if (typeof arg === "function") {
          return wrap(arg, method);
        }
        if (Array.isArray(arg)) {
          return arg.map((a3) => {
            if (typeof a3 === "function") {
              return wrap(a3, method);
            }
            return a3;
          });
        }
        return arg;
      });
    }
    function patchMiddleware(router, method) {
      const originalCallback = router[method];
      router[method] = function(...args) {
        return originalCallback.call(this, ...wrapMiddlewareArgs(args, method));
      };
      return router;
    }
    function instrumentMiddlewares(router, methods = []) {
      methods.forEach((method) => patchMiddleware(router, method));
    }
    function instrumentRouter(appOrRouter) {
      const isApp = "settings" in appOrRouter;
      if (isApp && appOrRouter._router === void 0 && appOrRouter.lazyrouter) {
        appOrRouter.lazyrouter();
      }
      const router = isApp ? appOrRouter._router : appOrRouter;
      if (!router) {
        debugBuild.DEBUG_BUILD && utils.logger.debug("Cannot instrument router for URL Parameterization (did not find a valid router).");
        debugBuild.DEBUG_BUILD && utils.logger.debug("Routing instrumentation is currently only supported in Express 4.");
        return;
      }
      const routerProto = Object.getPrototypeOf(router);
      const originalProcessParams = routerProto.process_params;
      routerProto.process_params = function process_params(layer, called, req, res, done) {
        if (!req._reconstructedRoute) {
          req._reconstructedRoute = "";
        }
        const { layerRoutePath, isRegex, isArray, numExtraSegments } = getLayerRoutePathInfo(layer);
        if (layerRoutePath || isRegex || isArray) {
          req._hasParameters = true;
        }
        let partialRoute;
        if (layerRoutePath) {
          partialRoute = layerRoutePath;
        } else {
          partialRoute = preventDuplicateSegments(req.originalUrl, req._reconstructedRoute, layer.path) || "";
        }
        const finalPartialRoute = partialRoute.split("/").filter((segment) => segment.length > 0 && (isRegex || isArray || !segment.includes("*"))).join("/");
        if (finalPartialRoute && finalPartialRoute.length > 0) {
          req._reconstructedRoute += `/${finalPartialRoute}${isRegex ? "/" : ""}`;
        }
        const urlLength = utils.getNumberOfUrlSegments(utils.stripUrlQueryAndFragment(req.originalUrl || "")) + numExtraSegments;
        const routeLength = utils.getNumberOfUrlSegments(req._reconstructedRoute);
        if (urlLength === routeLength) {
          if (!req._hasParameters) {
            if (req._reconstructedRoute !== req.originalUrl) {
              req._reconstructedRoute = req.originalUrl ? utils.stripUrlQueryAndFragment(req.originalUrl) : req.originalUrl;
            }
          }
          const transaction = res.__sentry_transaction;
          const attributes = transaction && core.spanToJSON(transaction).data || {};
          if (transaction && attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] !== "custom") {
            const finalRoute = req._reconstructedRoute || "/";
            const [name, source] = utils.extractPathForTransaction(req, { path: true, method: true, customRoute: finalRoute });
            transaction.updateName(name);
            transaction.setAttribute(core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source);
          }
        }
        return originalProcessParams.call(this, layer, called, req, res, done);
      };
    }
    var extractOriginalRoute = (path2, regexp, keys) => {
      if (!path2 || !regexp || !keys || Object.keys(keys).length === 0 || _optionalChain([keys, "access", (_10) => _10[0], "optionalAccess", (_11) => _11.offset]) === void 0 || _optionalChain([keys, "access", (_12) => _12[0], "optionalAccess", (_13) => _13.offset]) === null) {
        return void 0;
      }
      const orderedKeys = keys.sort((a3, b) => a3.offset - b.offset);
      const pathRegex = new RegExp(regexp, `${regexp.flags}d`);
      const execResult = pathRegex.exec(path2);
      if (!execResult || !execResult.indices) {
        return void 0;
      }
      const [, ...paramIndices] = execResult.indices;
      if (paramIndices.length !== orderedKeys.length) {
        return void 0;
      }
      let resultPath = path2;
      let indexShift = 0;
      paramIndices.forEach((item, index) => {
        if (item) {
          const [startOffset, endOffset] = item;
          const substr1 = resultPath.substring(0, startOffset - indexShift);
          const replacement = `:${orderedKeys[index].name}`;
          const substr2 = resultPath.substring(endOffset - indexShift);
          resultPath = substr1 + replacement + substr2;
          indexShift = indexShift + (endOffset - startOffset - replacement.length);
        }
      });
      return resultPath;
    };
    function getLayerRoutePathInfo(layer) {
      let lrp = _optionalChain([layer, "access", (_14) => _14.route, "optionalAccess", (_15) => _15.path]);
      const isRegex = utils.isRegExp(lrp);
      const isArray = Array.isArray(lrp);
      if (!lrp) {
        const [major] = utils.GLOBAL_OBJ.process.versions.node.split(".").map(Number);
        if (major >= 16) {
          lrp = extractOriginalRoute(layer.path, layer.regexp, layer.keys);
        }
      }
      if (!lrp) {
        return { isRegex, isArray, numExtraSegments: 0 };
      }
      const numExtraSegments = isArray ? Math.max(getNumberOfArrayUrlSegments(lrp) - utils.getNumberOfUrlSegments(layer.path || ""), 0) : 0;
      const layerRoutePath = getLayerRoutePathString(isArray, lrp);
      return { layerRoutePath, isRegex, isArray, numExtraSegments };
    }
    function getNumberOfArrayUrlSegments(routesArray) {
      return routesArray.reduce((accNumSegments, currentRoute) => {
        return accNumSegments + utils.getNumberOfUrlSegments(currentRoute.toString());
      }, 0);
    }
    function getLayerRoutePathString(isArray, lrp) {
      if (isArray) {
        return lrp.map((r3) => r3.toString()).join(",");
      }
      return lrp && lrp.toString();
    }
    function preventDuplicateSegments(originalUrl, reconstructedRoute, layerPath) {
      const normalizeURL = utils.stripUrlQueryAndFragment(originalUrl || "");
      const originalUrlSplit = _optionalChain([normalizeURL, "optionalAccess", (_16) => _16.split, "call", (_17) => _17("/"), "access", (_18) => _18.filter, "call", (_19) => _19((v3) => !!v3)]);
      let tempCounter = 0;
      const currentOffset = _optionalChain([reconstructedRoute, "optionalAccess", (_20) => _20.split, "call", (_21) => _21("/"), "access", (_22) => _22.filter, "call", (_23) => _23((v3) => !!v3), "access", (_24) => _24.length]) || 0;
      const result = _optionalChain([
        layerPath,
        "optionalAccess",
        (_25) => _25.split,
        "call",
        (_26) => _26("/"),
        "access",
        (_27) => _27.filter,
        "call",
        (_28) => _28((segment) => {
          if (_optionalChain([originalUrlSplit, "optionalAccess", (_29) => _29[currentOffset + tempCounter]]) === segment) {
            tempCounter += 1;
            return true;
          }
          return false;
        }),
        "access",
        (_30) => _30.join,
        "call",
        (_31) => _31("/")
      ]);
      return result;
    }
    exports.Express = Express;
    exports.extractOriginalRoute = extractOriginalRoute;
    exports.preventDuplicateSegments = preventDuplicateSegments;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/node/integrations/postgres.js
var require_postgres = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/node/integrations/postgres.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build3();
    var nodeUtils = require_node_utils();
    var Postgres = class _Postgres {
      /**
       * @inheritDoc
       */
      static __initStatic() {
        this.id = "Postgres";
      }
      /**
       * @inheritDoc
       */
      constructor(options = {}) {
        this.name = _Postgres.id;
        this._usePgNative = !!options.usePgNative;
        this._module = options.module;
      }
      /** @inheritdoc */
      loadDependency() {
        return this._module = this._module || utils.loadModule("pg");
      }
      /**
       * @inheritDoc
       */
      // eslint-disable-next-line deprecation/deprecation
      setupOnce(_3, getCurrentHub) {
        if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) {
          debugBuild.DEBUG_BUILD && utils.logger.log("Postgres Integration is skipped because of instrumenter configuration.");
          return;
        }
        const pkg = this.loadDependency();
        if (!pkg) {
          debugBuild.DEBUG_BUILD && utils.logger.error("Postgres Integration was unable to require `pg` package.");
          return;
        }
        const Client = this._usePgNative ? _optionalChain([pkg, "access", (_22) => _22.native, "optionalAccess", (_32) => _32.Client]) : pkg.Client;
        if (!Client) {
          debugBuild.DEBUG_BUILD && utils.logger.error("Postgres Integration was unable to access 'pg-native' bindings.");
          return;
        }
        utils.fill(Client.prototype, "query", function(orig) {
          return function(config, values, callback) {
            const scope = getCurrentHub().getScope();
            const parentSpan = scope.getSpan();
            const data = {
              "db.system": "postgresql"
            };
            try {
              if (this.database) {
                data["db.name"] = this.database;
              }
              if (this.host) {
                data["server.address"] = this.host;
              }
              if (this.port) {
                data["server.port"] = this.port;
              }
              if (this.user) {
                data["db.user"] = this.user;
              }
            } catch (e2) {
            }
            const span = _optionalChain([parentSpan, "optionalAccess", (_4) => _4.startChild, "call", (_5) => _5({
              description: typeof config === "string" ? config : config.text,
              op: "db",
              origin: "auto.db.postgres",
              data
            })]);
            if (typeof callback === "function") {
              return orig.call(this, config, values, function(err, result) {
                _optionalChain([span, "optionalAccess", (_6) => _6.end, "call", (_7) => _7()]);
                callback(err, result);
              });
            }
            if (typeof values === "function") {
              return orig.call(this, config, function(err, result) {
                _optionalChain([span, "optionalAccess", (_8) => _8.end, "call", (_9) => _9()]);
                values(err, result);
              });
            }
            const rv = typeof values !== "undefined" ? orig.call(this, config, values) : orig.call(this, config);
            if (utils.isThenable(rv)) {
              return rv.then((res) => {
                _optionalChain([span, "optionalAccess", (_10) => _10.end, "call", (_11) => _11()]);
                return res;
              });
            }
            _optionalChain([span, "optionalAccess", (_12) => _12.end, "call", (_13) => _13()]);
            return rv;
          };
        });
      }
    };
    Postgres.__initStatic();
    exports.Postgres = Postgres;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/node/integrations/mysql.js
var require_mysql = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/node/integrations/mysql.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build3();
    var nodeUtils = require_node_utils();
    var Mysql = class _Mysql {
      /**
       * @inheritDoc
       */
      static __initStatic() {
        this.id = "Mysql";
      }
      /**
       * @inheritDoc
       */
      constructor() {
        this.name = _Mysql.id;
      }
      /** @inheritdoc */
      loadDependency() {
        return this._module = this._module || utils.loadModule("mysql/lib/Connection.js");
      }
      /**
       * @inheritDoc
       */
      // eslint-disable-next-line deprecation/deprecation
      setupOnce(_3, getCurrentHub) {
        if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) {
          debugBuild.DEBUG_BUILD && utils.logger.log("Mysql Integration is skipped because of instrumenter configuration.");
          return;
        }
        const pkg = this.loadDependency();
        if (!pkg) {
          debugBuild.DEBUG_BUILD && utils.logger.error("Mysql Integration was unable to require `mysql` package.");
          return;
        }
        let mySqlConfig = void 0;
        try {
          pkg.prototype.connect = new Proxy(pkg.prototype.connect, {
            apply(wrappingTarget, thisArg, args) {
              if (!mySqlConfig) {
                mySqlConfig = thisArg.config;
              }
              return wrappingTarget.apply(thisArg, args);
            }
          });
        } catch (e2) {
          debugBuild.DEBUG_BUILD && utils.logger.error("Mysql Integration was unable to instrument `mysql` config.");
        }
        function spanDataFromConfig() {
          if (!mySqlConfig) {
            return {};
          }
          return {
            "server.address": mySqlConfig.host,
            "server.port": mySqlConfig.port,
            "db.user": mySqlConfig.user
          };
        }
        function finishSpan(span) {
          if (!span) {
            return;
          }
          const data = spanDataFromConfig();
          Object.keys(data).forEach((key) => {
            span.setAttribute(key, data[key]);
          });
          span.end();
        }
        utils.fill(pkg, "createQuery", function(orig) {
          return function(options, values, callback) {
            const scope = getCurrentHub().getScope();
            const parentSpan = scope.getSpan();
            const span = _optionalChain([parentSpan, "optionalAccess", (_22) => _22.startChild, "call", (_32) => _32({
              description: typeof options === "string" ? options : options.sql,
              op: "db",
              origin: "auto.db.mysql",
              data: {
                "db.system": "mysql"
              }
            })]);
            if (typeof callback === "function") {
              return orig.call(this, options, values, function(err, result, fields) {
                finishSpan(span);
                callback(err, result, fields);
              });
            }
            if (typeof values === "function") {
              return orig.call(this, options, function(err, result, fields) {
                finishSpan(span);
                values(err, result, fields);
              });
            }
            const query = orig.call(this, options, values);
            query.on("end", () => {
              finishSpan(span);
            });
            return query;
          };
        });
      }
    };
    Mysql.__initStatic();
    exports.Mysql = Mysql;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/node/integrations/mongo.js
var require_mongo = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/node/integrations/mongo.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build3();
    var nodeUtils = require_node_utils();
    var OPERATIONS = [
      "aggregate",
      // aggregate(pipeline, options, callback)
      "bulkWrite",
      // bulkWrite(operations, options, callback)
      "countDocuments",
      // countDocuments(query, options, callback)
      "createIndex",
      // createIndex(fieldOrSpec, options, callback)
      "createIndexes",
      // createIndexes(indexSpecs, options, callback)
      "deleteMany",
      // deleteMany(filter, options, callback)
      "deleteOne",
      // deleteOne(filter, options, callback)
      "distinct",
      // distinct(key, query, options, callback)
      "drop",
      // drop(options, callback)
      "dropIndex",
      // dropIndex(indexName, options, callback)
      "dropIndexes",
      // dropIndexes(options, callback)
      "estimatedDocumentCount",
      // estimatedDocumentCount(options, callback)
      "find",
      // find(query, options, callback)
      "findOne",
      // findOne(query, options, callback)
      "findOneAndDelete",
      // findOneAndDelete(filter, options, callback)
      "findOneAndReplace",
      // findOneAndReplace(filter, replacement, options, callback)
      "findOneAndUpdate",
      // findOneAndUpdate(filter, update, options, callback)
      "indexes",
      // indexes(options, callback)
      "indexExists",
      // indexExists(indexes, options, callback)
      "indexInformation",
      // indexInformation(options, callback)
      "initializeOrderedBulkOp",
      // initializeOrderedBulkOp(options, callback)
      "insertMany",
      // insertMany(docs, options, callback)
      "insertOne",
      // insertOne(doc, options, callback)
      "isCapped",
      // isCapped(options, callback)
      "mapReduce",
      // mapReduce(map, reduce, options, callback)
      "options",
      // options(options, callback)
      "parallelCollectionScan",
      // parallelCollectionScan(options, callback)
      "rename",
      // rename(newName, options, callback)
      "replaceOne",
      // replaceOne(filter, doc, options, callback)
      "stats",
      // stats(options, callback)
      "updateMany",
      // updateMany(filter, update, options, callback)
      "updateOne"
      // updateOne(filter, update, options, callback)
    ];
    var OPERATION_SIGNATURES = {
      // aggregate intentionally not included because `pipeline` arguments are too complex to serialize well
      // see https://github.com/getsentry/sentry-javascript/pull/3102
      bulkWrite: ["operations"],
      countDocuments: ["query"],
      createIndex: ["fieldOrSpec"],
      createIndexes: ["indexSpecs"],
      deleteMany: ["filter"],
      deleteOne: ["filter"],
      distinct: ["key", "query"],
      dropIndex: ["indexName"],
      find: ["query"],
      findOne: ["query"],
      findOneAndDelete: ["filter"],
      findOneAndReplace: ["filter", "replacement"],
      findOneAndUpdate: ["filter", "update"],
      indexExists: ["indexes"],
      insertMany: ["docs"],
      insertOne: ["doc"],
      mapReduce: ["map", "reduce"],
      rename: ["newName"],
      replaceOne: ["filter", "doc"],
      updateMany: ["filter", "update"],
      updateOne: ["filter", "update"]
    };
    function isCursor(maybeCursor) {
      return maybeCursor && typeof maybeCursor === "object" && maybeCursor.once && typeof maybeCursor.once === "function";
    }
    var Mongo = class _Mongo {
      /**
       * @inheritDoc
       */
      static __initStatic() {
        this.id = "Mongo";
      }
      /**
       * @inheritDoc
       */
      /**
       * @inheritDoc
       */
      constructor(options = {}) {
        this.name = _Mongo.id;
        this._operations = Array.isArray(options.operations) ? options.operations : OPERATIONS;
        this._describeOperations = "describeOperations" in options ? options.describeOperations : true;
        this._useMongoose = !!options.useMongoose;
      }
      /** @inheritdoc */
      loadDependency() {
        const moduleName = this._useMongoose ? "mongoose" : "mongodb";
        return this._module = this._module || utils.loadModule(moduleName);
      }
      /**
       * @inheritDoc
       */
      // eslint-disable-next-line deprecation/deprecation
      setupOnce(_3, getCurrentHub) {
        if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) {
          debugBuild.DEBUG_BUILD && utils.logger.log("Mongo Integration is skipped because of instrumenter configuration.");
          return;
        }
        const pkg = this.loadDependency();
        if (!pkg) {
          const moduleName = this._useMongoose ? "mongoose" : "mongodb";
          debugBuild.DEBUG_BUILD && utils.logger.error(`Mongo Integration was unable to require \`${moduleName}\` package.`);
          return;
        }
        this._instrumentOperations(pkg.Collection, this._operations, getCurrentHub);
      }
      /**
       * Patches original collection methods
       */
      // eslint-disable-next-line deprecation/deprecation
      _instrumentOperations(collection, operations, getCurrentHub) {
        operations.forEach((operation) => this._patchOperation(collection, operation, getCurrentHub));
      }
      /**
       * Patches original collection to utilize our tracing functionality
       */
      // eslint-disable-next-line deprecation/deprecation
      _patchOperation(collection, operation, getCurrentHub) {
        if (!(operation in collection.prototype))
          return;
        const getSpanContext = this._getSpanContextFromOperationArguments.bind(this);
        utils.fill(collection.prototype, operation, function(orig) {
          return function(...args) {
            const lastArg = args[args.length - 1];
            const hub = getCurrentHub();
            const scope = hub.getScope();
            const client = hub.getClient();
            const parentSpan = scope.getSpan();
            const sendDefaultPii = _optionalChain([client, "optionalAccess", (_22) => _22.getOptions, "call", (_3) => _3(), "access", (_4) => _4.sendDefaultPii]);
            if (typeof lastArg !== "function" || operation === "mapReduce" && args.length === 2) {
              const span2 = _optionalChain([parentSpan, "optionalAccess", (_5) => _5.startChild, "call", (_6) => _6(getSpanContext(this, operation, args, sendDefaultPii))]);
              const maybePromiseOrCursor = orig.call(this, ...args);
              if (utils.isThenable(maybePromiseOrCursor)) {
                return maybePromiseOrCursor.then((res) => {
                  _optionalChain([span2, "optionalAccess", (_7) => _7.end, "call", (_8) => _8()]);
                  return res;
                });
              } else if (isCursor(maybePromiseOrCursor)) {
                const cursor = maybePromiseOrCursor;
                try {
                  cursor.once("close", () => {
                    _optionalChain([span2, "optionalAccess", (_9) => _9.end, "call", (_10) => _10()]);
                  });
                } catch (e2) {
                  _optionalChain([span2, "optionalAccess", (_11) => _11.end, "call", (_12) => _12()]);
                }
                return cursor;
              } else {
                _optionalChain([span2, "optionalAccess", (_13) => _13.end, "call", (_14) => _14()]);
                return maybePromiseOrCursor;
              }
            }
            const span = _optionalChain([parentSpan, "optionalAccess", (_15) => _15.startChild, "call", (_16) => _16(getSpanContext(this, operation, args.slice(0, -1)))]);
            return orig.call(this, ...args.slice(0, -1), function(err, result) {
              _optionalChain([span, "optionalAccess", (_17) => _17.end, "call", (_18) => _18()]);
              lastArg(err, result);
            });
          };
        });
      }
      /**
       * Form a SpanContext based on the user input to a given operation.
       */
      _getSpanContextFromOperationArguments(collection, operation, args, sendDefaultPii = false) {
        const data = {
          "db.system": "mongodb",
          "db.name": collection.dbName,
          "db.operation": operation,
          "db.mongodb.collection": collection.collectionName
        };
        const spanContext = {
          op: "db",
          // TODO v8: Use `${collection.collectionName}.${operation}`
          origin: "auto.db.mongo",
          description: operation,
          data
        };
        const signature = OPERATION_SIGNATURES[operation];
        const shouldDescribe = Array.isArray(this._describeOperations) ? this._describeOperations.includes(operation) : this._describeOperations;
        if (!signature || !shouldDescribe || !sendDefaultPii) {
          return spanContext;
        }
        try {
          if (operation === "mapReduce") {
            const [map, reduce] = args;
            data[signature[0]] = typeof map === "string" ? map : map.name || "<anonymous>";
            data[signature[1]] = typeof reduce === "string" ? reduce : reduce.name || "<anonymous>";
          } else {
            for (let i2 = 0; i2 < signature.length; i2++) {
              data[`db.mongodb.${signature[i2]}`] = JSON.stringify(args[i2]);
            }
          }
        } catch (_oO) {
        }
        return spanContext;
      }
    };
    Mongo.__initStatic();
    exports.Mongo = Mongo;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/node/integrations/prisma.js
var require_prisma = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/node/integrations/prisma.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var debugBuild = require_debug_build3();
    var nodeUtils = require_node_utils();
    function isValidPrismaClient(possibleClient) {
      return !!possibleClient && !!possibleClient["$use"];
    }
    var Prisma = class _Prisma {
      /**
       * @inheritDoc
       */
      static __initStatic() {
        this.id = "Prisma";
      }
      /**
       * @inheritDoc
       */
      /**
       * @inheritDoc
       */
      constructor(options = {}) {
        this.name = _Prisma.id;
        if (isValidPrismaClient(options.client) && !options.client._sentryInstrumented) {
          utils.addNonEnumerableProperty(options.client, "_sentryInstrumented", true);
          const clientData = {};
          try {
            const engineConfig = options.client._engineConfig;
            if (engineConfig) {
              const { activeProvider, clientVersion } = engineConfig;
              if (activeProvider) {
                clientData["db.system"] = activeProvider;
              }
              if (clientVersion) {
                clientData["db.prisma.version"] = clientVersion;
              }
            }
          } catch (e2) {
          }
          options.client.$use((params, next) => {
            if (nodeUtils.shouldDisableAutoInstrumentation(core.getCurrentHub)) {
              return next(params);
            }
            const action = params.action;
            const model = params.model;
            return core.startSpan(
              {
                name: model ? `${model} ${action}` : action,
                onlyIfParent: true,
                op: "db.prisma",
                attributes: {
                  [core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.db.prisma"
                },
                data: { ...clientData, "db.operation": action }
              },
              () => next(params)
            );
          });
        } else {
          debugBuild.DEBUG_BUILD && utils.logger.warn("Unsupported Prisma client provided to PrismaIntegration. Provided client:", options.client);
        }
      }
      /**
       * @inheritDoc
       */
      setupOnce() {
      }
    };
    Prisma.__initStatic();
    exports.Prisma = Prisma;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/node/integrations/graphql.js
var require_graphql = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/node/integrations/graphql.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build3();
    var nodeUtils = require_node_utils();
    var GraphQL = class _GraphQL {
      /**
       * @inheritDoc
       */
      static __initStatic() {
        this.id = "GraphQL";
      }
      /**
       * @inheritDoc
       */
      constructor() {
        this.name = _GraphQL.id;
      }
      /** @inheritdoc */
      loadDependency() {
        return this._module = this._module || utils.loadModule("graphql/execution/execute.js");
      }
      /**
       * @inheritDoc
       */
      // eslint-disable-next-line deprecation/deprecation
      setupOnce(_3, getCurrentHub) {
        if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) {
          debugBuild.DEBUG_BUILD && utils.logger.log("GraphQL Integration is skipped because of instrumenter configuration.");
          return;
        }
        const pkg = this.loadDependency();
        if (!pkg) {
          debugBuild.DEBUG_BUILD && utils.logger.error("GraphQL Integration was unable to require graphql/execution package.");
          return;
        }
        utils.fill(pkg, "execute", function(orig) {
          return function(...args) {
            const scope = getCurrentHub().getScope();
            const parentSpan = scope.getSpan();
            const span = _optionalChain([parentSpan, "optionalAccess", (_22) => _22.startChild, "call", (_32) => _32({
              description: "execute",
              op: "graphql.execute",
              origin: "auto.graphql.graphql"
            })]);
            _optionalChain([scope, "optionalAccess", (_4) => _4.setSpan, "call", (_5) => _5(span)]);
            const rv = orig.call(this, ...args);
            if (utils.isThenable(rv)) {
              return rv.then((res) => {
                _optionalChain([span, "optionalAccess", (_6) => _6.end, "call", (_7) => _7()]);
                _optionalChain([scope, "optionalAccess", (_8) => _8.setSpan, "call", (_9) => _9(parentSpan)]);
                return res;
              });
            }
            _optionalChain([span, "optionalAccess", (_10) => _10.end, "call", (_11) => _11()]);
            _optionalChain([scope, "optionalAccess", (_12) => _12.setSpan, "call", (_13) => _13(parentSpan)]);
            return rv;
          };
        });
      }
    };
    GraphQL.__initStatic();
    exports.GraphQL = GraphQL;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/node/integrations/apollo.js
var require_apollo = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/node/integrations/apollo.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build3();
    var nodeUtils = require_node_utils();
    var Apollo = class _Apollo {
      /**
       * @inheritDoc
       */
      static __initStatic() {
        this.id = "Apollo";
      }
      /**
       * @inheritDoc
       */
      /**
       * @inheritDoc
       */
      constructor(options = {
        useNestjs: false
      }) {
        this.name = _Apollo.id;
        this._useNest = !!options.useNestjs;
      }
      /** @inheritdoc */
      loadDependency() {
        if (this._useNest) {
          this._module = this._module || utils.loadModule("@nestjs/graphql");
        } else {
          this._module = this._module || utils.loadModule("apollo-server-core");
        }
        return this._module;
      }
      /**
       * @inheritDoc
       */
      // eslint-disable-next-line deprecation/deprecation
      setupOnce(_3, getCurrentHub) {
        if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) {
          debugBuild.DEBUG_BUILD && utils.logger.log("Apollo Integration is skipped because of instrumenter configuration.");
          return;
        }
        if (this._useNest) {
          const pkg = this.loadDependency();
          if (!pkg) {
            debugBuild.DEBUG_BUILD && utils.logger.error("Apollo-NestJS Integration was unable to require @nestjs/graphql package.");
            return;
          }
          utils.fill(
            pkg.GraphQLFactory.prototype,
            "mergeWithSchema",
            function(orig) {
              return function(...args) {
                utils.fill(this.resolversExplorerService, "explore", function(orig2) {
                  return function() {
                    const resolvers = utils.arrayify(orig2.call(this));
                    const instrumentedResolvers = instrumentResolvers(resolvers, getCurrentHub);
                    return instrumentedResolvers;
                  };
                });
                return orig.call(this, ...args);
              };
            }
          );
        } else {
          const pkg = this.loadDependency();
          if (!pkg) {
            debugBuild.DEBUG_BUILD && utils.logger.error("Apollo Integration was unable to require apollo-server-core package.");
            return;
          }
          utils.fill(pkg.ApolloServerBase.prototype, "constructSchema", function(orig) {
            return function() {
              if (!this.config.resolvers) {
                if (debugBuild.DEBUG_BUILD) {
                  if (this.config.schema) {
                    utils.logger.warn(
                      "Apollo integration is not able to trace `ApolloServer` instances constructed via `schema` property.If you are using NestJS with Apollo, please use `Sentry.Integrations.Apollo({ useNestjs: true })` instead."
                    );
                    utils.logger.warn();
                  } else if (this.config.modules) {
                    utils.logger.warn(
                      "Apollo integration is not able to trace `ApolloServer` instances constructed via `modules` property."
                    );
                  }
                  utils.logger.error("Skipping tracing as no resolvers found on the `ApolloServer` instance.");
                }
                return orig.call(this);
              }
              const resolvers = utils.arrayify(this.config.resolvers);
              this.config.resolvers = instrumentResolvers(resolvers, getCurrentHub);
              return orig.call(this);
            };
          });
        }
      }
    };
    Apollo.__initStatic();
    function instrumentResolvers(resolvers, getCurrentHub) {
      return resolvers.map((model) => {
        Object.keys(model).forEach((resolverGroupName) => {
          Object.keys(model[resolverGroupName]).forEach((resolverName) => {
            if (typeof model[resolverGroupName][resolverName] !== "function") {
              return;
            }
            wrapResolver(model, resolverGroupName, resolverName, getCurrentHub);
          });
        });
        return model;
      });
    }
    function wrapResolver(model, resolverGroupName, resolverName, getCurrentHub) {
      utils.fill(model[resolverGroupName], resolverName, function(orig) {
        return function(...args) {
          const scope = getCurrentHub().getScope();
          const parentSpan = scope.getSpan();
          const span = _optionalChain([parentSpan, "optionalAccess", (_22) => _22.startChild, "call", (_3) => _3({
            description: `${resolverGroupName}.${resolverName}`,
            op: "graphql.resolve",
            origin: "auto.graphql.apollo"
          })]);
          const rv = orig.call(this, ...args);
          if (utils.isThenable(rv)) {
            return rv.then((res) => {
              _optionalChain([span, "optionalAccess", (_4) => _4.end, "call", (_5) => _5()]);
              return res;
            });
          }
          _optionalChain([span, "optionalAccess", (_6) => _6.end, "call", (_7) => _7()]);
          return rv;
        };
      });
    }
    exports.Apollo = Apollo;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/node/integrations/lazy.js
var require_lazy = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/node/integrations/lazy.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var lazyLoadedNodePerformanceMonitoringIntegrations = [
      () => {
        const integration = utils.dynamicRequire(module, "./apollo");
        return new integration.Apollo();
      },
      () => {
        const integration = utils.dynamicRequire(module, "./apollo");
        return new integration.Apollo({ useNestjs: true });
      },
      () => {
        const integration = utils.dynamicRequire(module, "./graphql");
        return new integration.GraphQL();
      },
      () => {
        const integration = utils.dynamicRequire(module, "./mongo");
        return new integration.Mongo();
      },
      () => {
        const integration = utils.dynamicRequire(module, "./mongo");
        return new integration.Mongo({ mongoose: true });
      },
      () => {
        const integration = utils.dynamicRequire(module, "./mysql");
        return new integration.Mysql();
      },
      () => {
        const integration = utils.dynamicRequire(module, "./postgres");
        return new integration.Postgres();
      }
    ];
    exports.lazyLoadedNodePerformanceMonitoringIntegrations = lazyLoadedNodePerformanceMonitoringIntegrations;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/types.js
var require_types = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/types.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var WINDOW = utils.GLOBAL_OBJ;
    exports.WINDOW = WINDOW;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/backgroundtab.js
var require_backgroundtab = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/backgroundtab.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var debugBuild = require_debug_build3();
    var types = require_types();
    function registerBackgroundTabDetection() {
      if (types.WINDOW.document) {
        types.WINDOW.document.addEventListener("visibilitychange", () => {
          const activeTransaction = core.getActiveTransaction();
          if (types.WINDOW.document.hidden && activeTransaction) {
            const statusType = "cancelled";
            const { op, status } = core.spanToJSON(activeTransaction);
            debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${op}`);
            if (!status) {
              activeTransaction.setStatus(statusType);
            }
            activeTransaction.setTag("visibilitychange", "document.hidden");
            activeTransaction.end();
          }
        });
      } else {
        debugBuild.DEBUG_BUILD && utils.logger.warn("[Tracing] Could not set up background tab detection due to lack of global document");
      }
    }
    exports.registerBackgroundTabDetection = registerBackgroundTabDetection;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/lib/bindReporter.js
var require_bindReporter = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/lib/bindReporter.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var bindReporter = (callback, metric, reportAllChanges) => {
      let prevValue;
      let delta;
      return (forceReport) => {
        if (metric.value >= 0) {
          if (forceReport || reportAllChanges) {
            delta = metric.value - (prevValue || 0);
            if (delta || prevValue === void 0) {
              prevValue = metric.value;
              metric.delta = delta;
              callback(metric);
            }
          }
        }
      };
    };
    exports.bindReporter = bindReporter;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/lib/generateUniqueID.js
var require_generateUniqueID = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/lib/generateUniqueID.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var generateUniqueID = () => {
      return `v3-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;
    };
    exports.generateUniqueID = generateUniqueID;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/lib/getNavigationEntry.js
var require_getNavigationEntry = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/lib/getNavigationEntry.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var types = require_types();
    var getNavigationEntryFromPerformanceTiming = () => {
      const timing = types.WINDOW.performance.timing;
      const type = types.WINDOW.performance.navigation.type;
      const navigationEntry = {
        entryType: "navigation",
        startTime: 0,
        type: type == 2 ? "back_forward" : type === 1 ? "reload" : "navigate"
      };
      for (const key in timing) {
        if (key !== "navigationStart" && key !== "toJSON") {
          navigationEntry[key] = Math.max(timing[key] - timing.navigationStart, 0);
        }
      }
      return navigationEntry;
    };
    var getNavigationEntry = () => {
      if (types.WINDOW.__WEB_VITALS_POLYFILL__) {
        return types.WINDOW.performance && (performance.getEntriesByType && performance.getEntriesByType("navigation")[0] || getNavigationEntryFromPerformanceTiming());
      } else {
        return types.WINDOW.performance && performance.getEntriesByType && performance.getEntriesByType("navigation")[0];
      }
    };
    exports.getNavigationEntry = getNavigationEntry;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/lib/getActivationStart.js
var require_getActivationStart = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/lib/getActivationStart.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var getNavigationEntry = require_getNavigationEntry();
    var getActivationStart = () => {
      const navEntry = getNavigationEntry.getNavigationEntry();
      return navEntry && navEntry.activationStart || 0;
    };
    exports.getActivationStart = getActivationStart;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/lib/initMetric.js
var require_initMetric = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/lib/initMetric.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var types = require_types();
    var generateUniqueID = require_generateUniqueID();
    var getActivationStart = require_getActivationStart();
    var getNavigationEntry = require_getNavigationEntry();
    var initMetric = (name, value) => {
      const navEntry = getNavigationEntry.getNavigationEntry();
      let navigationType = "navigate";
      if (navEntry) {
        if (types.WINDOW.document && types.WINDOW.document.prerendering || getActivationStart.getActivationStart() > 0) {
          navigationType = "prerender";
        } else {
          navigationType = navEntry.type.replace(/_/g, "-");
        }
      }
      return {
        name,
        value: typeof value === "undefined" ? -1 : value,
        rating: "good",
        // Will be updated if the value changes.
        delta: 0,
        entries: [],
        id: generateUniqueID.generateUniqueID(),
        navigationType
      };
    };
    exports.initMetric = initMetric;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/lib/observe.js
var require_observe = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/lib/observe.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var observe = (type, callback, opts) => {
      try {
        if (PerformanceObserver.supportedEntryTypes.includes(type)) {
          const po = new PerformanceObserver((list) => {
            callback(list.getEntries());
          });
          po.observe(
            Object.assign(
              {
                type,
                buffered: true
              },
              opts || {}
            )
          );
          return po;
        }
      } catch (e2) {
      }
      return;
    };
    exports.observe = observe;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/lib/onHidden.js
var require_onHidden = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/lib/onHidden.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var types = require_types();
    var onHidden = (cb, once) => {
      const onHiddenOrPageHide = (event) => {
        if (event.type === "pagehide" || types.WINDOW.document.visibilityState === "hidden") {
          cb(event);
          if (once) {
            removeEventListener("visibilitychange", onHiddenOrPageHide, true);
            removeEventListener("pagehide", onHiddenOrPageHide, true);
          }
        }
      };
      if (types.WINDOW.document) {
        addEventListener("visibilitychange", onHiddenOrPageHide, true);
        addEventListener("pagehide", onHiddenOrPageHide, true);
      }
    };
    exports.onHidden = onHidden;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/getCLS.js
var require_getCLS = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/getCLS.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var bindReporter = require_bindReporter();
    var initMetric = require_initMetric();
    var observe = require_observe();
    var onHidden = require_onHidden();
    var onCLS = (onReport, options = {}) => {
      const metric = initMetric.initMetric("CLS", 0);
      let report;
      let sessionValue = 0;
      let sessionEntries = [];
      const handleEntries = (entries) => {
        entries.forEach((entry) => {
          if (!entry.hadRecentInput) {
            const firstSessionEntry = sessionEntries[0];
            const lastSessionEntry = sessionEntries[sessionEntries.length - 1];
            if (sessionValue && sessionEntries.length !== 0 && entry.startTime - lastSessionEntry.startTime < 1e3 && entry.startTime - firstSessionEntry.startTime < 5e3) {
              sessionValue += entry.value;
              sessionEntries.push(entry);
            } else {
              sessionValue = entry.value;
              sessionEntries = [entry];
            }
            if (sessionValue > metric.value) {
              metric.value = sessionValue;
              metric.entries = sessionEntries;
              if (report) {
                report();
              }
            }
          }
        });
      };
      const po = observe.observe("layout-shift", handleEntries);
      if (po) {
        report = bindReporter.bindReporter(onReport, metric, options.reportAllChanges);
        const stopListening = () => {
          handleEntries(po.takeRecords());
          report(true);
        };
        onHidden.onHidden(stopListening);
        return stopListening;
      }
      return;
    };
    exports.onCLS = onCLS;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/lib/getVisibilityWatcher.js
var require_getVisibilityWatcher = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/lib/getVisibilityWatcher.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var types = require_types();
    var onHidden = require_onHidden();
    var firstHiddenTime = -1;
    var initHiddenTime = () => {
      if (types.WINDOW.document && types.WINDOW.document.visibilityState) {
        firstHiddenTime = types.WINDOW.document.visibilityState === "hidden" && !types.WINDOW.document.prerendering ? 0 : Infinity;
      }
    };
    var trackChanges = () => {
      onHidden.onHidden(({ timeStamp }) => {
        firstHiddenTime = timeStamp;
      }, true);
    };
    var getVisibilityWatcher = () => {
      if (firstHiddenTime < 0) {
        initHiddenTime();
        trackChanges();
      }
      return {
        get firstHiddenTime() {
          return firstHiddenTime;
        }
      };
    };
    exports.getVisibilityWatcher = getVisibilityWatcher;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/getFID.js
var require_getFID = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/getFID.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var bindReporter = require_bindReporter();
    var getVisibilityWatcher = require_getVisibilityWatcher();
    var initMetric = require_initMetric();
    var observe = require_observe();
    var onHidden = require_onHidden();
    var onFID = (onReport) => {
      const visibilityWatcher = getVisibilityWatcher.getVisibilityWatcher();
      const metric = initMetric.initMetric("FID");
      let report;
      const handleEntry = (entry) => {
        if (entry.startTime < visibilityWatcher.firstHiddenTime) {
          metric.value = entry.processingStart - entry.startTime;
          metric.entries.push(entry);
          report(true);
        }
      };
      const handleEntries = (entries) => {
        entries.forEach(handleEntry);
      };
      const po = observe.observe("first-input", handleEntries);
      report = bindReporter.bindReporter(onReport, metric);
      if (po) {
        onHidden.onHidden(() => {
          handleEntries(po.takeRecords());
          po.disconnect();
        }, true);
      }
    };
    exports.onFID = onFID;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/lib/polyfills/interactionCountPolyfill.js
var require_interactionCountPolyfill = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/lib/polyfills/interactionCountPolyfill.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var observe = require_observe();
    var interactionCountEstimate = 0;
    var minKnownInteractionId = Infinity;
    var maxKnownInteractionId = 0;
    var updateEstimate = (entries) => {
      entries.forEach((e2) => {
        if (e2.interactionId) {
          minKnownInteractionId = Math.min(minKnownInteractionId, e2.interactionId);
          maxKnownInteractionId = Math.max(maxKnownInteractionId, e2.interactionId);
          interactionCountEstimate = maxKnownInteractionId ? (maxKnownInteractionId - minKnownInteractionId) / 7 + 1 : 0;
        }
      });
    };
    var po;
    var getInteractionCount = () => {
      return po ? interactionCountEstimate : performance.interactionCount || 0;
    };
    var initInteractionCountPolyfill = () => {
      if ("interactionCount" in performance || po)
        return;
      po = observe.observe("event", updateEstimate, {
        type: "event",
        buffered: true,
        durationThreshold: 0
      });
    };
    exports.getInteractionCount = getInteractionCount;
    exports.initInteractionCountPolyfill = initInteractionCountPolyfill;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/getINP.js
var require_getINP = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/getINP.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var bindReporter = require_bindReporter();
    var initMetric = require_initMetric();
    var observe = require_observe();
    var onHidden = require_onHidden();
    var interactionCountPolyfill = require_interactionCountPolyfill();
    var getInteractionCountForNavigation = () => {
      return interactionCountPolyfill.getInteractionCount();
    };
    var MAX_INTERACTIONS_TO_CONSIDER = 10;
    var longestInteractionList = [];
    var longestInteractionMap = {};
    var processEntry = (entry) => {
      const minLongestInteraction = longestInteractionList[longestInteractionList.length - 1];
      const existingInteraction = longestInteractionMap[entry.interactionId];
      if (existingInteraction || longestInteractionList.length < MAX_INTERACTIONS_TO_CONSIDER || entry.duration > minLongestInteraction.latency) {
        if (existingInteraction) {
          existingInteraction.entries.push(entry);
          existingInteraction.latency = Math.max(existingInteraction.latency, entry.duration);
        } else {
          const interaction = {
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            id: entry.interactionId,
            latency: entry.duration,
            entries: [entry]
          };
          longestInteractionMap[interaction.id] = interaction;
          longestInteractionList.push(interaction);
        }
        longestInteractionList.sort((a3, b) => b.latency - a3.latency);
        longestInteractionList.splice(MAX_INTERACTIONS_TO_CONSIDER).forEach((i2) => {
          delete longestInteractionMap[i2.id];
        });
      }
    };
    var estimateP98LongestInteraction = () => {
      const candidateInteractionIndex = Math.min(
        longestInteractionList.length - 1,
        Math.floor(getInteractionCountForNavigation() / 50)
      );
      return longestInteractionList[candidateInteractionIndex];
    };
    var onINP = (onReport, opts) => {
      opts = opts || {};
      interactionCountPolyfill.initInteractionCountPolyfill();
      const metric = initMetric.initMetric("INP");
      let report;
      const handleEntries = (entries) => {
        entries.forEach((entry) => {
          if (entry.interactionId) {
            processEntry(entry);
          }
          if (entry.entryType === "first-input") {
            const noMatchingEntry = !longestInteractionList.some((interaction) => {
              return interaction.entries.some((prevEntry) => {
                return entry.duration === prevEntry.duration && entry.startTime === prevEntry.startTime;
              });
            });
            if (noMatchingEntry) {
              processEntry(entry);
            }
          }
        });
        const inp = estimateP98LongestInteraction();
        if (inp && inp.latency !== metric.value) {
          metric.value = inp.latency;
          metric.entries = inp.entries;
          report();
        }
      };
      const po = observe.observe("event", handleEntries, {
        // Event Timing entries have their durations rounded to the nearest 8ms,
        // so a duration of 40ms would be any event that spans 2.5 or more frames
        // at 60Hz. This threshold is chosen to strike a balance between usefulness
        // and performance. Running this callback for any interaction that spans
        // just one or two frames is likely not worth the insight that could be
        // gained.
        durationThreshold: opts.durationThreshold || 40
      });
      report = bindReporter.bindReporter(onReport, metric, opts.reportAllChanges);
      if (po) {
        po.observe({ type: "first-input", buffered: true });
        onHidden.onHidden(() => {
          handleEntries(po.takeRecords());
          if (metric.value < 0 && getInteractionCountForNavigation() > 0) {
            metric.value = 0;
            metric.entries = [];
          }
          report(true);
        });
      }
    };
    exports.onINP = onINP;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/getLCP.js
var require_getLCP = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/getLCP.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var types = require_types();
    var bindReporter = require_bindReporter();
    var getActivationStart = require_getActivationStart();
    var getVisibilityWatcher = require_getVisibilityWatcher();
    var initMetric = require_initMetric();
    var observe = require_observe();
    var onHidden = require_onHidden();
    var reportedMetricIDs = {};
    var onLCP = (onReport) => {
      const visibilityWatcher = getVisibilityWatcher.getVisibilityWatcher();
      const metric = initMetric.initMetric("LCP");
      let report;
      const handleEntries = (entries) => {
        const lastEntry = entries[entries.length - 1];
        if (lastEntry) {
          const value = Math.max(lastEntry.startTime - getActivationStart.getActivationStart(), 0);
          if (value < visibilityWatcher.firstHiddenTime) {
            metric.value = value;
            metric.entries = [lastEntry];
            report();
          }
        }
      };
      const po = observe.observe("largest-contentful-paint", handleEntries);
      if (po) {
        report = bindReporter.bindReporter(onReport, metric);
        const stopListening = () => {
          if (!reportedMetricIDs[metric.id]) {
            handleEntries(po.takeRecords());
            po.disconnect();
            reportedMetricIDs[metric.id] = true;
            report(true);
          }
        };
        ["keydown", "click"].forEach((type) => {
          if (types.WINDOW.document) {
            addEventListener(type, stopListening, { once: true, capture: true });
          }
        });
        onHidden.onHidden(stopListening, true);
        return stopListening;
      }
      return;
    };
    exports.onLCP = onLCP;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/onTTFB.js
var require_onTTFB = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/web-vitals/onTTFB.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var types = require_types();
    var bindReporter = require_bindReporter();
    var getActivationStart = require_getActivationStart();
    var getNavigationEntry = require_getNavigationEntry();
    var initMetric = require_initMetric();
    var whenReady = (callback) => {
      if (!types.WINDOW.document) {
        return;
      }
      if (types.WINDOW.document.prerendering) {
        addEventListener("prerenderingchange", () => whenReady(callback), true);
      } else if (types.WINDOW.document.readyState !== "complete") {
        addEventListener("load", () => whenReady(callback), true);
      } else {
        setTimeout(callback, 0);
      }
    };
    var onTTFB = (onReport, opts) => {
      opts = opts || {};
      const metric = initMetric.initMetric("TTFB");
      const report = bindReporter.bindReporter(onReport, metric, opts.reportAllChanges);
      whenReady(() => {
        const navEntry = getNavigationEntry.getNavigationEntry();
        if (navEntry) {
          metric.value = Math.max(navEntry.responseStart - getActivationStart.getActivationStart(), 0);
          if (metric.value < 0 || metric.value > performance.now())
            return;
          metric.entries = [navEntry];
          report(true);
        }
      });
    };
    exports.onTTFB = onTTFB;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/instrument.js
var require_instrument2 = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/instrument.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build3();
    var getCLS = require_getCLS();
    var getFID = require_getFID();
    var getINP = require_getINP();
    var getLCP = require_getLCP();
    var observe = require_observe();
    var onTTFB = require_onTTFB();
    var handlers = {};
    var instrumented = {};
    var _previousCls;
    var _previousFid;
    var _previousLcp;
    var _previousTtfb;
    var _previousInp;
    function addClsInstrumentationHandler(callback, stopOnCallback = false) {
      return addMetricObserver("cls", callback, instrumentCls, _previousCls, stopOnCallback);
    }
    function addLcpInstrumentationHandler(callback, stopOnCallback = false) {
      return addMetricObserver("lcp", callback, instrumentLcp, _previousLcp, stopOnCallback);
    }
    function addTtfbInstrumentationHandler(callback) {
      return addMetricObserver("ttfb", callback, instrumentTtfb, _previousTtfb);
    }
    function addFidInstrumentationHandler(callback) {
      return addMetricObserver("fid", callback, instrumentFid, _previousFid);
    }
    function addInpInstrumentationHandler(callback) {
      return addMetricObserver("inp", callback, instrumentInp, _previousInp);
    }
    function addPerformanceInstrumentationHandler(type, callback) {
      addHandler(type, callback);
      if (!instrumented[type]) {
        instrumentPerformanceObserver(type);
        instrumented[type] = true;
      }
      return getCleanupCallback(type, callback);
    }
    function triggerHandlers(type, data) {
      const typeHandlers = handlers[type];
      if (!typeHandlers || !typeHandlers.length) {
        return;
      }
      for (const handler of typeHandlers) {
        try {
          handler(data);
        } catch (e2) {
          debugBuild.DEBUG_BUILD && utils.logger.error(
            `Error while triggering instrumentation handler.
Type: ${type}
Name: ${utils.getFunctionName(handler)}
Error:`,
            e2
          );
        }
      }
    }
    function instrumentCls() {
      return getCLS.onCLS(
        (metric) => {
          triggerHandlers("cls", {
            metric
          });
          _previousCls = metric;
        },
        { reportAllChanges: true }
      );
    }
    function instrumentFid() {
      return getFID.onFID((metric) => {
        triggerHandlers("fid", {
          metric
        });
        _previousFid = metric;
      });
    }
    function instrumentLcp() {
      return getLCP.onLCP((metric) => {
        triggerHandlers("lcp", {
          metric
        });
        _previousLcp = metric;
      });
    }
    function instrumentTtfb() {
      return onTTFB.onTTFB((metric) => {
        triggerHandlers("ttfb", {
          metric
        });
        _previousTtfb = metric;
      });
    }
    function instrumentInp() {
      return getINP.onINP((metric) => {
        triggerHandlers("inp", {
          metric
        });
        _previousInp = metric;
      });
    }
    function addMetricObserver(type, callback, instrumentFn, previousValue, stopOnCallback = false) {
      addHandler(type, callback);
      let stopListening;
      if (!instrumented[type]) {
        stopListening = instrumentFn();
        instrumented[type] = true;
      }
      if (previousValue) {
        callback({ metric: previousValue });
      }
      return getCleanupCallback(type, callback, stopOnCallback ? stopListening : void 0);
    }
    function instrumentPerformanceObserver(type) {
      const options = {};
      if (type === "event") {
        options.durationThreshold = 0;
      }
      observe.observe(
        type,
        (entries) => {
          triggerHandlers(type, { entries });
        },
        options
      );
    }
    function addHandler(type, handler) {
      handlers[type] = handlers[type] || [];
      handlers[type].push(handler);
    }
    function getCleanupCallback(type, callback, stopListening) {
      return () => {
        if (stopListening) {
          stopListening();
        }
        const typeHandlers = handlers[type];
        if (!typeHandlers) {
          return;
        }
        const index = typeHandlers.indexOf(callback);
        if (index !== -1) {
          typeHandlers.splice(index, 1);
        }
      };
    }
    exports.addClsInstrumentationHandler = addClsInstrumentationHandler;
    exports.addFidInstrumentationHandler = addFidInstrumentationHandler;
    exports.addInpInstrumentationHandler = addInpInstrumentationHandler;
    exports.addLcpInstrumentationHandler = addLcpInstrumentationHandler;
    exports.addPerformanceInstrumentationHandler = addPerformanceInstrumentationHandler;
    exports.addTtfbInstrumentationHandler = addTtfbInstrumentationHandler;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/metrics/utils.js
var require_utils3 = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/metrics/utils.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    function isMeasurementValue(value) {
      return typeof value === "number" && isFinite(value);
    }
    function _startChild(transaction, { startTimestamp, ...ctx }) {
      if (startTimestamp && transaction.startTimestamp > startTimestamp) {
        transaction.startTimestamp = startTimestamp;
      }
      return transaction.startChild({
        startTimestamp,
        ...ctx
      });
    }
    exports._startChild = _startChild;
    exports.isMeasurementValue = isMeasurementValue;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/metrics/index.js
var require_metrics = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/metrics/index.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var debugBuild = require_debug_build3();
    var instrument = require_instrument2();
    var types = require_types();
    var getVisibilityWatcher = require_getVisibilityWatcher();
    var utils$1 = require_utils3();
    var getNavigationEntry = require_getNavigationEntry();
    var MAX_INT_AS_BYTES = 2147483647;
    function msToSec(time) {
      return time / 1e3;
    }
    function getBrowserPerformanceAPI() {
      return types.WINDOW && types.WINDOW.addEventListener && types.WINDOW.performance;
    }
    var _performanceCursor = 0;
    var _measurements = {};
    var _lcpEntry;
    var _clsEntry;
    function startTrackingWebVitals() {
      const performance2 = getBrowserPerformanceAPI();
      if (performance2 && utils.browserPerformanceTimeOrigin) {
        if (performance2.mark) {
          types.WINDOW.performance.mark("sentry-tracing-init");
        }
        const fidCallback = _trackFID();
        const clsCallback = _trackCLS();
        const lcpCallback = _trackLCP();
        const ttfbCallback = _trackTtfb();
        return () => {
          fidCallback();
          clsCallback();
          lcpCallback();
          ttfbCallback();
        };
      }
      return () => void 0;
    }
    function startTrackingLongTasks() {
      instrument.addPerformanceInstrumentationHandler("longtask", ({ entries }) => {
        for (const entry of entries) {
          const transaction = core.getActiveTransaction();
          if (!transaction) {
            return;
          }
          const startTime = msToSec(utils.browserPerformanceTimeOrigin + entry.startTime);
          const duration = msToSec(entry.duration);
          transaction.startChild({
            description: "Main UI thread blocked",
            op: "ui.long-task",
            origin: "auto.ui.browser.metrics",
            startTimestamp: startTime,
            endTimestamp: startTime + duration
          });
        }
      });
    }
    function startTrackingInteractions() {
      instrument.addPerformanceInstrumentationHandler("event", ({ entries }) => {
        for (const entry of entries) {
          const transaction = core.getActiveTransaction();
          if (!transaction) {
            return;
          }
          if (entry.name === "click") {
            const startTime = msToSec(utils.browserPerformanceTimeOrigin + entry.startTime);
            const duration = msToSec(entry.duration);
            const span = {
              description: utils.htmlTreeAsString(entry.target),
              op: `ui.interaction.${entry.name}`,
              origin: "auto.ui.browser.metrics",
              startTimestamp: startTime,
              endTimestamp: startTime + duration
            };
            const componentName = utils.getComponentName(entry.target);
            if (componentName) {
              span.attributes = { "ui.component_name": componentName };
            }
            transaction.startChild(span);
          }
        }
      });
    }
    function startTrackingINP(interactionIdtoRouteNameMapping, interactionsSampleRate) {
      const performance2 = getBrowserPerformanceAPI();
      if (performance2 && utils.browserPerformanceTimeOrigin) {
        const inpCallback = _trackINP(interactionIdtoRouteNameMapping, interactionsSampleRate);
        return () => {
          inpCallback();
        };
      }
      return () => void 0;
    }
    function _trackCLS() {
      return instrument.addClsInstrumentationHandler(({ metric }) => {
        const entry = metric.entries[metric.entries.length - 1];
        if (!entry) {
          return;
        }
        debugBuild.DEBUG_BUILD && utils.logger.log("[Measurements] Adding CLS");
        _measurements["cls"] = { value: metric.value, unit: "" };
        _clsEntry = entry;
      }, true);
    }
    function _trackLCP() {
      return instrument.addLcpInstrumentationHandler(({ metric }) => {
        const entry = metric.entries[metric.entries.length - 1];
        if (!entry) {
          return;
        }
        debugBuild.DEBUG_BUILD && utils.logger.log("[Measurements] Adding LCP");
        _measurements["lcp"] = { value: metric.value, unit: "millisecond" };
        _lcpEntry = entry;
      }, true);
    }
    function _trackFID() {
      return instrument.addFidInstrumentationHandler(({ metric }) => {
        const entry = metric.entries[metric.entries.length - 1];
        if (!entry) {
          return;
        }
        const timeOrigin = msToSec(utils.browserPerformanceTimeOrigin);
        const startTime = msToSec(entry.startTime);
        debugBuild.DEBUG_BUILD && utils.logger.log("[Measurements] Adding FID");
        _measurements["fid"] = { value: metric.value, unit: "millisecond" };
        _measurements["mark.fid"] = { value: timeOrigin + startTime, unit: "second" };
      });
    }
    function _trackTtfb() {
      return instrument.addTtfbInstrumentationHandler(({ metric }) => {
        const entry = metric.entries[metric.entries.length - 1];
        if (!entry) {
          return;
        }
        debugBuild.DEBUG_BUILD && utils.logger.log("[Measurements] Adding TTFB");
        _measurements["ttfb"] = { value: metric.value, unit: "millisecond" };
      });
    }
    var INP_ENTRY_MAP = {
      click: "click",
      pointerdown: "click",
      pointerup: "click",
      mousedown: "click",
      mouseup: "click",
      touchstart: "click",
      touchend: "click",
      mouseover: "hover",
      mouseout: "hover",
      mouseenter: "hover",
      mouseleave: "hover",
      pointerover: "hover",
      pointerout: "hover",
      pointerenter: "hover",
      pointerleave: "hover",
      dragstart: "drag",
      dragend: "drag",
      drag: "drag",
      dragenter: "drag",
      dragleave: "drag",
      dragover: "drag",
      drop: "drag",
      keydown: "press",
      keyup: "press",
      keypress: "press",
      input: "press"
    };
    function _trackINP(interactionIdToRouteNameMapping, interactionsSampleRate) {
      return instrument.addInpInstrumentationHandler(({ metric }) => {
        if (metric.value === void 0) {
          return;
        }
        const entry = metric.entries.find(
          (entry2) => entry2.duration === metric.value && INP_ENTRY_MAP[entry2.name] !== void 0
        );
        const client = core.getClient();
        if (!entry || !client) {
          return;
        }
        const interactionType = INP_ENTRY_MAP[entry.name];
        const options = client.getOptions();
        const startTime = msToSec(utils.browserPerformanceTimeOrigin + entry.startTime);
        const duration = msToSec(metric.value);
        const interaction = entry.interactionId !== void 0 ? interactionIdToRouteNameMapping[entry.interactionId] : void 0;
        if (interaction === void 0) {
          return;
        }
        const { routeName, parentContext, activeTransaction, user, replayId } = interaction;
        const userDisplay = user !== void 0 ? user.email || user.id || user.ip_address : void 0;
        const profileId = activeTransaction !== void 0 ? activeTransaction.getProfileId() : void 0;
        const span = new core.Span({
          startTimestamp: startTime,
          endTimestamp: startTime + duration,
          op: `ui.interaction.${interactionType}`,
          name: utils.htmlTreeAsString(entry.target),
          attributes: {
            release: options.release,
            environment: options.environment,
            transaction: routeName,
            ...userDisplay !== void 0 && userDisplay !== "" ? { user: userDisplay } : {},
            ...profileId !== void 0 ? { profile_id: profileId } : {},
            ...replayId !== void 0 ? { replay_id: replayId } : {}
          },
          exclusiveTime: metric.value,
          measurements: {
            inp: { value: metric.value, unit: "millisecond" }
          }
        });
        const sampleRate = getSampleRate(parentContext, options, interactionsSampleRate);
        if (!sampleRate) {
          return;
        }
        if (Math.random() < sampleRate) {
          const envelope = span ? core.createSpanEnvelope([span], client.getDsn()) : void 0;
          const transport = client && client.getTransport();
          if (transport && envelope) {
            transport.send(envelope).then(null, (reason) => {
              debugBuild.DEBUG_BUILD && utils.logger.error("Error while sending interaction:", reason);
            });
          }
          return;
        }
      });
    }
    function addPerformanceEntries(transaction) {
      const performance2 = getBrowserPerformanceAPI();
      if (!performance2 || !types.WINDOW.performance.getEntries || !utils.browserPerformanceTimeOrigin) {
        return;
      }
      debugBuild.DEBUG_BUILD && utils.logger.log("[Tracing] Adding & adjusting spans using Performance API");
      const timeOrigin = msToSec(utils.browserPerformanceTimeOrigin);
      const performanceEntries = performance2.getEntries();
      const { op, start_timestamp: transactionStartTime } = core.spanToJSON(transaction);
      performanceEntries.slice(_performanceCursor).forEach((entry) => {
        const startTime = msToSec(entry.startTime);
        const duration = msToSec(entry.duration);
        if (transaction.op === "navigation" && transactionStartTime && timeOrigin + startTime < transactionStartTime) {
          return;
        }
        switch (entry.entryType) {
          case "navigation": {
            _addNavigationSpans(transaction, entry, timeOrigin);
            break;
          }
          case "mark":
          case "paint":
          case "measure": {
            _addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);
            const firstHidden = getVisibilityWatcher.getVisibilityWatcher();
            const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;
            if (entry.name === "first-paint" && shouldRecord) {
              debugBuild.DEBUG_BUILD && utils.logger.log("[Measurements] Adding FP");
              _measurements["fp"] = { value: entry.startTime, unit: "millisecond" };
            }
            if (entry.name === "first-contentful-paint" && shouldRecord) {
              debugBuild.DEBUG_BUILD && utils.logger.log("[Measurements] Adding FCP");
              _measurements["fcp"] = { value: entry.startTime, unit: "millisecond" };
            }
            break;
          }
          case "resource": {
            _addResourceSpans(transaction, entry, entry.name, startTime, duration, timeOrigin);
            break;
          }
        }
      });
      _performanceCursor = Math.max(performanceEntries.length - 1, 0);
      _trackNavigator(transaction);
      if (op === "pageload") {
        _addTtfbRequestTimeToMeasurements(_measurements);
        ["fcp", "fp", "lcp"].forEach((name) => {
          if (!_measurements[name] || !transactionStartTime || timeOrigin >= transactionStartTime) {
            return;
          }
          const oldValue = _measurements[name].value;
          const measurementTimestamp = timeOrigin + msToSec(oldValue);
          const normalizedValue = Math.abs((measurementTimestamp - transactionStartTime) * 1e3);
          const delta = normalizedValue - oldValue;
          debugBuild.DEBUG_BUILD && utils.logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`);
          _measurements[name].value = normalizedValue;
        });
        const fidMark = _measurements["mark.fid"];
        if (fidMark && _measurements["fid"]) {
          utils$1._startChild(transaction, {
            description: "first input delay",
            endTimestamp: fidMark.value + msToSec(_measurements["fid"].value),
            op: "ui.action",
            origin: "auto.ui.browser.metrics",
            startTimestamp: fidMark.value
          });
          delete _measurements["mark.fid"];
        }
        if (!("fcp" in _measurements)) {
          delete _measurements.cls;
        }
        Object.keys(_measurements).forEach((measurementName) => {
          core.setMeasurement(measurementName, _measurements[measurementName].value, _measurements[measurementName].unit);
        });
        _tagMetricInfo(transaction);
      }
      _lcpEntry = void 0;
      _clsEntry = void 0;
      _measurements = {};
    }
    function _addMeasureSpans(transaction, entry, startTime, duration, timeOrigin) {
      const measureStartTimestamp = timeOrigin + startTime;
      const measureEndTimestamp = measureStartTimestamp + duration;
      utils$1._startChild(transaction, {
        description: entry.name,
        endTimestamp: measureEndTimestamp,
        op: entry.entryType,
        origin: "auto.resource.browser.metrics",
        startTimestamp: measureStartTimestamp
      });
      return measureStartTimestamp;
    }
    function _addNavigationSpans(transaction, entry, timeOrigin) {
      ["unloadEvent", "redirect", "domContentLoadedEvent", "loadEvent", "connect"].forEach((event) => {
        _addPerformanceNavigationTiming(transaction, entry, event, timeOrigin);
      });
      _addPerformanceNavigationTiming(transaction, entry, "secureConnection", timeOrigin, "TLS/SSL", "connectEnd");
      _addPerformanceNavigationTiming(transaction, entry, "fetch", timeOrigin, "cache", "domainLookupStart");
      _addPerformanceNavigationTiming(transaction, entry, "domainLookup", timeOrigin, "DNS");
      _addRequest(transaction, entry, timeOrigin);
    }
    function _addPerformanceNavigationTiming(transaction, entry, event, timeOrigin, description, eventEnd) {
      const end = eventEnd ? entry[eventEnd] : entry[`${event}End`];
      const start = entry[`${event}Start`];
      if (!start || !end) {
        return;
      }
      utils$1._startChild(transaction, {
        op: "browser",
        origin: "auto.browser.browser.metrics",
        description: description || event,
        startTimestamp: timeOrigin + msToSec(start),
        endTimestamp: timeOrigin + msToSec(end)
      });
    }
    function _addRequest(transaction, entry, timeOrigin) {
      if (entry.responseEnd) {
        utils$1._startChild(transaction, {
          op: "browser",
          origin: "auto.browser.browser.metrics",
          description: "request",
          startTimestamp: timeOrigin + msToSec(entry.requestStart),
          endTimestamp: timeOrigin + msToSec(entry.responseEnd)
        });
        utils$1._startChild(transaction, {
          op: "browser",
          origin: "auto.browser.browser.metrics",
          description: "response",
          startTimestamp: timeOrigin + msToSec(entry.responseStart),
          endTimestamp: timeOrigin + msToSec(entry.responseEnd)
        });
      }
    }
    function _addResourceSpans(transaction, entry, resourceUrl, startTime, duration, timeOrigin) {
      if (entry.initiatorType === "xmlhttprequest" || entry.initiatorType === "fetch") {
        return;
      }
      const parsedUrl = utils.parseUrl(resourceUrl);
      const data = {};
      setResourceEntrySizeData(data, entry, "transferSize", "http.response_transfer_size");
      setResourceEntrySizeData(data, entry, "encodedBodySize", "http.response_content_length");
      setResourceEntrySizeData(data, entry, "decodedBodySize", "http.decoded_response_content_length");
      if ("renderBlockingStatus" in entry) {
        data["resource.render_blocking_status"] = entry.renderBlockingStatus;
      }
      if (parsedUrl.protocol) {
        data["url.scheme"] = parsedUrl.protocol.split(":").pop();
      }
      if (parsedUrl.host) {
        data["server.address"] = parsedUrl.host;
      }
      data["url.same_origin"] = resourceUrl.includes(types.WINDOW.location.origin);
      const startTimestamp = timeOrigin + startTime;
      const endTimestamp = startTimestamp + duration;
      utils$1._startChild(transaction, {
        description: resourceUrl.replace(types.WINDOW.location.origin, ""),
        endTimestamp,
        op: entry.initiatorType ? `resource.${entry.initiatorType}` : "resource.other",
        origin: "auto.resource.browser.metrics",
        startTimestamp,
        data
      });
    }
    function _trackNavigator(transaction) {
      const navigator2 = types.WINDOW.navigator;
      if (!navigator2) {
        return;
      }
      const connection = navigator2.connection;
      if (connection) {
        if (connection.effectiveType) {
          transaction.setTag("effectiveConnectionType", connection.effectiveType);
        }
        if (connection.type) {
          transaction.setTag("connectionType", connection.type);
        }
        if (utils$1.isMeasurementValue(connection.rtt)) {
          _measurements["connection.rtt"] = { value: connection.rtt, unit: "millisecond" };
        }
      }
      if (utils$1.isMeasurementValue(navigator2.deviceMemory)) {
        transaction.setTag("deviceMemory", `${navigator2.deviceMemory} GB`);
      }
      if (utils$1.isMeasurementValue(navigator2.hardwareConcurrency)) {
        transaction.setTag("hardwareConcurrency", String(navigator2.hardwareConcurrency));
      }
    }
    function _tagMetricInfo(transaction) {
      if (_lcpEntry) {
        debugBuild.DEBUG_BUILD && utils.logger.log("[Measurements] Adding LCP Data");
        if (_lcpEntry.element) {
          transaction.setTag("lcp.element", utils.htmlTreeAsString(_lcpEntry.element));
        }
        if (_lcpEntry.id) {
          transaction.setTag("lcp.id", _lcpEntry.id);
        }
        if (_lcpEntry.url) {
          transaction.setTag("lcp.url", _lcpEntry.url.trim().slice(0, 200));
        }
        transaction.setTag("lcp.size", _lcpEntry.size);
      }
      if (_clsEntry && _clsEntry.sources) {
        debugBuild.DEBUG_BUILD && utils.logger.log("[Measurements] Adding CLS Data");
        _clsEntry.sources.forEach(
          (source, index) => (
            // TODO: Can we rewrite this to an attribute?
            // eslint-disable-next-line deprecation/deprecation
            transaction.setTag(`cls.source.${index + 1}`, utils.htmlTreeAsString(source.node))
          )
        );
      }
    }
    function setResourceEntrySizeData(data, entry, key, dataKey) {
      const entryVal = entry[key];
      if (entryVal != null && entryVal < MAX_INT_AS_BYTES) {
        data[dataKey] = entryVal;
      }
    }
    function _addTtfbRequestTimeToMeasurements(_measurements2) {
      const navEntry = getNavigationEntry.getNavigationEntry();
      if (!navEntry) {
        return;
      }
      const { responseStart, requestStart } = navEntry;
      if (requestStart <= responseStart) {
        debugBuild.DEBUG_BUILD && utils.logger.log("[Measurements] Adding TTFB Request Time");
        _measurements2["ttfb.requestTime"] = {
          value: responseStart - requestStart,
          unit: "millisecond"
        };
      }
    }
    function getSampleRate(transactionContext, options, interactionsSampleRate) {
      if (!core.hasTracingEnabled(options)) {
        return false;
      }
      let sampleRate;
      if (transactionContext !== void 0 && typeof options.tracesSampler === "function") {
        sampleRate = options.tracesSampler({
          transactionContext,
          name: transactionContext.name,
          parentSampled: transactionContext.parentSampled,
          attributes: {
            // eslint-disable-next-line deprecation/deprecation
            ...transactionContext.data,
            ...transactionContext.attributes
          },
          location: types.WINDOW.location
        });
      } else if (transactionContext !== void 0 && transactionContext.sampled !== void 0) {
        sampleRate = transactionContext.sampled;
      } else if (typeof options.tracesSampleRate !== "undefined") {
        sampleRate = options.tracesSampleRate;
      } else {
        sampleRate = 1;
      }
      if (!core.isValidSampleRate(sampleRate)) {
        debugBuild.DEBUG_BUILD && utils.logger.warn("[Tracing] Discarding interaction span because of invalid sample rate.");
        return false;
      }
      if (sampleRate === true) {
        return interactionsSampleRate;
      } else if (sampleRate === false) {
        return 0;
      }
      return sampleRate * interactionsSampleRate;
    }
    exports._addMeasureSpans = _addMeasureSpans;
    exports._addResourceSpans = _addResourceSpans;
    exports.addPerformanceEntries = addPerformanceEntries;
    exports.startTrackingINP = startTrackingINP;
    exports.startTrackingInteractions = startTrackingInteractions;
    exports.startTrackingLongTasks = startTrackingLongTasks;
    exports.startTrackingWebVitals = startTrackingWebVitals;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/common/fetch.js
var require_fetch2 = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/common/fetch.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    function instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeaders, spans, spanOrigin = "auto.http.browser") {
      if (!core.hasTracingEnabled() || !handlerData.fetchData) {
        return void 0;
      }
      const shouldCreateSpanResult = shouldCreateSpan(handlerData.fetchData.url);
      if (handlerData.endTimestamp && shouldCreateSpanResult) {
        const spanId = handlerData.fetchData.__span;
        if (!spanId)
          return;
        const span2 = spans[spanId];
        if (span2) {
          endSpan(span2, handlerData);
          delete spans[spanId];
        }
        return void 0;
      }
      const scope = core.getCurrentScope();
      const client = core.getClient();
      const { method, url } = handlerData.fetchData;
      const fullUrl = getFullURL(url);
      const host = fullUrl ? utils.parseUrl(fullUrl).host : void 0;
      const span = shouldCreateSpanResult ? core.startInactiveSpan({
        name: `${method} ${url}`,
        onlyIfParent: true,
        attributes: {
          url,
          type: "fetch",
          "http.method": method,
          "http.url": fullUrl,
          "server.address": host,
          [core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin
        },
        op: "http.client"
      }) : void 0;
      if (span) {
        handlerData.fetchData.__span = span.spanContext().spanId;
        spans[span.spanContext().spanId] = span;
      }
      if (shouldAttachHeaders(handlerData.fetchData.url) && client) {
        const request = handlerData.args[0];
        handlerData.args[1] = handlerData.args[1] || {};
        const options = handlerData.args[1];
        options.headers = addTracingHeadersToFetchRequest(request, client, scope, options, span);
      }
      return span;
    }
    function addTracingHeadersToFetchRequest(request, client, scope, options, requestSpan) {
      const span = requestSpan || scope.getSpan();
      const isolationScope = core.getIsolationScope();
      const { traceId, spanId, sampled, dsc } = {
        ...isolationScope.getPropagationContext(),
        ...scope.getPropagationContext()
      };
      const sentryTraceHeader = span ? core.spanToTraceHeader(span) : utils.generateSentryTraceHeader(traceId, spanId, sampled);
      const sentryBaggageHeader = utils.dynamicSamplingContextToSentryBaggageHeader(
        dsc || (span ? core.getDynamicSamplingContextFromSpan(span) : core.getDynamicSamplingContextFromClient(traceId, client, scope))
      );
      const headers = options.headers || (typeof Request !== "undefined" && utils.isInstanceOf(request, Request) ? request.headers : void 0);
      if (!headers) {
        return { "sentry-trace": sentryTraceHeader, baggage: sentryBaggageHeader };
      } else if (typeof Headers !== "undefined" && utils.isInstanceOf(headers, Headers)) {
        const newHeaders = new Headers(headers);
        newHeaders.append("sentry-trace", sentryTraceHeader);
        if (sentryBaggageHeader) {
          newHeaders.append(utils.BAGGAGE_HEADER_NAME, sentryBaggageHeader);
        }
        return newHeaders;
      } else if (Array.isArray(headers)) {
        const newHeaders = [...headers, ["sentry-trace", sentryTraceHeader]];
        if (sentryBaggageHeader) {
          newHeaders.push([utils.BAGGAGE_HEADER_NAME, sentryBaggageHeader]);
        }
        return newHeaders;
      } else {
        const existingBaggageHeader = "baggage" in headers ? headers.baggage : void 0;
        const newBaggageHeaders = [];
        if (Array.isArray(existingBaggageHeader)) {
          newBaggageHeaders.push(...existingBaggageHeader);
        } else if (existingBaggageHeader) {
          newBaggageHeaders.push(existingBaggageHeader);
        }
        if (sentryBaggageHeader) {
          newBaggageHeaders.push(sentryBaggageHeader);
        }
        return {
          ...headers,
          "sentry-trace": sentryTraceHeader,
          baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(",") : void 0
        };
      }
    }
    function getFullURL(url) {
      try {
        const parsed = new URL(url);
        return parsed.href;
      } catch (e2) {
        return void 0;
      }
    }
    function endSpan(span, handlerData) {
      if (handlerData.response) {
        core.setHttpStatus(span, handlerData.response.status);
        const contentLength = handlerData.response && handlerData.response.headers && handlerData.response.headers.get("content-length");
        if (contentLength) {
          const contentLengthNum = parseInt(contentLength);
          if (contentLengthNum > 0) {
            span.setAttribute("http.response_content_length", contentLengthNum);
          }
        }
      } else if (handlerData.error) {
        span.setStatus("internal_error");
      }
      span.end();
    }
    exports.addTracingHeadersToFetchRequest = addTracingHeadersToFetchRequest;
    exports.instrumentFetchRequest = instrumentFetchRequest;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/request.js
var require_request = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/request.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var fetch2 = require_fetch2();
    var instrument = require_instrument2();
    var types = require_types();
    var DEFAULT_TRACE_PROPAGATION_TARGETS = ["localhost", /^\/(?!\/)/];
    var defaultRequestInstrumentationOptions = {
      traceFetch: true,
      traceXHR: true,
      enableHTTPTimings: true,
      // TODO (v8): Remove this property
      tracingOrigins: DEFAULT_TRACE_PROPAGATION_TARGETS,
      tracePropagationTargets: DEFAULT_TRACE_PROPAGATION_TARGETS
    };
    function instrumentOutgoingRequests(_options) {
      const {
        traceFetch,
        traceXHR,
        // eslint-disable-next-line deprecation/deprecation
        tracePropagationTargets,
        // eslint-disable-next-line deprecation/deprecation
        tracingOrigins,
        shouldCreateSpanForRequest,
        enableHTTPTimings
      } = {
        traceFetch: defaultRequestInstrumentationOptions.traceFetch,
        traceXHR: defaultRequestInstrumentationOptions.traceXHR,
        ..._options
      };
      const shouldCreateSpan = typeof shouldCreateSpanForRequest === "function" ? shouldCreateSpanForRequest : (_3) => true;
      const shouldAttachHeadersWithTargets = (url) => shouldAttachHeaders(url, tracePropagationTargets || tracingOrigins);
      const spans = {};
      if (traceFetch) {
        utils.addFetchInstrumentationHandler((handlerData) => {
          const createdSpan = fetch2.instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);
          if (createdSpan) {
            const fullUrl = getFullURL(handlerData.fetchData.url);
            const host = fullUrl ? utils.parseUrl(fullUrl).host : void 0;
            createdSpan.setAttributes({
              "http.url": fullUrl,
              "server.address": host
            });
          }
          if (enableHTTPTimings && createdSpan) {
            addHTTPTimings(createdSpan);
          }
        });
      }
      if (traceXHR) {
        utils.addXhrInstrumentationHandler((handlerData) => {
          const createdSpan = xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);
          if (enableHTTPTimings && createdSpan) {
            addHTTPTimings(createdSpan);
          }
        });
      }
    }
    function isPerformanceResourceTiming(entry) {
      return entry.entryType === "resource" && "initiatorType" in entry && typeof entry.nextHopProtocol === "string" && (entry.initiatorType === "fetch" || entry.initiatorType === "xmlhttprequest");
    }
    function addHTTPTimings(span) {
      const { url } = core.spanToJSON(span).data || {};
      if (!url || typeof url !== "string") {
        return;
      }
      const cleanup = instrument.addPerformanceInstrumentationHandler("resource", ({ entries }) => {
        entries.forEach((entry) => {
          if (isPerformanceResourceTiming(entry) && entry.name.endsWith(url)) {
            const spanData = resourceTimingEntryToSpanData(entry);
            spanData.forEach((data) => span.setAttribute(...data));
            setTimeout(cleanup);
          }
        });
      });
    }
    function extractNetworkProtocol(nextHopProtocol) {
      let name = "unknown";
      let version2 = "unknown";
      let _name = "";
      for (const char of nextHopProtocol) {
        if (char === "/") {
          [name, version2] = nextHopProtocol.split("/");
          break;
        }
        if (!isNaN(Number(char))) {
          name = _name === "h" ? "http" : _name;
          version2 = nextHopProtocol.split(_name)[1];
          break;
        }
        _name += char;
      }
      if (_name === nextHopProtocol) {
        name = _name;
      }
      return { name, version: version2 };
    }
    function getAbsoluteTime(time = 0) {
      return ((utils.browserPerformanceTimeOrigin || performance.timeOrigin) + time) / 1e3;
    }
    function resourceTimingEntryToSpanData(resourceTiming) {
      const { name, version: version2 } = extractNetworkProtocol(resourceTiming.nextHopProtocol);
      const timingSpanData = [];
      timingSpanData.push(["network.protocol.version", version2], ["network.protocol.name", name]);
      if (!utils.browserPerformanceTimeOrigin) {
        return timingSpanData;
      }
      return [
        ...timingSpanData,
        ["http.request.redirect_start", getAbsoluteTime(resourceTiming.redirectStart)],
        ["http.request.fetch_start", getAbsoluteTime(resourceTiming.fetchStart)],
        ["http.request.domain_lookup_start", getAbsoluteTime(resourceTiming.domainLookupStart)],
        ["http.request.domain_lookup_end", getAbsoluteTime(resourceTiming.domainLookupEnd)],
        ["http.request.connect_start", getAbsoluteTime(resourceTiming.connectStart)],
        ["http.request.secure_connection_start", getAbsoluteTime(resourceTiming.secureConnectionStart)],
        ["http.request.connection_end", getAbsoluteTime(resourceTiming.connectEnd)],
        ["http.request.request_start", getAbsoluteTime(resourceTiming.requestStart)],
        ["http.request.response_start", getAbsoluteTime(resourceTiming.responseStart)],
        ["http.request.response_end", getAbsoluteTime(resourceTiming.responseEnd)]
      ];
    }
    function shouldAttachHeaders(url, tracePropagationTargets) {
      return utils.stringMatchesSomePattern(url, tracePropagationTargets || DEFAULT_TRACE_PROPAGATION_TARGETS);
    }
    function xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeaders2, spans) {
      const xhr = handlerData.xhr;
      const sentryXhrData = xhr && xhr[utils.SENTRY_XHR_DATA_KEY];
      if (!core.hasTracingEnabled() || !xhr || xhr.__sentry_own_request__ || !sentryXhrData) {
        return void 0;
      }
      const shouldCreateSpanResult = shouldCreateSpan(sentryXhrData.url);
      if (handlerData.endTimestamp && shouldCreateSpanResult) {
        const spanId = xhr.__sentry_xhr_span_id__;
        if (!spanId)
          return;
        const span2 = spans[spanId];
        if (span2 && sentryXhrData.status_code !== void 0) {
          core.setHttpStatus(span2, sentryXhrData.status_code);
          span2.end();
          delete spans[spanId];
        }
        return void 0;
      }
      const scope = core.getCurrentScope();
      const isolationScope = core.getIsolationScope();
      const fullUrl = getFullURL(sentryXhrData.url);
      const host = fullUrl ? utils.parseUrl(fullUrl).host : void 0;
      const span = shouldCreateSpanResult ? core.startInactiveSpan({
        name: `${sentryXhrData.method} ${sentryXhrData.url}`,
        onlyIfParent: true,
        attributes: {
          type: "xhr",
          "http.method": sentryXhrData.method,
          "http.url": fullUrl,
          url: sentryXhrData.url,
          "server.address": host,
          [core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.browser"
        },
        op: "http.client"
      }) : void 0;
      if (span) {
        xhr.__sentry_xhr_span_id__ = span.spanContext().spanId;
        spans[xhr.__sentry_xhr_span_id__] = span;
      }
      const client = core.getClient();
      if (xhr.setRequestHeader && shouldAttachHeaders2(sentryXhrData.url) && client) {
        const { traceId, spanId, sampled, dsc } = {
          ...isolationScope.getPropagationContext(),
          ...scope.getPropagationContext()
        };
        const sentryTraceHeader = span ? core.spanToTraceHeader(span) : utils.generateSentryTraceHeader(traceId, spanId, sampled);
        const sentryBaggageHeader = utils.dynamicSamplingContextToSentryBaggageHeader(
          dsc || (span ? core.getDynamicSamplingContextFromSpan(span) : core.getDynamicSamplingContextFromClient(traceId, client, scope))
        );
        setHeaderOnXhr(xhr, sentryTraceHeader, sentryBaggageHeader);
      }
      return span;
    }
    function setHeaderOnXhr(xhr, sentryTraceHeader, sentryBaggageHeader) {
      try {
        xhr.setRequestHeader("sentry-trace", sentryTraceHeader);
        if (sentryBaggageHeader) {
          xhr.setRequestHeader(utils.BAGGAGE_HEADER_NAME, sentryBaggageHeader);
        }
      } catch (_3) {
      }
    }
    function getFullURL(url) {
      try {
        const parsed = new URL(url, types.WINDOW.location.origin);
        return parsed.href;
      } catch (e2) {
        return void 0;
      }
    }
    exports.DEFAULT_TRACE_PROPAGATION_TARGETS = DEFAULT_TRACE_PROPAGATION_TARGETS;
    exports.defaultRequestInstrumentationOptions = defaultRequestInstrumentationOptions;
    exports.extractNetworkProtocol = extractNetworkProtocol;
    exports.instrumentOutgoingRequests = instrumentOutgoingRequests;
    exports.shouldAttachHeaders = shouldAttachHeaders;
    exports.xhrCallback = xhrCallback;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/router.js
var require_router = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/router.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var debugBuild = require_debug_build3();
    var types = require_types();
    function instrumentRoutingWithDefaults(customStartTransaction, startTransactionOnPageLoad = true, startTransactionOnLocationChange = true) {
      if (!types.WINDOW || !types.WINDOW.location) {
        debugBuild.DEBUG_BUILD && utils.logger.warn("Could not initialize routing instrumentation due to invalid location");
        return;
      }
      let startingUrl = types.WINDOW.location.href;
      let activeTransaction;
      if (startTransactionOnPageLoad) {
        activeTransaction = customStartTransaction({
          name: types.WINDOW.location.pathname,
          // pageload should always start at timeOrigin (and needs to be in s, not ms)
          startTimestamp: utils.browserPerformanceTimeOrigin ? utils.browserPerformanceTimeOrigin / 1e3 : void 0,
          op: "pageload",
          origin: "auto.pageload.browser",
          metadata: { source: "url" }
        });
      }
      if (startTransactionOnLocationChange) {
        utils.addHistoryInstrumentationHandler(({ to, from }) => {
          if (from === void 0 && startingUrl && startingUrl.indexOf(to) !== -1) {
            startingUrl = void 0;
            return;
          }
          if (from !== to) {
            startingUrl = void 0;
            if (activeTransaction) {
              debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`);
              activeTransaction.end();
            }
            activeTransaction = customStartTransaction({
              name: types.WINDOW.location.pathname,
              op: "navigation",
              origin: "auto.navigation.browser",
              metadata: { source: "url" }
            });
          }
        });
      }
    }
    exports.instrumentRoutingWithDefaults = instrumentRoutingWithDefaults;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/browsertracing.js
var require_browsertracing = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/browsertracing.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var debugBuild = require_debug_build3();
    var backgroundtab = require_backgroundtab();
    var instrument = require_instrument2();
    var index = require_metrics();
    var request = require_request();
    var router = require_router();
    var types = require_types();
    var BROWSER_TRACING_INTEGRATION_ID = "BrowserTracing";
    var DEFAULT_BROWSER_TRACING_OPTIONS = {
      ...core.TRACING_DEFAULTS,
      markBackgroundTransactions: true,
      routingInstrumentation: router.instrumentRoutingWithDefaults,
      startTransactionOnLocationChange: true,
      startTransactionOnPageLoad: true,
      enableLongTask: true,
      enableInp: false,
      interactionsSampleRate: 1,
      _experiments: {},
      ...request.defaultRequestInstrumentationOptions
    };
    var MAX_INTERACTIONS = 10;
    var BrowserTracing = class {
      // This class currently doesn't have a static `id` field like the other integration classes, because it prevented
      // @sentry/tracing from being treeshaken. Tree shakers do not like static fields, because they behave like side effects.
      // TODO: Come up with a better plan, than using static fields on integration classes, and use that plan on all
      // integrations.
      /** Browser Tracing integration options */
      /**
       * @inheritDoc
       */
      // eslint-disable-next-line deprecation/deprecation
      constructor(_options) {
        this.name = BROWSER_TRACING_INTEGRATION_ID;
        this._hasSetTracePropagationTargets = false;
        core.addTracingExtensions();
        if (debugBuild.DEBUG_BUILD) {
          this._hasSetTracePropagationTargets = !!(_options && // eslint-disable-next-line deprecation/deprecation
          (_options.tracePropagationTargets || _options.tracingOrigins));
        }
        this.options = {
          ...DEFAULT_BROWSER_TRACING_OPTIONS,
          ..._options
        };
        if (this.options._experiments.enableLongTask !== void 0) {
          this.options.enableLongTask = this.options._experiments.enableLongTask;
        }
        if (_options && !_options.tracePropagationTargets && _options.tracingOrigins) {
          this.options.tracePropagationTargets = _options.tracingOrigins;
        }
        this._collectWebVitals = index.startTrackingWebVitals();
        this._interactionIdToRouteNameMapping = {};
        if (this.options.enableInp) {
          index.startTrackingINP(this._interactionIdToRouteNameMapping, this.options.interactionsSampleRate);
        }
        if (this.options.enableLongTask) {
          index.startTrackingLongTasks();
        }
        if (this.options._experiments.enableInteractions) {
          index.startTrackingInteractions();
        }
        this._latestRoute = {
          name: void 0,
          context: void 0
        };
      }
      /**
       * @inheritDoc
       */
      // eslint-disable-next-line deprecation/deprecation
      setupOnce(_3, getCurrentHub) {
        this._getCurrentHub = getCurrentHub;
        const hub = getCurrentHub();
        const client = hub.getClient();
        const clientOptions = client && client.getOptions();
        const {
          routingInstrumentation: instrumentRouting,
          startTransactionOnLocationChange,
          startTransactionOnPageLoad,
          markBackgroundTransactions,
          traceFetch,
          traceXHR,
          shouldCreateSpanForRequest,
          enableHTTPTimings,
          _experiments
        } = this.options;
        const clientOptionsTracePropagationTargets = clientOptions && clientOptions.tracePropagationTargets;
        const tracePropagationTargets = clientOptionsTracePropagationTargets || this.options.tracePropagationTargets;
        if (debugBuild.DEBUG_BUILD && this._hasSetTracePropagationTargets && clientOptionsTracePropagationTargets) {
          utils.logger.warn(
            "[Tracing] The `tracePropagationTargets` option was set in the BrowserTracing integration and top level `Sentry.init`. The top level `Sentry.init` value is being used."
          );
        }
        instrumentRouting(
          (context2) => {
            const transaction = this._createRouteTransaction(context2);
            this.options._experiments.onStartRouteTransaction && this.options._experiments.onStartRouteTransaction(transaction, context2, getCurrentHub);
            return transaction;
          },
          startTransactionOnPageLoad,
          startTransactionOnLocationChange
        );
        if (markBackgroundTransactions) {
          backgroundtab.registerBackgroundTabDetection();
        }
        if (_experiments.enableInteractions) {
          this._registerInteractionListener();
        }
        if (this.options.enableInp) {
          this._registerInpInteractionListener();
        }
        request.instrumentOutgoingRequests({
          traceFetch,
          traceXHR,
          tracePropagationTargets,
          shouldCreateSpanForRequest,
          enableHTTPTimings
        });
      }
      /** Create routing idle transaction. */
      _createRouteTransaction(context2) {
        if (!this._getCurrentHub) {
          debugBuild.DEBUG_BUILD && utils.logger.warn(`[Tracing] Did not create ${context2.op} transaction because _getCurrentHub is invalid.`);
          return void 0;
        }
        const hub = this._getCurrentHub();
        const { beforeNavigate, idleTimeout, finalTimeout, heartbeatInterval } = this.options;
        const isPageloadTransaction = context2.op === "pageload";
        let expandedContext;
        if (isPageloadTransaction) {
          const sentryTrace = isPageloadTransaction ? getMetaContent("sentry-trace") : "";
          const baggage = isPageloadTransaction ? getMetaContent("baggage") : void 0;
          const { traceId, dsc, parentSpanId, sampled } = utils.propagationContextFromHeaders(sentryTrace, baggage);
          expandedContext = {
            traceId,
            parentSpanId,
            parentSampled: sampled,
            ...context2,
            metadata: {
              // eslint-disable-next-line deprecation/deprecation
              ...context2.metadata,
              dynamicSamplingContext: dsc
            },
            trimEnd: true
          };
        } else {
          expandedContext = {
            trimEnd: true,
            ...context2
          };
        }
        const modifiedContext = typeof beforeNavigate === "function" ? beforeNavigate(expandedContext) : expandedContext;
        const finalContext = modifiedContext === void 0 ? { ...expandedContext, sampled: false } : modifiedContext;
        finalContext.metadata = finalContext.name !== expandedContext.name ? (
          // eslint-disable-next-line deprecation/deprecation
          { ...finalContext.metadata, source: "custom" }
        ) : (
          // eslint-disable-next-line deprecation/deprecation
          finalContext.metadata
        );
        this._latestRoute.name = finalContext.name;
        this._latestRoute.context = finalContext;
        if (finalContext.sampled === false) {
          debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);
        }
        debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);
        const { location } = types.WINDOW;
        const idleTransaction = core.startIdleTransaction(
          hub,
          finalContext,
          idleTimeout,
          finalTimeout,
          true,
          { location },
          // for use in the tracesSampler
          heartbeatInterval,
          isPageloadTransaction
          // should wait for finish signal if it's a pageload transaction
        );
        if (isPageloadTransaction) {
          if (types.WINDOW.document) {
            types.WINDOW.document.addEventListener("readystatechange", () => {
              if (["interactive", "complete"].includes(types.WINDOW.document.readyState)) {
                idleTransaction.sendAutoFinishSignal();
              }
            });
            if (["interactive", "complete"].includes(types.WINDOW.document.readyState)) {
              idleTransaction.sendAutoFinishSignal();
            }
          }
        }
        idleTransaction.registerBeforeFinishCallback((transaction) => {
          this._collectWebVitals();
          index.addPerformanceEntries(transaction);
        });
        return idleTransaction;
      }
      /** Start listener for interaction transactions */
      _registerInteractionListener() {
        let inflightInteractionTransaction;
        const registerInteractionTransaction = () => {
          const { idleTimeout, finalTimeout, heartbeatInterval } = this.options;
          const op = "ui.action.click";
          const currentTransaction = core.getActiveTransaction();
          if (currentTransaction && currentTransaction.op && ["navigation", "pageload"].includes(currentTransaction.op)) {
            debugBuild.DEBUG_BUILD && utils.logger.warn(
              `[Tracing] Did not create ${op} transaction because a pageload or navigation transaction is in progress.`
            );
            return void 0;
          }
          if (inflightInteractionTransaction) {
            inflightInteractionTransaction.setFinishReason("interactionInterrupted");
            inflightInteractionTransaction.end();
            inflightInteractionTransaction = void 0;
          }
          if (!this._getCurrentHub) {
            debugBuild.DEBUG_BUILD && utils.logger.warn(`[Tracing] Did not create ${op} transaction because _getCurrentHub is invalid.`);
            return void 0;
          }
          if (!this._latestRoute.name) {
            debugBuild.DEBUG_BUILD && utils.logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);
            return void 0;
          }
          const hub = this._getCurrentHub();
          const { location } = types.WINDOW;
          const context2 = {
            name: this._latestRoute.name,
            op,
            trimEnd: true,
            data: {
              [core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: this._latestRoute.context ? getSource(this._latestRoute.context) : "url"
            }
          };
          inflightInteractionTransaction = core.startIdleTransaction(
            hub,
            context2,
            idleTimeout,
            finalTimeout,
            true,
            { location },
            // for use in the tracesSampler
            heartbeatInterval
          );
        };
        ["click"].forEach((type) => {
          if (types.WINDOW.document) {
            addEventListener(type, registerInteractionTransaction, { once: false, capture: true });
          }
        });
      }
      /** Creates a listener on interaction entries, and maps interactionIds to the origin path of the interaction */
      _registerInpInteractionListener() {
        const handleEntries = ({ entries }) => {
          const client = core.getClient();
          const replay = client !== void 0 && client.getIntegrationByName !== void 0 ? client.getIntegrationByName("Replay") : void 0;
          const replayId = replay !== void 0 ? replay.getReplayId() : void 0;
          const activeTransaction = core.getActiveTransaction();
          const currentScope = core.getCurrentScope();
          const user = currentScope !== void 0 ? currentScope.getUser() : void 0;
          entries.forEach((entry) => {
            if (isPerformanceEventTiming(entry)) {
              const interactionId = entry.interactionId;
              if (interactionId === void 0) {
                return;
              }
              const existingInteraction = this._interactionIdToRouteNameMapping[interactionId];
              const duration = entry.duration;
              const startTime = entry.startTime;
              const keys = Object.keys(this._interactionIdToRouteNameMapping);
              const minInteractionId = keys.length > 0 ? keys.reduce((a3, b) => {
                return this._interactionIdToRouteNameMapping[a3].duration < this._interactionIdToRouteNameMapping[b].duration ? a3 : b;
              }) : void 0;
              if (entry.entryType === "first-input") {
                const matchingEntry = keys.map((key) => this._interactionIdToRouteNameMapping[key]).some((interaction) => {
                  return interaction.duration === duration && interaction.startTime === startTime;
                });
                if (matchingEntry) {
                  return;
                }
              }
              if (!interactionId) {
                return;
              }
              if (existingInteraction) {
                existingInteraction.duration = Math.max(existingInteraction.duration, duration);
              } else if (keys.length < MAX_INTERACTIONS || minInteractionId === void 0 || duration > this._interactionIdToRouteNameMapping[minInteractionId].duration) {
                const routeName = this._latestRoute.name;
                const parentContext = this._latestRoute.context;
                if (routeName && parentContext) {
                  if (minInteractionId && Object.keys(this._interactionIdToRouteNameMapping).length >= MAX_INTERACTIONS) {
                    delete this._interactionIdToRouteNameMapping[minInteractionId];
                  }
                  this._interactionIdToRouteNameMapping[interactionId] = {
                    routeName,
                    duration,
                    parentContext,
                    user,
                    activeTransaction,
                    replayId,
                    startTime
                  };
                }
              }
            }
          });
        };
        instrument.addPerformanceInstrumentationHandler("event", handleEntries);
        instrument.addPerformanceInstrumentationHandler("first-input", handleEntries);
      }
    };
    function getMetaContent(metaName) {
      const metaTag = utils.getDomElement(`meta[name=${metaName}]`);
      return metaTag ? metaTag.getAttribute("content") : void 0;
    }
    function getSource(context2) {
      const sourceFromAttributes = context2.attributes && context2.attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
      const sourceFromData = context2.data && context2.data[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
      const sourceFromMetadata = context2.metadata && context2.metadata.source;
      return sourceFromAttributes || sourceFromData || sourceFromMetadata;
    }
    function isPerformanceEventTiming(entry) {
      return "duration" in entry;
    }
    exports.BROWSER_TRACING_INTEGRATION_ID = BROWSER_TRACING_INTEGRATION_ID;
    exports.BrowserTracing = BrowserTracing;
    exports.getMetaContent = getMetaContent;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/browserTracingIntegration.js
var require_browserTracingIntegration = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/browser/browserTracingIntegration.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var debugBuild = require_debug_build3();
    var backgroundtab = require_backgroundtab();
    var instrument = require_instrument2();
    var index = require_metrics();
    var request = require_request();
    var types = require_types();
    var BROWSER_TRACING_INTEGRATION_ID = "BrowserTracing";
    var DEFAULT_BROWSER_TRACING_OPTIONS = {
      ...core.TRACING_DEFAULTS,
      instrumentNavigation: true,
      instrumentPageLoad: true,
      markBackgroundSpan: true,
      enableLongTask: true,
      enableInp: false,
      interactionsSampleRate: 1,
      _experiments: {},
      ...request.defaultRequestInstrumentationOptions
    };
    var browserTracingIntegration = (_options = {}) => {
      const _hasSetTracePropagationTargets = debugBuild.DEBUG_BUILD ? !!// eslint-disable-next-line deprecation/deprecation
      (_options.tracePropagationTargets || _options.tracingOrigins) : false;
      core.addTracingExtensions();
      if (!_options.tracePropagationTargets && _options.tracingOrigins) {
        _options.tracePropagationTargets = _options.tracingOrigins;
      }
      const options = {
        ...DEFAULT_BROWSER_TRACING_OPTIONS,
        ..._options
      };
      const _collectWebVitals = index.startTrackingWebVitals();
      const interactionIdToRouteNameMapping = {};
      if (options.enableInp) {
        index.startTrackingINP(interactionIdToRouteNameMapping, options.interactionsSampleRate);
      }
      if (options.enableLongTask) {
        index.startTrackingLongTasks();
      }
      if (options._experiments.enableInteractions) {
        index.startTrackingInteractions();
      }
      const latestRoute = {
        name: void 0,
        context: void 0
      };
      function _createRouteTransaction(context2) {
        const hub = core.getCurrentHub();
        const { beforeStartSpan, idleTimeout, finalTimeout, heartbeatInterval } = options;
        const isPageloadTransaction = context2.op === "pageload";
        let expandedContext;
        if (isPageloadTransaction) {
          const sentryTrace = isPageloadTransaction ? getMetaContent("sentry-trace") : "";
          const baggage = isPageloadTransaction ? getMetaContent("baggage") : void 0;
          const { traceId, dsc, parentSpanId, sampled } = utils.propagationContextFromHeaders(sentryTrace, baggage);
          expandedContext = {
            traceId,
            parentSpanId,
            parentSampled: sampled,
            ...context2,
            metadata: {
              // eslint-disable-next-line deprecation/deprecation
              ...context2.metadata,
              dynamicSamplingContext: dsc
            },
            trimEnd: true
          };
        } else {
          expandedContext = {
            trimEnd: true,
            ...context2
          };
        }
        const finalContext = beforeStartSpan ? beforeStartSpan(expandedContext) : expandedContext;
        finalContext.metadata = finalContext.name !== expandedContext.name ? (
          // eslint-disable-next-line deprecation/deprecation
          { ...finalContext.metadata, source: "custom" }
        ) : (
          // eslint-disable-next-line deprecation/deprecation
          finalContext.metadata
        );
        latestRoute.name = finalContext.name;
        latestRoute.context = finalContext;
        if (finalContext.sampled === false) {
          debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);
        }
        debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);
        const { location } = types.WINDOW;
        const idleTransaction = core.startIdleTransaction(
          hub,
          finalContext,
          idleTimeout,
          finalTimeout,
          true,
          { location },
          // for use in the tracesSampler
          heartbeatInterval,
          isPageloadTransaction
          // should wait for finish signal if it's a pageload transaction
        );
        if (isPageloadTransaction && types.WINDOW.document) {
          types.WINDOW.document.addEventListener("readystatechange", () => {
            if (["interactive", "complete"].includes(types.WINDOW.document.readyState)) {
              idleTransaction.sendAutoFinishSignal();
            }
          });
          if (["interactive", "complete"].includes(types.WINDOW.document.readyState)) {
            idleTransaction.sendAutoFinishSignal();
          }
        }
        idleTransaction.registerBeforeFinishCallback((transaction) => {
          _collectWebVitals();
          index.addPerformanceEntries(transaction);
        });
        return idleTransaction;
      }
      return {
        name: BROWSER_TRACING_INTEGRATION_ID,
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        setupOnce: () => {
        },
        afterAllSetup(client) {
          const clientOptions = client.getOptions();
          const { markBackgroundSpan, traceFetch, traceXHR, shouldCreateSpanForRequest, enableHTTPTimings, _experiments } = options;
          const clientOptionsTracePropagationTargets = clientOptions && clientOptions.tracePropagationTargets;
          const tracePropagationTargets = clientOptionsTracePropagationTargets || options.tracePropagationTargets;
          if (debugBuild.DEBUG_BUILD && _hasSetTracePropagationTargets && clientOptionsTracePropagationTargets) {
            utils.logger.warn(
              "[Tracing] The `tracePropagationTargets` option was set in the BrowserTracing integration and top level `Sentry.init`. The top level `Sentry.init` value is being used."
            );
          }
          let activeSpan;
          let startingUrl = types.WINDOW.location && types.WINDOW.location.href;
          if (client.on) {
            client.on("startNavigationSpan", (context2) => {
              if (activeSpan) {
                debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Finishing current transaction with op: ${core.spanToJSON(activeSpan).op}`);
                activeSpan.end();
              }
              activeSpan = _createRouteTransaction({
                op: "navigation",
                ...context2
              });
            });
            client.on("startPageLoadSpan", (context2) => {
              if (activeSpan) {
                debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Finishing current transaction with op: ${core.spanToJSON(activeSpan).op}`);
                activeSpan.end();
              }
              activeSpan = _createRouteTransaction({
                op: "pageload",
                ...context2
              });
            });
          }
          if (options.instrumentPageLoad && client.emit && types.WINDOW.location) {
            const context2 = {
              name: types.WINDOW.location.pathname,
              // pageload should always start at timeOrigin (and needs to be in s, not ms)
              startTimestamp: utils.browserPerformanceTimeOrigin ? utils.browserPerformanceTimeOrigin / 1e3 : void 0,
              origin: "auto.pageload.browser",
              attributes: {
                [core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "url"
              }
            };
            startBrowserTracingPageLoadSpan(client, context2);
          }
          if (options.instrumentNavigation && client.emit && types.WINDOW.location) {
            utils.addHistoryInstrumentationHandler(({ to, from }) => {
              if (from === void 0 && startingUrl && startingUrl.indexOf(to) !== -1) {
                startingUrl = void 0;
                return;
              }
              if (from !== to) {
                startingUrl = void 0;
                const context2 = {
                  name: types.WINDOW.location.pathname,
                  origin: "auto.navigation.browser",
                  attributes: {
                    [core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "url"
                  }
                };
                startBrowserTracingNavigationSpan(client, context2);
              }
            });
          }
          if (markBackgroundSpan) {
            backgroundtab.registerBackgroundTabDetection();
          }
          if (_experiments.enableInteractions) {
            registerInteractionListener(options, latestRoute);
          }
          if (options.enableInp) {
            registerInpInteractionListener(interactionIdToRouteNameMapping, latestRoute);
          }
          request.instrumentOutgoingRequests({
            traceFetch,
            traceXHR,
            tracePropagationTargets,
            shouldCreateSpanForRequest,
            enableHTTPTimings
          });
        },
        // TODO v8: Remove this again
        // This is private API that we use to fix converted BrowserTracing integrations in Next.js & SvelteKit
        options
      };
    };
    function startBrowserTracingPageLoadSpan(client, spanOptions) {
      if (!client.emit) {
        return;
      }
      client.emit("startPageLoadSpan", spanOptions);
      const span = core.getActiveSpan();
      const op = span && core.spanToJSON(span).op;
      return op === "pageload" ? span : void 0;
    }
    function startBrowserTracingNavigationSpan(client, spanOptions) {
      if (!client.emit) {
        return;
      }
      client.emit("startNavigationSpan", spanOptions);
      const span = core.getActiveSpan();
      const op = span && core.spanToJSON(span).op;
      return op === "navigation" ? span : void 0;
    }
    function getMetaContent(metaName) {
      const metaTag = utils.getDomElement(`meta[name=${metaName}]`);
      return metaTag ? metaTag.getAttribute("content") : void 0;
    }
    function registerInteractionListener(options, latestRoute) {
      let inflightInteractionTransaction;
      const registerInteractionTransaction = () => {
        const { idleTimeout, finalTimeout, heartbeatInterval } = options;
        const op = "ui.action.click";
        const currentTransaction = core.getActiveTransaction();
        if (currentTransaction && currentTransaction.op && ["navigation", "pageload"].includes(currentTransaction.op)) {
          debugBuild.DEBUG_BUILD && utils.logger.warn(
            `[Tracing] Did not create ${op} transaction because a pageload or navigation transaction is in progress.`
          );
          return void 0;
        }
        if (inflightInteractionTransaction) {
          inflightInteractionTransaction.setFinishReason("interactionInterrupted");
          inflightInteractionTransaction.end();
          inflightInteractionTransaction = void 0;
        }
        if (!latestRoute.name) {
          debugBuild.DEBUG_BUILD && utils.logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);
          return void 0;
        }
        const { location } = types.WINDOW;
        const context2 = {
          name: latestRoute.name,
          op,
          trimEnd: true,
          data: {
            [core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: latestRoute.context ? getSource(latestRoute.context) : "url"
          }
        };
        inflightInteractionTransaction = core.startIdleTransaction(
          // eslint-disable-next-line deprecation/deprecation
          core.getCurrentHub(),
          context2,
          idleTimeout,
          finalTimeout,
          true,
          { location },
          // for use in the tracesSampler
          heartbeatInterval
        );
      };
      ["click"].forEach((type) => {
        if (types.WINDOW.document) {
          addEventListener(type, registerInteractionTransaction, { once: false, capture: true });
        }
      });
    }
    function isPerformanceEventTiming(entry) {
      return "duration" in entry;
    }
    var MAX_INTERACTIONS = 10;
    function registerInpInteractionListener(interactionIdToRouteNameMapping, latestRoute) {
      const handleEntries = ({ entries }) => {
        const client = core.getClient();
        const replay = client !== void 0 && client.getIntegrationByName !== void 0 ? client.getIntegrationByName("Replay") : void 0;
        const replayId = replay !== void 0 ? replay.getReplayId() : void 0;
        const activeTransaction = core.getActiveTransaction();
        const currentScope = core.getCurrentScope();
        const user = currentScope !== void 0 ? currentScope.getUser() : void 0;
        entries.forEach((entry) => {
          if (isPerformanceEventTiming(entry)) {
            const interactionId = entry.interactionId;
            if (interactionId === void 0) {
              return;
            }
            const existingInteraction = interactionIdToRouteNameMapping[interactionId];
            const duration = entry.duration;
            const startTime = entry.startTime;
            const keys = Object.keys(interactionIdToRouteNameMapping);
            const minInteractionId = keys.length > 0 ? keys.reduce((a3, b) => {
              return interactionIdToRouteNameMapping[a3].duration < interactionIdToRouteNameMapping[b].duration ? a3 : b;
            }) : void 0;
            if (entry.entryType === "first-input") {
              const matchingEntry = keys.map((key) => interactionIdToRouteNameMapping[key]).some((interaction) => {
                return interaction.duration === duration && interaction.startTime === startTime;
              });
              if (matchingEntry) {
                return;
              }
            }
            if (!interactionId) {
              return;
            }
            if (existingInteraction) {
              existingInteraction.duration = Math.max(existingInteraction.duration, duration);
            } else if (keys.length < MAX_INTERACTIONS || minInteractionId === void 0 || duration > interactionIdToRouteNameMapping[minInteractionId].duration) {
              const routeName = latestRoute.name;
              const parentContext = latestRoute.context;
              if (routeName && parentContext) {
                if (minInteractionId && Object.keys(interactionIdToRouteNameMapping).length >= MAX_INTERACTIONS) {
                  delete interactionIdToRouteNameMapping[minInteractionId];
                }
                interactionIdToRouteNameMapping[interactionId] = {
                  routeName,
                  duration,
                  parentContext,
                  user,
                  activeTransaction,
                  replayId,
                  startTime
                };
              }
            }
          }
        });
      };
      instrument.addPerformanceInstrumentationHandler("event", handleEntries);
      instrument.addPerformanceInstrumentationHandler("first-input", handleEntries);
    }
    function getSource(context2) {
      const sourceFromAttributes = context2.attributes && context2.attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
      const sourceFromData = context2.data && context2.data[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
      const sourceFromMetadata = context2.metadata && context2.metadata.source;
      return sourceFromAttributes || sourceFromData || sourceFromMetadata;
    }
    exports.BROWSER_TRACING_INTEGRATION_ID = BROWSER_TRACING_INTEGRATION_ID;
    exports.browserTracingIntegration = browserTracingIntegration;
    exports.getMetaContent = getMetaContent;
    exports.startBrowserTracingNavigationSpan = startBrowserTracingNavigationSpan;
    exports.startBrowserTracingPageLoadSpan = startBrowserTracingPageLoadSpan;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/extensions.js
var require_extensions = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/extensions.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    function _autoloadDatabaseIntegrations() {
      const carrier = core.getMainCarrier();
      if (!carrier.__SENTRY__) {
        return;
      }
      const packageToIntegrationMapping = {
        mongodb() {
          const integration = utils.dynamicRequire(module, "./node/integrations/mongo");
          return new integration.Mongo();
        },
        mongoose() {
          const integration = utils.dynamicRequire(module, "./node/integrations/mongo");
          return new integration.Mongo();
        },
        mysql() {
          const integration = utils.dynamicRequire(module, "./node/integrations/mysql");
          return new integration.Mysql();
        },
        pg() {
          const integration = utils.dynamicRequire(module, "./node/integrations/postgres");
          return new integration.Postgres();
        }
      };
      const mappedPackages = Object.keys(packageToIntegrationMapping).filter((moduleName) => !!utils.loadModule(moduleName)).map((pkg) => {
        try {
          return packageToIntegrationMapping[pkg]();
        } catch (e2) {
          return void 0;
        }
      }).filter((p3) => p3);
      if (mappedPackages.length > 0) {
        carrier.__SENTRY__.integrations = [...carrier.__SENTRY__.integrations || [], ...mappedPackages];
      }
    }
    function addExtensionMethods() {
      core.addTracingExtensions();
      if (utils.isNodeEnv()) {
        _autoloadDatabaseIntegrations();
      }
    }
    exports.addExtensionMethods = addExtensionMethods;
  }
});

// ../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/index.js
var require_cjs3 = __commonJS({
  "../../node_modules/.pnpm/@sentry-internal+tracing@7.120.3/node_modules/@sentry-internal/tracing/cjs/index.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var express = require_express();
    var postgres = require_postgres();
    var mysql = require_mysql();
    var mongo = require_mongo();
    var prisma = require_prisma();
    var graphql = require_graphql();
    var apollo = require_apollo();
    var lazy = require_lazy();
    var browsertracing = require_browsertracing();
    var browserTracingIntegration = require_browserTracingIntegration();
    var request = require_request();
    var instrument = require_instrument2();
    var fetch2 = require_fetch2();
    var extensions = require_extensions();
    exports.IdleTransaction = core.IdleTransaction;
    exports.Span = core.Span;
    exports.SpanStatus = core.SpanStatus;
    exports.Transaction = core.Transaction;
    exports.extractTraceparentData = core.extractTraceparentData;
    exports.getActiveTransaction = core.getActiveTransaction;
    exports.hasTracingEnabled = core.hasTracingEnabled;
    exports.spanStatusfromHttpCode = core.spanStatusfromHttpCode;
    exports.startIdleTransaction = core.startIdleTransaction;
    exports.TRACEPARENT_REGEXP = utils.TRACEPARENT_REGEXP;
    exports.stripUrlQueryAndFragment = utils.stripUrlQueryAndFragment;
    exports.Express = express.Express;
    exports.Postgres = postgres.Postgres;
    exports.Mysql = mysql.Mysql;
    exports.Mongo = mongo.Mongo;
    exports.Prisma = prisma.Prisma;
    exports.GraphQL = graphql.GraphQL;
    exports.Apollo = apollo.Apollo;
    exports.lazyLoadedNodePerformanceMonitoringIntegrations = lazy.lazyLoadedNodePerformanceMonitoringIntegrations;
    exports.BROWSER_TRACING_INTEGRATION_ID = browsertracing.BROWSER_TRACING_INTEGRATION_ID;
    exports.BrowserTracing = browsertracing.BrowserTracing;
    exports.browserTracingIntegration = browserTracingIntegration.browserTracingIntegration;
    exports.startBrowserTracingNavigationSpan = browserTracingIntegration.startBrowserTracingNavigationSpan;
    exports.startBrowserTracingPageLoadSpan = browserTracingIntegration.startBrowserTracingPageLoadSpan;
    exports.defaultRequestInstrumentationOptions = request.defaultRequestInstrumentationOptions;
    exports.instrumentOutgoingRequests = request.instrumentOutgoingRequests;
    exports.addClsInstrumentationHandler = instrument.addClsInstrumentationHandler;
    exports.addFidInstrumentationHandler = instrument.addFidInstrumentationHandler;
    exports.addLcpInstrumentationHandler = instrument.addLcpInstrumentationHandler;
    exports.addPerformanceInstrumentationHandler = instrument.addPerformanceInstrumentationHandler;
    exports.addTracingHeadersToFetchRequest = fetch2.addTracingHeadersToFetchRequest;
    exports.instrumentFetchRequest = fetch2.instrumentFetchRequest;
    exports.addExtensionMethods = extensions.addExtensionMethods;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/tracing/index.js
var require_tracing2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/tracing/index.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var tracing = require_cjs3();
    var utils = require_cjs();
    function autoDiscoverNodePerformanceMonitoringIntegrations() {
      const loadedIntegrations = tracing.lazyLoadedNodePerformanceMonitoringIntegrations.map((tryLoad) => {
        try {
          return tryLoad();
        } catch (_3) {
          return void 0;
        }
      }).filter((integration) => !!integration);
      if (loadedIntegrations.length === 0) {
        utils.logger.warn("Performance monitoring integrations could not be automatically loaded.");
      }
      return loadedIntegrations.filter((integration) => !!integration.loadDependency());
    }
    exports.autoDiscoverNodePerformanceMonitoringIntegrations = autoDiscoverNodePerformanceMonitoringIntegrations;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/client.js
var require_client = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/client.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var os = __require("os");
    var util = __require("util");
    var core = require_cjs2();
    var NodeClient = class extends core.ServerRuntimeClient {
      /**
       * Creates a new Node SDK instance.
       * @param options Configuration options for this SDK.
       */
      constructor(options) {
        core.applySdkMetadata(options, "node");
        options.transportOptions = {
          textEncoder: new util.TextEncoder(),
          ...options.transportOptions
        };
        const clientOptions = {
          ...options,
          platform: "node",
          runtime: { name: "node", version: global.process.version },
          serverName: options.serverName || global.process.env.SENTRY_NAME || os.hostname()
        };
        super(clientOptions);
      }
    };
    exports.NodeClient = NodeClient;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/proxy/base.js
var require_base2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/proxy/base.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _nullishCoalesce
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var http = __require("http");
    __require("https");
    var INTERNAL = Symbol("AgentBaseInternalState");
    var Agent = class extends http.Agent {
      // Set by `http.Agent` - missing from `@types/node`
      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((l2) => l2.indexOf("(https.js:") !== -1 || l2.indexOf("node:https:") !== -1);
      }
      createSocket(req, options, cb) {
        const connectOpts = {
          ...options,
          secureEndpoint: this.isSecureEndpoint(options)
        };
        Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => {
          if (socket instanceof http.Agent) {
            return socket.addRequest(req, connectOpts);
          }
          this[INTERNAL].currentSocket = socket;
          super.createSocket(req, options, cb);
        }, cb);
      }
      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 _nullishCoalesce(this[INTERNAL].defaultPort, () => this.protocol === "https:" ? 443 : 80);
      }
      set defaultPort(v3) {
        if (this[INTERNAL]) {
          this[INTERNAL].defaultPort = v3;
        }
      }
      get protocol() {
        return _nullishCoalesce(this[INTERNAL].protocol, () => this.isSecureEndpoint() ? "https:" : "http:");
      }
      set protocol(v3) {
        if (this[INTERNAL]) {
          this[INTERNAL].protocol = v3;
        }
      }
    };
    exports.Agent = Agent;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/proxy/parse-proxy-response.js
var require_parse_proxy_response = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/proxy/parse-proxy-response.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    function debug(...args) {
      utils.logger.log("[https-proxy-agent:parse-proxy-response]", ...args);
    }
    function parseProxyResponse(socket) {
      return new Promise((resolve2, 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();
          resolve2({
            connect: {
              statusCode,
              statusText,
              headers
            },
            buffered
          });
        }
        socket.on("error", onerror);
        socket.on("end", onend);
        read();
      });
    }
    exports.parseProxyResponse = parseProxyResponse;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/proxy/index.js
var require_proxy = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/proxy/index.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _nullishCoalesce,
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var net = __require("net");
    var tls = __require("tls");
    var url = __require("url");
    var utils = require_cjs();
    var base = require_base2();
    var parseProxyResponse = require_parse_proxy_response();
    function debug(...args) {
      utils.logger.log("[https-proxy-agent]", ...args);
    }
    var HttpsProxyAgent = class extends base.Agent {
      static __initStatic() {
        this.protocols = ["http", "https"];
      }
      constructor(proxy, opts) {
        super(opts);
        this.options = {};
        this.proxy = typeof proxy === "string" ? new url.URL(proxy) : proxy;
        this.proxyHeaders = _nullishCoalesce(_optionalChain([opts, "optionalAccess", (_22) => _22.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);
          const servername = this.connectOpts.servername || this.connectOpts.host;
          socket = tls.connect({
            ...this.connectOpts,
            servername: servername && net.isIP(servername) ? void 0 : servername
          });
        } 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 = parseProxyResponse.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");
            const servername = opts.servername || opts.host;
            return tls.connect({
              ...omit(opts, "host", "path", "port"),
              socket,
              servername: net.isIP(servername) ? void 0 : servername
            });
          }
          return socket;
        }
        socket.destroy();
        const fakeSocket = new net.Socket({ writable: false });
        fakeSocket.readable = true;
        req.once("socket", (s2) => {
          debug("Replaying proxy buffer for failed request");
          s2.push(buffered);
          s2.push(null);
        });
        return fakeSocket;
      }
    };
    HttpsProxyAgent.__initStatic();
    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;
    }
    exports.HttpsProxyAgent = HttpsProxyAgent;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/transports/http.js
var require_http = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/transports/http.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _nullishCoalesce
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var http = __require("http");
    var https = __require("https");
    var stream = __require("stream");
    var url = __require("url");
    var zlib = __require("zlib");
    var core = require_cjs2();
    var utils = require_cjs();
    var index = require_proxy();
    var GZIP_THRESHOLD = 1024 * 32;
    function streamFromBody(body) {
      return new stream.Readable({
        read() {
          this.push(body);
          this.push(null);
        }
      });
    }
    function makeNodeTransport(options) {
      let urlSegments;
      try {
        urlSegments = new url.URL(options.url);
      } catch (e2) {
        utils.consoleSandbox(() => {
          console.warn(
            "[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used."
          );
        });
        return core.createTransport(options, () => Promise.resolve({}));
      }
      const isHttps = urlSegments.protocol === "https:";
      const proxy = applyNoProxyOption(
        urlSegments,
        options.proxy || (isHttps ? process.env.https_proxy : void 0) || process.env.http_proxy
      );
      const nativeHttpModule = isHttps ? https : http;
      const keepAlive = options.keepAlive === void 0 ? false : options.keepAlive;
      const agent = proxy ? new index.HttpsProxyAgent(proxy) : new nativeHttpModule.Agent({ keepAlive, maxSockets: 30, timeout: 2e3 });
      const requestExecutor = createRequestExecutor(options, _nullishCoalesce(options.httpModule, () => nativeHttpModule), agent);
      return core.createTransport(options, requestExecutor);
    }
    function applyNoProxyOption(transportUrlSegments, proxy) {
      const { no_proxy } = process.env;
      const urlIsExemptFromProxy = no_proxy && no_proxy.split(",").some(
        (exemption) => transportUrlSegments.host.endsWith(exemption) || transportUrlSegments.hostname.endsWith(exemption)
      );
      if (urlIsExemptFromProxy) {
        return void 0;
      } else {
        return proxy;
      }
    }
    function createRequestExecutor(options, httpModule, agent) {
      const { hostname, pathname, port, protocol, search } = new url.URL(options.url);
      return function makeRequest(request) {
        return new Promise((resolve2, reject) => {
          let body = streamFromBody(request.body);
          const headers = { ...options.headers };
          if (request.body.length > GZIP_THRESHOLD) {
            headers["content-encoding"] = "gzip";
            body = body.pipe(zlib.createGzip());
          }
          const req = httpModule.request(
            {
              method: "POST",
              agent,
              headers,
              hostname,
              path: `${pathname}${search}`,
              port,
              protocol,
              ca: options.caCerts
            },
            (res) => {
              res.on("data", () => {
              });
              res.on("end", () => {
              });
              res.setEncoding("utf8");
              const retryAfterHeader = _nullishCoalesce(res.headers["retry-after"], () => null);
              const rateLimitsHeader = _nullishCoalesce(res.headers["x-sentry-rate-limits"], () => null);
              resolve2({
                statusCode: res.statusCode,
                headers: {
                  "retry-after": retryAfterHeader,
                  "x-sentry-rate-limits": Array.isArray(rateLimitsHeader) ? rateLimitsHeader[0] : rateLimitsHeader
                }
              });
            }
          );
          req.on("error", reject);
          body.pipe(req);
        });
      };
    }
    exports.makeNodeTransport = makeNodeTransport;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/nodeVersion.js
var require_nodeVersion = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/nodeVersion.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var NODE_VERSION = utils.parseSemver(process.versions.node);
    exports.NODE_VERSION = NODE_VERSION;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/async/domain.js
var require_domain = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/async/domain.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var domain = __require("domain");
    var core = require_cjs2();
    function getActiveDomain() {
      return domain.active;
    }
    function getCurrentHub() {
      const activeDomain = getActiveDomain();
      if (!activeDomain) {
        return void 0;
      }
      core.ensureHubOnCarrier(activeDomain);
      return core.getHubFromCarrier(activeDomain);
    }
    function createNewHub(parent) {
      const carrier = {};
      core.ensureHubOnCarrier(carrier, parent);
      return core.getHubFromCarrier(carrier);
    }
    function runWithAsyncContext(callback, options) {
      const activeDomain = getActiveDomain();
      if (activeDomain && _optionalChain([options, "optionalAccess", (_3) => _3.reuseExisting])) {
        return callback();
      }
      const local = domain.create();
      const parentHub = activeDomain ? core.getHubFromCarrier(activeDomain) : void 0;
      const newHub = createNewHub(parentHub);
      core.setHubOnCarrier(local, newHub);
      return local.bind(() => {
        return callback();
      })();
    }
    function setDomainAsyncContextStrategy() {
      core.setAsyncContextStrategy({ getCurrentHub, runWithAsyncContext });
    }
    exports.setDomainAsyncContextStrategy = setDomainAsyncContextStrategy;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/async/hooks.js
var require_hooks = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/async/hooks.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var async_hooks = __require("async_hooks");
    var asyncStorage;
    function setHooksAsyncContextStrategy() {
      if (!asyncStorage) {
        asyncStorage = new async_hooks.AsyncLocalStorage();
      }
      function getCurrentHub() {
        return asyncStorage.getStore();
      }
      function createNewHub(parent) {
        const carrier = {};
        core.ensureHubOnCarrier(carrier, parent);
        return core.getHubFromCarrier(carrier);
      }
      function runWithAsyncContext(callback, options) {
        const existingHub = getCurrentHub();
        if (existingHub && _optionalChain([options, "optionalAccess", (_3) => _3.reuseExisting])) {
          return callback();
        }
        const newHub = createNewHub(existingHub);
        return asyncStorage.run(newHub, () => {
          return callback();
        });
      }
      core.setAsyncContextStrategy({ getCurrentHub, runWithAsyncContext });
    }
    exports.setHooksAsyncContextStrategy = setHooksAsyncContextStrategy;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/async/index.js
var require_async = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/async/index.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var nodeVersion = require_nodeVersion();
    var domain = require_domain();
    var hooks = require_hooks();
    function setNodeAsyncContextStrategy() {
      if (nodeVersion.NODE_VERSION.major >= 14) {
        hooks.setHooksAsyncContextStrategy();
      } else {
        domain.setDomainAsyncContextStrategy();
      }
    }
    exports.setNodeAsyncContextStrategy = setNodeAsyncContextStrategy;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/console.js
var require_console2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/console.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var util = __require("util");
    var core = require_cjs2();
    var utils = require_cjs();
    var INTEGRATION_NAME = "Console";
    var _consoleIntegration = () => {
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        setup(client) {
          utils.addConsoleInstrumentationHandler(({ args, level }) => {
            if (core.getClient() !== client) {
              return;
            }
            core.addBreadcrumb(
              {
                category: "console",
                level: utils.severityLevelFromString(level),
                message: util.format.apply(void 0, args)
              },
              {
                input: [...args],
                level
              }
            );
          });
        }
      };
    };
    var consoleIntegration = core.defineIntegration(_consoleIntegration);
    var Console = core.convertIntegrationFnToClass(INTEGRATION_NAME, consoleIntegration);
    exports.Console = Console;
    exports.consoleIntegration = consoleIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/context.js
var require_context = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/context.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var child_process = __require("child_process");
    var fs3 = __require("fs");
    var os = __require("os");
    var path2 = __require("path");
    var util = __require("util");
    var core = require_cjs2();
    var readFileAsync = util.promisify(fs3.readFile);
    var readDirAsync = util.promisify(fs3.readdir);
    var INTEGRATION_NAME = "Context";
    var _nodeContextIntegration = (options = {}) => {
      let cachedContext;
      const _options = {
        app: true,
        os: true,
        device: true,
        culture: true,
        cloudResource: true,
        ...options
      };
      async function addContext(event) {
        if (cachedContext === void 0) {
          cachedContext = _getContexts();
        }
        const updatedContext = _updateContext(await cachedContext);
        event.contexts = {
          ...event.contexts,
          app: { ...updatedContext.app, ..._optionalChain([event, "access", (_3) => _3.contexts, "optionalAccess", (_22) => _22.app]) },
          os: { ...updatedContext.os, ..._optionalChain([event, "access", (_3) => _3.contexts, "optionalAccess", (_4) => _4.os]) },
          device: { ...updatedContext.device, ..._optionalChain([event, "access", (_5) => _5.contexts, "optionalAccess", (_6) => _6.device]) },
          culture: { ...updatedContext.culture, ..._optionalChain([event, "access", (_7) => _7.contexts, "optionalAccess", (_8) => _8.culture]) },
          cloud_resource: { ...updatedContext.cloud_resource, ..._optionalChain([event, "access", (_9) => _9.contexts, "optionalAccess", (_10) => _10.cloud_resource]) }
        };
        return event;
      }
      async function _getContexts() {
        const contexts = {};
        if (_options.os) {
          contexts.os = await getOsContext();
        }
        if (_options.app) {
          contexts.app = getAppContext();
        }
        if (_options.device) {
          contexts.device = getDeviceContext(_options.device);
        }
        if (_options.culture) {
          const culture = getCultureContext();
          if (culture) {
            contexts.culture = culture;
          }
        }
        if (_options.cloudResource) {
          contexts.cloud_resource = getCloudResourceContext();
        }
        return contexts;
      }
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        processEvent(event) {
          return addContext(event);
        }
      };
    };
    var nodeContextIntegration = core.defineIntegration(_nodeContextIntegration);
    var Context = core.convertIntegrationFnToClass(INTEGRATION_NAME, nodeContextIntegration);
    function _updateContext(contexts) {
      if (_optionalChain([contexts, "optionalAccess", (_11) => _11.app, "optionalAccess", (_12) => _12.app_memory])) {
        contexts.app.app_memory = process.memoryUsage().rss;
      }
      if (_optionalChain([contexts, "optionalAccess", (_13) => _13.device, "optionalAccess", (_14) => _14.free_memory])) {
        contexts.device.free_memory = os.freemem();
      }
      return contexts;
    }
    async function getOsContext() {
      const platformId = os.platform();
      switch (platformId) {
        case "darwin":
          return getDarwinInfo();
        case "linux":
          return getLinuxInfo();
        default:
          return {
            name: PLATFORM_NAMES[platformId] || platformId,
            version: os.release()
          };
      }
    }
    function getCultureContext() {
      try {
        if (typeof process.versions.icu !== "string") {
          return;
        }
        const january = /* @__PURE__ */ new Date(9e8);
        const spanish = new Intl.DateTimeFormat("es", { month: "long" });
        if (spanish.format(january) === "enero") {
          const options = Intl.DateTimeFormat().resolvedOptions();
          return {
            locale: options.locale,
            timezone: options.timeZone
          };
        }
      } catch (err) {
      }
      return;
    }
    function getAppContext() {
      const app_memory = process.memoryUsage().rss;
      const app_start_time = new Date(Date.now() - process.uptime() * 1e3).toISOString();
      return { app_start_time, app_memory };
    }
    function getDeviceContext(deviceOpt) {
      const device = {};
      let uptime;
      try {
        uptime = os.uptime && os.uptime();
      } catch (e2) {
      }
      if (typeof uptime === "number") {
        device.boot_time = new Date(Date.now() - uptime * 1e3).toISOString();
      }
      device.arch = os.arch();
      if (deviceOpt === true || deviceOpt.memory) {
        device.memory_size = os.totalmem();
        device.free_memory = os.freemem();
      }
      if (deviceOpt === true || deviceOpt.cpu) {
        const cpuInfo = os.cpus();
        if (cpuInfo && cpuInfo.length) {
          const firstCpu = cpuInfo[0];
          device.processor_count = cpuInfo.length;
          device.cpu_description = firstCpu.model;
          device.processor_frequency = firstCpu.speed;
        }
      }
      return device;
    }
    var PLATFORM_NAMES = {
      aix: "IBM AIX",
      freebsd: "FreeBSD",
      openbsd: "OpenBSD",
      sunos: "SunOS",
      win32: "Windows"
    };
    var LINUX_DISTROS = [
      { name: "fedora-release", distros: ["Fedora"] },
      { name: "redhat-release", distros: ["Red Hat Linux", "Centos"] },
      { name: "redhat_version", distros: ["Red Hat Linux"] },
      { name: "SuSE-release", distros: ["SUSE Linux"] },
      { name: "lsb-release", distros: ["Ubuntu Linux", "Arch Linux"] },
      { name: "debian_version", distros: ["Debian"] },
      { name: "debian_release", distros: ["Debian"] },
      { name: "arch-release", distros: ["Arch Linux"] },
      { name: "gentoo-release", distros: ["Gentoo Linux"] },
      { name: "novell-release", distros: ["SUSE Linux"] },
      { name: "alpine-release", distros: ["Alpine Linux"] }
    ];
    var LINUX_VERSIONS = {
      alpine: (content) => content,
      arch: (content) => matchFirst(/distrib_release=(.*)/, content),
      centos: (content) => matchFirst(/release ([^ ]+)/, content),
      debian: (content) => content,
      fedora: (content) => matchFirst(/release (..)/, content),
      mint: (content) => matchFirst(/distrib_release=(.*)/, content),
      red: (content) => matchFirst(/release ([^ ]+)/, content),
      suse: (content) => matchFirst(/VERSION = (.*)\n/, content),
      ubuntu: (content) => matchFirst(/distrib_release=(.*)/, content)
    };
    function matchFirst(regex2, text) {
      const match = regex2.exec(text);
      return match ? match[1] : void 0;
    }
    async function getDarwinInfo() {
      const darwinInfo = {
        kernel_version: os.release(),
        name: "Mac OS X",
        version: `10.${Number(os.release().split(".")[0]) - 4}`
      };
      try {
        const output = await new Promise((resolve2, reject) => {
          child_process.execFile("/usr/bin/sw_vers", (error, stdout2) => {
            if (error) {
              reject(error);
              return;
            }
            resolve2(stdout2);
          });
        });
        darwinInfo.name = matchFirst(/^ProductName:\s+(.*)$/m, output);
        darwinInfo.version = matchFirst(/^ProductVersion:\s+(.*)$/m, output);
        darwinInfo.build = matchFirst(/^BuildVersion:\s+(.*)$/m, output);
      } catch (e2) {
      }
      return darwinInfo;
    }
    function getLinuxDistroId(name) {
      return name.split(" ")[0].toLowerCase();
    }
    async function getLinuxInfo() {
      const linuxInfo = {
        kernel_version: os.release(),
        name: "Linux"
      };
      try {
        const etcFiles = await readDirAsync("/etc");
        const distroFile = LINUX_DISTROS.find((file) => etcFiles.includes(file.name));
        if (!distroFile) {
          return linuxInfo;
        }
        const distroPath = path2.join("/etc", distroFile.name);
        const contents = (await readFileAsync(distroPath, { encoding: "utf-8" })).toLowerCase();
        const { distros } = distroFile;
        linuxInfo.name = distros.find((d2) => contents.indexOf(getLinuxDistroId(d2)) >= 0) || distros[0];
        const id = getLinuxDistroId(linuxInfo.name);
        linuxInfo.version = LINUX_VERSIONS[id](contents);
      } catch (e2) {
      }
      return linuxInfo;
    }
    function getCloudResourceContext() {
      if (process.env.VERCEL) {
        return {
          "cloud.provider": "vercel",
          "cloud.region": process.env.VERCEL_REGION
        };
      } else if (process.env.AWS_REGION) {
        return {
          "cloud.provider": "aws",
          "cloud.region": process.env.AWS_REGION,
          "cloud.platform": process.env.AWS_EXECUTION_ENV
        };
      } else if (process.env.GCP_PROJECT) {
        return {
          "cloud.provider": "gcp"
        };
      } else if (process.env.ALIYUN_REGION_ID) {
        return {
          "cloud.provider": "alibaba_cloud",
          "cloud.region": process.env.ALIYUN_REGION_ID
        };
      } else if (process.env.WEBSITE_SITE_NAME && process.env.REGION_NAME) {
        return {
          "cloud.provider": "azure",
          "cloud.region": process.env.REGION_NAME
        };
      } else if (process.env.IBM_CLOUD_REGION) {
        return {
          "cloud.provider": "ibm_cloud",
          "cloud.region": process.env.IBM_CLOUD_REGION
        };
      } else if (process.env.TENCENTCLOUD_REGION) {
        return {
          "cloud.provider": "tencent_cloud",
          "cloud.region": process.env.TENCENTCLOUD_REGION,
          "cloud.account.id": process.env.TENCENTCLOUD_APPID,
          "cloud.availability_zone": process.env.TENCENTCLOUD_ZONE
        };
      } else if (process.env.NETLIFY) {
        return {
          "cloud.provider": "netlify"
        };
      } else if (process.env.FLY_REGION) {
        return {
          "cloud.provider": "fly.io",
          "cloud.region": process.env.FLY_REGION
        };
      } else if (process.env.DYNO) {
        return {
          "cloud.provider": "heroku"
        };
      } else {
        return void 0;
      }
    }
    exports.Context = Context;
    exports.getDeviceContext = getDeviceContext;
    exports.nodeContextIntegration = nodeContextIntegration;
    exports.readDirAsync = readDirAsync;
    exports.readFileAsync = readFileAsync;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/contextlines.js
var require_contextlines = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/contextlines.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var fs3 = __require("fs");
    var core = require_cjs2();
    var utils = require_cjs();
    var FILE_CONTENT_CACHE = new utils.LRUMap(100);
    var DEFAULT_LINES_OF_CONTEXT = 7;
    var INTEGRATION_NAME = "ContextLines";
    function readTextFileAsync(path2) {
      return new Promise((resolve2, reject) => {
        fs3.readFile(path2, "utf8", (err, data) => {
          if (err)
            reject(err);
          else
            resolve2(data);
        });
      });
    }
    var _contextLinesIntegration = (options = {}) => {
      const contextLines = options.frameContextLines !== void 0 ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT;
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        processEvent(event) {
          return addSourceContext(event, contextLines);
        }
      };
    };
    var contextLinesIntegration = core.defineIntegration(_contextLinesIntegration);
    var ContextLines = core.convertIntegrationFnToClass(INTEGRATION_NAME, contextLinesIntegration);
    async function addSourceContext(event, contextLines) {
      const enqueuedReadSourceFileTasks = {};
      const readSourceFileTasks = [];
      if (contextLines > 0 && _optionalChain([event, "access", (_22) => _22.exception, "optionalAccess", (_3) => _3.values])) {
        for (const exception of event.exception.values) {
          if (!_optionalChain([exception, "access", (_4) => _4.stacktrace, "optionalAccess", (_5) => _5.frames])) {
            continue;
          }
          for (let i2 = exception.stacktrace.frames.length - 1; i2 >= 0; i2--) {
            const frame = exception.stacktrace.frames[i2];
            if (frame.filename && !enqueuedReadSourceFileTasks[frame.filename] && !FILE_CONTENT_CACHE.get(frame.filename)) {
              readSourceFileTasks.push(_readSourceFile(frame.filename));
              enqueuedReadSourceFileTasks[frame.filename] = 1;
            }
          }
        }
      }
      if (readSourceFileTasks.length > 0) {
        await Promise.all(readSourceFileTasks);
      }
      if (contextLines > 0 && _optionalChain([event, "access", (_6) => _6.exception, "optionalAccess", (_7) => _7.values])) {
        for (const exception of event.exception.values) {
          if (exception.stacktrace && exception.stacktrace.frames) {
            await addSourceContextToFrames(exception.stacktrace.frames, contextLines);
          }
        }
      }
      return event;
    }
    function addSourceContextToFrames(frames, contextLines) {
      for (const frame of frames) {
        if (frame.filename && frame.context_line === void 0) {
          const sourceFileLines = FILE_CONTENT_CACHE.get(frame.filename);
          if (sourceFileLines) {
            try {
              utils.addContextToFrame(sourceFileLines, frame, contextLines);
            } catch (e2) {
            }
          }
        }
      }
    }
    async function _readSourceFile(filename) {
      const cachedFile = FILE_CONTENT_CACHE.get(filename);
      if (cachedFile === null) {
        return null;
      }
      if (cachedFile !== void 0) {
        return cachedFile;
      }
      let content = null;
      try {
        const rawFileContents = await readTextFileAsync(filename);
        content = rawFileContents.split("\n");
      } catch (_3) {
      }
      FILE_CONTENT_CACHE.set(filename, content);
      return content;
    }
    exports.ContextLines = ContextLines;
    exports.contextLinesIntegration = contextLinesIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/debug-build.js
var require_debug_build4 = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/debug-build.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
    exports.DEBUG_BUILD = DEBUG_BUILD;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/utils/http.js
var require_http2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/utils/http.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var url = __require("url");
    var nodeVersion = require_nodeVersion();
    function extractRawUrl(requestOptions) {
      const { protocol, hostname, port } = parseRequestOptions(requestOptions);
      const path2 = requestOptions.path ? requestOptions.path : "/";
      return `${protocol}//${hostname}${port}${path2}`;
    }
    function extractUrl(requestOptions) {
      const { protocol, hostname, port } = parseRequestOptions(requestOptions);
      const path2 = requestOptions.pathname || "/";
      const authority = requestOptions.auth ? redactAuthority(requestOptions.auth) : "";
      return `${protocol}//${authority}${hostname}${port}${path2}`;
    }
    function redactAuthority(auth) {
      const [user, password] = auth.split(":");
      return `${user ? "[Filtered]" : ""}:${password ? "[Filtered]" : ""}@`;
    }
    function cleanSpanDescription(description, requestOptions, request) {
      if (!description) {
        return description;
      }
      let [method, requestUrl] = description.split(" ");
      if (requestOptions.host && !requestOptions.protocol) {
        requestOptions.protocol = _optionalChain([request, "optionalAccess", (_3) => _3.agent, "optionalAccess", (_22) => _22.protocol]);
        requestUrl = extractUrl(requestOptions);
      }
      if (_optionalChain([requestUrl, "optionalAccess", (_3) => _3.startsWith, "call", (_4) => _4("///")])) {
        requestUrl = requestUrl.slice(2);
      }
      return `${method} ${requestUrl}`;
    }
    function urlToOptions(url2) {
      const options = {
        protocol: url2.protocol,
        hostname: typeof url2.hostname === "string" && url2.hostname.startsWith("[") ? url2.hostname.slice(1, -1) : url2.hostname,
        hash: url2.hash,
        search: url2.search,
        pathname: url2.pathname,
        path: `${url2.pathname || ""}${url2.search || ""}`,
        href: url2.href
      };
      if (url2.port !== "") {
        options.port = Number(url2.port);
      }
      if (url2.username || url2.password) {
        options.auth = `${url2.username}:${url2.password}`;
      }
      return options;
    }
    function normalizeRequestArgs(httpModule, requestArgs) {
      let callback, requestOptions;
      if (typeof requestArgs[requestArgs.length - 1] === "function") {
        callback = requestArgs.pop();
      }
      if (typeof requestArgs[0] === "string") {
        requestOptions = urlToOptions(new url.URL(requestArgs[0]));
      } else if (requestArgs[0] instanceof url.URL) {
        requestOptions = urlToOptions(requestArgs[0]);
      } else {
        requestOptions = requestArgs[0];
        try {
          const parsed = new url.URL(
            requestOptions.path || "",
            `${requestOptions.protocol || "http:"}//${requestOptions.hostname}`
          );
          requestOptions = {
            pathname: parsed.pathname,
            search: parsed.search,
            hash: parsed.hash,
            ...requestOptions
          };
        } catch (e2) {
        }
      }
      if (requestArgs.length === 2) {
        requestOptions = { ...requestOptions, ...requestArgs[1] };
      }
      if (requestOptions.protocol === void 0) {
        if (nodeVersion.NODE_VERSION.major > 8) {
          requestOptions.protocol = _optionalChain([_optionalChain([httpModule, "optionalAccess", (_5) => _5.globalAgent]), "optionalAccess", (_6) => _6.protocol]) || _optionalChain([requestOptions.agent, "optionalAccess", (_7) => _7.protocol]) || _optionalChain([requestOptions._defaultAgent, "optionalAccess", (_8) => _8.protocol]);
        } else {
          requestOptions.protocol = _optionalChain([requestOptions.agent, "optionalAccess", (_9) => _9.protocol]) || _optionalChain([requestOptions._defaultAgent, "optionalAccess", (_10) => _10.protocol]) || _optionalChain([_optionalChain([httpModule, "optionalAccess", (_11) => _11.globalAgent]), "optionalAccess", (_12) => _12.protocol]);
        }
      }
      if (callback) {
        return [requestOptions, callback];
      } else {
        return [requestOptions];
      }
    }
    function parseRequestOptions(requestOptions) {
      const protocol = requestOptions.protocol || "";
      const hostname = requestOptions.hostname || requestOptions.host || "";
      const port = !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 || /^(.*):(\d+)$/.test(hostname) ? "" : `:${requestOptions.port}`;
      return { protocol, hostname, port };
    }
    exports.cleanSpanDescription = cleanSpanDescription;
    exports.extractRawUrl = extractRawUrl;
    exports.extractUrl = extractUrl;
    exports.normalizeRequestArgs = normalizeRequestArgs;
    exports.urlToOptions = urlToOptions;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/http.js
var require_http3 = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/http.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var debugBuild = require_debug_build4();
    var nodeVersion = require_nodeVersion();
    var http = require_http2();
    var _httpIntegration = (options = {}) => {
      const { breadcrumbs, tracing, shouldCreateSpanForRequest } = options;
      const convertedOptions = {
        breadcrumbs,
        tracing: tracing === false ? false : utils.dropUndefinedKeys({
          // If tracing is forced to `true`, we don't want to set `enableIfHasTracingEnabled`
          enableIfHasTracingEnabled: tracing === true ? void 0 : true,
          shouldCreateSpanForRequest
        })
      };
      return new Http(convertedOptions);
    };
    var httpIntegration = core.defineIntegration(_httpIntegration);
    var Http = class _Http {
      /**
       * @inheritDoc
       */
      static __initStatic() {
        this.id = "Http";
      }
      /**
       * @inheritDoc
       */
      // eslint-disable-next-line deprecation/deprecation
      __init() {
        this.name = _Http.id;
      }
      /**
       * @inheritDoc
       */
      constructor(options = {}) {
        _Http.prototype.__init.call(this);
        this._breadcrumbs = typeof options.breadcrumbs === "undefined" ? true : options.breadcrumbs;
        this._tracing = !options.tracing ? void 0 : options.tracing === true ? {} : options.tracing;
      }
      /**
       * @inheritDoc
       */
      setupOnce(_addGlobalEventProcessor, setupOnceGetCurrentHub) {
        const clientOptions = _optionalChain([setupOnceGetCurrentHub, "call", (_3) => _3(), "access", (_22) => _22.getClient, "call", (_3) => _3(), "optionalAccess", (_4) => _4.getOptions, "call", (_5) => _5()]);
        const shouldCreateSpans = _shouldCreateSpans(this._tracing, clientOptions);
        if (!this._breadcrumbs && !shouldCreateSpans) {
          return;
        }
        if (clientOptions && clientOptions.instrumenter !== "sentry") {
          debugBuild.DEBUG_BUILD && utils.logger.log("HTTP Integration is skipped because of instrumenter configuration.");
          return;
        }
        const shouldCreateSpanForRequest = _getShouldCreateSpanForRequest(shouldCreateSpans, this._tracing, clientOptions);
        const tracePropagationTargets = _optionalChain([clientOptions, "optionalAccess", (_6) => _6.tracePropagationTargets]) || _optionalChain([this, "access", (_7) => _7._tracing, "optionalAccess", (_8) => _8.tracePropagationTargets]);
        const httpModule = __require("http");
        const wrappedHttpHandlerMaker = _createWrappedRequestMethodFactory(
          httpModule,
          this._breadcrumbs,
          shouldCreateSpanForRequest,
          tracePropagationTargets
        );
        utils.fill(httpModule, "get", wrappedHttpHandlerMaker);
        utils.fill(httpModule, "request", wrappedHttpHandlerMaker);
        if (nodeVersion.NODE_VERSION.major > 8) {
          const httpsModule = __require("https");
          const wrappedHttpsHandlerMaker = _createWrappedRequestMethodFactory(
            httpsModule,
            this._breadcrumbs,
            shouldCreateSpanForRequest,
            tracePropagationTargets
          );
          utils.fill(httpsModule, "get", wrappedHttpsHandlerMaker);
          utils.fill(httpsModule, "request", wrappedHttpsHandlerMaker);
        }
      }
    };
    Http.__initStatic();
    function _createWrappedRequestMethodFactory(httpModule, breadcrumbsEnabled, shouldCreateSpanForRequest, tracePropagationTargets) {
      const createSpanUrlMap = new utils.LRUMap(100);
      const headersUrlMap = new utils.LRUMap(100);
      const shouldCreateSpan = (url) => {
        if (shouldCreateSpanForRequest === void 0) {
          return true;
        }
        const cachedDecision = createSpanUrlMap.get(url);
        if (cachedDecision !== void 0) {
          return cachedDecision;
        }
        const decision = shouldCreateSpanForRequest(url);
        createSpanUrlMap.set(url, decision);
        return decision;
      };
      const shouldAttachTraceData = (url) => {
        if (tracePropagationTargets === void 0) {
          return true;
        }
        const cachedDecision = headersUrlMap.get(url);
        if (cachedDecision !== void 0) {
          return cachedDecision;
        }
        const decision = utils.stringMatchesSomePattern(url, tracePropagationTargets);
        headersUrlMap.set(url, decision);
        return decision;
      };
      function addRequestBreadcrumb(event, requestSpanData, req, res) {
        if (!core.getCurrentHub().getIntegration(Http)) {
          return;
        }
        core.addBreadcrumb(
          {
            category: "http",
            data: {
              status_code: res && res.statusCode,
              ...requestSpanData
            },
            type: "http"
          },
          {
            event,
            request: req,
            response: res
          }
        );
      }
      return function wrappedRequestMethodFactory(originalRequestMethod) {
        return function wrappedMethod(...args) {
          const requestArgs = http.normalizeRequestArgs(httpModule, args);
          const requestOptions = requestArgs[0];
          const rawRequestUrl = http.extractRawUrl(requestOptions);
          const requestUrl = http.extractUrl(requestOptions);
          const client = core.getClient();
          if (core.isSentryRequestUrl(requestUrl, client)) {
            return originalRequestMethod.apply(httpModule, requestArgs);
          }
          const scope = core.getCurrentScope();
          const isolationScope = core.getIsolationScope();
          const parentSpan = core.getActiveSpan();
          const data = getRequestSpanData(requestUrl, requestOptions);
          const requestSpan = shouldCreateSpan(rawRequestUrl) ? (
            // eslint-disable-next-line deprecation/deprecation
            _optionalChain([parentSpan, "optionalAccess", (_9) => _9.startChild, "call", (_10) => _10({
              op: "http.client",
              origin: "auto.http.node.http",
              description: `${data["http.method"]} ${data.url}`,
              data
            })])
          ) : void 0;
          if (client && shouldAttachTraceData(rawRequestUrl)) {
            const { traceId, spanId, sampled, dsc } = {
              ...isolationScope.getPropagationContext(),
              ...scope.getPropagationContext()
            };
            const sentryTraceHeader = requestSpan ? core.spanToTraceHeader(requestSpan) : utils.generateSentryTraceHeader(traceId, spanId, sampled);
            const sentryBaggageHeader = utils.dynamicSamplingContextToSentryBaggageHeader(
              dsc || (requestSpan ? core.getDynamicSamplingContextFromSpan(requestSpan) : core.getDynamicSamplingContextFromClient(traceId, client, scope))
            );
            addHeadersToRequestOptions(requestOptions, requestUrl, sentryTraceHeader, sentryBaggageHeader);
          } else {
            debugBuild.DEBUG_BUILD && utils.logger.log(
              `[Tracing] Not adding sentry-trace header to outgoing request (${requestUrl}) due to mismatching tracePropagationTargets option.`
            );
          }
          return originalRequestMethod.apply(httpModule, requestArgs).once("response", function(res) {
            const req = this;
            if (breadcrumbsEnabled) {
              addRequestBreadcrumb("response", data, req, res);
            }
            if (requestSpan) {
              if (res.statusCode) {
                core.setHttpStatus(requestSpan, res.statusCode);
              }
              requestSpan.updateName(
                http.cleanSpanDescription(core.spanToJSON(requestSpan).description || "", requestOptions, req) || ""
              );
              requestSpan.end();
            }
          }).once("error", function() {
            const req = this;
            if (breadcrumbsEnabled) {
              addRequestBreadcrumb("error", data, req);
            }
            if (requestSpan) {
              core.setHttpStatus(requestSpan, 500);
              requestSpan.updateName(
                http.cleanSpanDescription(core.spanToJSON(requestSpan).description || "", requestOptions, req) || ""
              );
              requestSpan.end();
            }
          });
        };
      };
    }
    function addHeadersToRequestOptions(requestOptions, requestUrl, sentryTraceHeader, sentryBaggageHeader) {
      const headers = requestOptions.headers || {};
      if (headers["sentry-trace"]) {
        return;
      }
      debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Adding sentry-trace header ${sentryTraceHeader} to outgoing request to "${requestUrl}": `);
      requestOptions.headers = {
        ...requestOptions.headers,
        "sentry-trace": sentryTraceHeader,
        // Setting a header to `undefined` will crash in node so we only set the baggage header when it's defined
        ...sentryBaggageHeader && sentryBaggageHeader.length > 0 && { baggage: normalizeBaggageHeader(requestOptions, sentryBaggageHeader) }
      };
    }
    function getRequestSpanData(requestUrl, requestOptions) {
      const method = requestOptions.method || "GET";
      const data = {
        url: requestUrl,
        "http.method": method
      };
      if (requestOptions.hash) {
        data["http.fragment"] = requestOptions.hash.substring(1);
      }
      if (requestOptions.search) {
        data["http.query"] = requestOptions.search.substring(1);
      }
      return data;
    }
    function normalizeBaggageHeader(requestOptions, sentryBaggageHeader) {
      if (!requestOptions.headers || !requestOptions.headers.baggage) {
        return sentryBaggageHeader;
      } else if (!sentryBaggageHeader) {
        return requestOptions.headers.baggage;
      } else if (Array.isArray(requestOptions.headers.baggage)) {
        return [...requestOptions.headers.baggage, sentryBaggageHeader];
      }
      return [requestOptions.headers.baggage, sentryBaggageHeader];
    }
    function _shouldCreateSpans(tracingOptions, clientOptions) {
      return tracingOptions === void 0 ? false : tracingOptions.enableIfHasTracingEnabled ? core.hasTracingEnabled(clientOptions) : true;
    }
    function _getShouldCreateSpanForRequest(shouldCreateSpans, tracingOptions, clientOptions) {
      const handler = shouldCreateSpans ? (
        // eslint-disable-next-line deprecation/deprecation
        _optionalChain([tracingOptions, "optionalAccess", (_11) => _11.shouldCreateSpanForRequest]) || _optionalChain([clientOptions, "optionalAccess", (_12) => _12.shouldCreateSpanForRequest])
      ) : () => false;
      return handler;
    }
    exports.Http = Http;
    exports._getShouldCreateSpanForRequest = _getShouldCreateSpanForRequest;
    exports._shouldCreateSpans = _shouldCreateSpans;
    exports.httpIntegration = httpIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/local-variables/common.js
var require_common = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/local-variables/common.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    function createRateLimiter(maxPerSecond, enable, disable) {
      let count = 0;
      let retrySeconds = 5;
      let disabledTimeout = 0;
      setInterval(() => {
        if (disabledTimeout === 0) {
          if (count > maxPerSecond) {
            retrySeconds *= 2;
            disable(retrySeconds);
            if (retrySeconds > 86400) {
              retrySeconds = 86400;
            }
            disabledTimeout = retrySeconds;
          }
        } else {
          disabledTimeout -= 1;
          if (disabledTimeout === 0) {
            enable();
          }
        }
        count = 0;
      }, 1e3).unref();
      return () => {
        count += 1;
      };
    }
    function isAnonymous(name) {
      return name !== void 0 && (name.length === 0 || name === "?" || name === "<anonymous>");
    }
    function functionNamesMatch(a3, b) {
      return a3 === b || isAnonymous(a3) && isAnonymous(b);
    }
    function hashFrames(frames) {
      if (frames === void 0) {
        return;
      }
      return frames.slice(-10).reduce((acc, frame) => `${acc},${frame.function},${frame.lineno},${frame.colno}`, "");
    }
    function hashFromStack(stackParser, stack) {
      if (stack === void 0) {
        return void 0;
      }
      return hashFrames(stackParser(stack, 1));
    }
    exports.createRateLimiter = createRateLimiter;
    exports.functionNamesMatch = functionNamesMatch;
    exports.hashFrames = hashFrames;
    exports.hashFromStack = hashFromStack;
    exports.isAnonymous = isAnonymous;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/local-variables/local-variables-sync.js
var require_local_variables_sync = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/local-variables/local-variables-sync.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var nodeVersion = require_nodeVersion();
    var common = require_common();
    function createCallbackList(complete) {
      let callbacks = [];
      let completedCalled = false;
      function checkedComplete(result) {
        callbacks = [];
        if (completedCalled) {
          return;
        }
        completedCalled = true;
        complete(result);
      }
      callbacks.push(checkedComplete);
      function add(fn) {
        callbacks.push(fn);
      }
      function next(result) {
        const popped = callbacks.pop() || checkedComplete;
        try {
          popped(result);
        } catch (_3) {
          checkedComplete(result);
        }
      }
      return { add, next };
    }
    var AsyncSession = class {
      /** Throws if inspector API is not available */
      constructor() {
        const { Session } = __require("inspector");
        this._session = new Session();
      }
      /** @inheritdoc */
      configureAndConnect(onPause, captureAll) {
        this._session.connect();
        this._session.on("Debugger.paused", (event) => {
          onPause(event, () => {
            this._session.post("Debugger.resume");
          });
        });
        this._session.post("Debugger.enable");
        this._session.post("Debugger.setPauseOnExceptions", { state: captureAll ? "all" : "uncaught" });
      }
      setPauseOnExceptions(captureAll) {
        this._session.post("Debugger.setPauseOnExceptions", { state: captureAll ? "all" : "uncaught" });
      }
      /** @inheritdoc */
      getLocalVariables(objectId, complete) {
        this._getProperties(objectId, (props) => {
          const { add, next } = createCallbackList(complete);
          for (const prop of props) {
            if (_optionalChain([prop, "optionalAccess", (_22) => _22.value, "optionalAccess", (_3) => _3.objectId]) && _optionalChain([prop, "optionalAccess", (_4) => _4.value, "access", (_5) => _5.className]) === "Array") {
              const id = prop.value.objectId;
              add((vars) => this._unrollArray(id, prop.name, vars, next));
            } else if (_optionalChain([prop, "optionalAccess", (_6) => _6.value, "optionalAccess", (_7) => _7.objectId]) && _optionalChain([prop, "optionalAccess", (_8) => _8.value, "optionalAccess", (_9) => _9.className]) === "Object") {
              const id = prop.value.objectId;
              add((vars) => this._unrollObject(id, prop.name, vars, next));
            } else if (_optionalChain([prop, "optionalAccess", (_10) => _10.value, "optionalAccess", (_11) => _11.value]) != null || _optionalChain([prop, "optionalAccess", (_12) => _12.value, "optionalAccess", (_13) => _13.description]) != null) {
              add((vars) => this._unrollOther(prop, vars, next));
            }
          }
          next({});
        });
      }
      /**
       * Gets all the PropertyDescriptors of an object
       */
      _getProperties(objectId, next) {
        this._session.post(
          "Runtime.getProperties",
          {
            objectId,
            ownProperties: true
          },
          (err, params) => {
            if (err) {
              next([]);
            } else {
              next(params.result);
            }
          }
        );
      }
      /**
       * Unrolls an array property
       */
      _unrollArray(objectId, name, vars, next) {
        this._getProperties(objectId, (props) => {
          vars[name] = props.filter((v3) => v3.name !== "length" && !isNaN(parseInt(v3.name, 10))).sort((a3, b) => parseInt(a3.name, 10) - parseInt(b.name, 10)).map((v3) => _optionalChain([v3, "optionalAccess", (_14) => _14.value, "optionalAccess", (_15) => _15.value]));
          next(vars);
        });
      }
      /**
       * Unrolls an object property
       */
      _unrollObject(objectId, name, vars, next) {
        this._getProperties(objectId, (props) => {
          vars[name] = props.map((v3) => [v3.name, _optionalChain([v3, "optionalAccess", (_16) => _16.value, "optionalAccess", (_17) => _17.value])]).reduce((obj, [key, val]) => {
            obj[key] = val;
            return obj;
          }, {});
          next(vars);
        });
      }
      /**
       * Unrolls other properties
       */
      _unrollOther(prop, vars, next) {
        if (_optionalChain([prop, "optionalAccess", (_18) => _18.value, "optionalAccess", (_19) => _19.value]) != null) {
          vars[prop.name] = prop.value.value;
        } else if (_optionalChain([prop, "optionalAccess", (_20) => _20.value, "optionalAccess", (_21) => _21.description]) != null && _optionalChain([prop, "optionalAccess", (_22) => _22.value, "optionalAccess", (_23) => _23.type]) !== "function") {
          vars[prop.name] = `<${prop.value.description}>`;
        }
        next(vars);
      }
    };
    function tryNewAsyncSession() {
      try {
        return new AsyncSession();
      } catch (e2) {
        return void 0;
      }
    }
    var INTEGRATION_NAME = "LocalVariables";
    var _localVariablesSyncIntegration = (options = {}, session = tryNewAsyncSession()) => {
      const cachedFrames = new utils.LRUMap(20);
      let rateLimiter;
      let shouldProcessEvent = false;
      function handlePaused(stackParser, { params: { reason, data, callFrames } }, complete) {
        if (reason !== "exception" && reason !== "promiseRejection") {
          complete();
          return;
        }
        _optionalChain([rateLimiter, "optionalCall", (_24) => _24()]);
        const exceptionHash = common.hashFromStack(stackParser, _optionalChain([data, "optionalAccess", (_25) => _25.description]));
        if (exceptionHash == void 0) {
          complete();
          return;
        }
        const { add, next } = createCallbackList((frames) => {
          cachedFrames.set(exceptionHash, frames);
          complete();
        });
        for (let i2 = 0; i2 < Math.min(callFrames.length, 5); i2++) {
          const { scopeChain, functionName, this: obj } = callFrames[i2];
          const localScope = scopeChain.find((scope) => scope.type === "local");
          const fn = obj.className === "global" || !obj.className ? functionName : `${obj.className}.${functionName}`;
          if (_optionalChain([localScope, "optionalAccess", (_26) => _26.object, "access", (_27) => _27.objectId]) === void 0) {
            add((frames) => {
              frames[i2] = { function: fn };
              next(frames);
            });
          } else {
            const id = localScope.object.objectId;
            add(
              (frames) => _optionalChain([session, "optionalAccess", (_28) => _28.getLocalVariables, "call", (_29) => _29(id, (vars) => {
                frames[i2] = { function: fn, vars };
                next(frames);
              })])
            );
          }
        }
        next([]);
      }
      function addLocalVariablesToException(exception) {
        const hash = common.hashFrames(_optionalChain([exception, "optionalAccess", (_30) => _30.stacktrace, "optionalAccess", (_31) => _31.frames]));
        if (hash === void 0) {
          return;
        }
        const cachedFrame = cachedFrames.remove(hash);
        if (cachedFrame === void 0) {
          return;
        }
        const frames = (_optionalChain([exception, "access", (_32) => _32.stacktrace, "optionalAccess", (_33) => _33.frames]) || []).filter((frame) => frame.function !== "new Promise");
        for (let i2 = 0; i2 < frames.length; i2++) {
          const frameIndex = frames.length - i2 - 1;
          if (!frames[frameIndex] || !cachedFrame[i2]) {
            break;
          }
          if (
            // We need to have vars to add
            cachedFrame[i2].vars === void 0 || // We're not interested in frames that are not in_app because the vars are not relevant
            frames[frameIndex].in_app === false || // The function names need to match
            !common.functionNamesMatch(frames[frameIndex].function, cachedFrame[i2].function)
          ) {
            continue;
          }
          frames[frameIndex].vars = cachedFrame[i2].vars;
        }
      }
      function addLocalVariablesToEvent(event) {
        for (const exception of _optionalChain([event, "optionalAccess", (_34) => _34.exception, "optionalAccess", (_35) => _35.values]) || []) {
          addLocalVariablesToException(exception);
        }
        return event;
      }
      return {
        name: INTEGRATION_NAME,
        setupOnce() {
          const client = core.getClient();
          const clientOptions = _optionalChain([client, "optionalAccess", (_36) => _36.getOptions, "call", (_37) => _37()]);
          if (session && _optionalChain([clientOptions, "optionalAccess", (_38) => _38.includeLocalVariables])) {
            const unsupportedNodeVersion = nodeVersion.NODE_VERSION.major < 18;
            if (unsupportedNodeVersion) {
              utils.logger.log("The `LocalVariables` integration is only supported on Node >= v18.");
              return;
            }
            const captureAll = options.captureAllExceptions !== false;
            session.configureAndConnect(
              (ev, complete) => handlePaused(clientOptions.stackParser, ev, complete),
              captureAll
            );
            if (captureAll) {
              const max = options.maxExceptionsPerSecond || 50;
              rateLimiter = common.createRateLimiter(
                max,
                () => {
                  utils.logger.log("Local variables rate-limit lifted.");
                  _optionalChain([session, "optionalAccess", (_39) => _39.setPauseOnExceptions, "call", (_40) => _40(true)]);
                },
                (seconds) => {
                  utils.logger.log(
                    `Local variables rate-limit exceeded. Disabling capturing of caught exceptions for ${seconds} seconds.`
                  );
                  _optionalChain([session, "optionalAccess", (_41) => _41.setPauseOnExceptions, "call", (_42) => _42(false)]);
                }
              );
            }
            shouldProcessEvent = true;
          }
        },
        processEvent(event) {
          if (shouldProcessEvent) {
            return addLocalVariablesToEvent(event);
          }
          return event;
        },
        // These are entirely for testing
        _getCachedFramesCount() {
          return cachedFrames.size;
        },
        _getFirstCachedFrame() {
          return cachedFrames.values()[0];
        }
      };
    };
    var localVariablesSyncIntegration = core.defineIntegration(_localVariablesSyncIntegration);
    var LocalVariablesSync = core.convertIntegrationFnToClass(
      INTEGRATION_NAME,
      localVariablesSyncIntegration
    );
    exports.LocalVariablesSync = LocalVariablesSync;
    exports.createCallbackList = createCallbackList;
    exports.localVariablesSyncIntegration = localVariablesSyncIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/local-variables/index.js
var require_local_variables = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/local-variables/index.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var localVariablesSync = require_local_variables_sync();
    var LocalVariables = localVariablesSync.LocalVariablesSync;
    var localVariablesIntegration = localVariablesSync.localVariablesSyncIntegration;
    exports.LocalVariables = LocalVariables;
    exports.localVariablesIntegration = localVariablesIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/modules.js
var require_modules = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/modules.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var fs3 = __require("fs");
    var path2 = __require("path");
    var core = require_cjs2();
    var moduleCache;
    var INTEGRATION_NAME = "Modules";
    function getPaths() {
      try {
        return __require.cache ? Object.keys(__require.cache) : [];
      } catch (e2) {
        return [];
      }
    }
    function collectModules() {
      const mainPaths = __require.main && __require.main.paths || [];
      const paths = getPaths();
      const infos = {};
      const seen = {};
      paths.forEach((path$1) => {
        let dir = path$1;
        const updir = () => {
          const orig = dir;
          dir = path2.dirname(orig);
          if (!dir || orig === dir || seen[orig]) {
            return void 0;
          }
          if (mainPaths.indexOf(dir) < 0) {
            return updir();
          }
          const pkgfile = path2.join(orig, "package.json");
          seen[orig] = true;
          if (!fs3.existsSync(pkgfile)) {
            return updir();
          }
          try {
            const info = JSON.parse(fs3.readFileSync(pkgfile, "utf8"));
            infos[info.name] = info.version;
          } catch (_oO) {
          }
        };
        updir();
      });
      return infos;
    }
    function _getModules() {
      if (!moduleCache) {
        moduleCache = collectModules();
      }
      return moduleCache;
    }
    var _modulesIntegration = () => {
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        processEvent(event) {
          event.modules = {
            ...event.modules,
            ..._getModules()
          };
          return event;
        }
      };
    };
    var modulesIntegration = core.defineIntegration(_modulesIntegration);
    var Modules = core.convertIntegrationFnToClass(INTEGRATION_NAME, modulesIntegration);
    exports.Modules = Modules;
    exports.modulesIntegration = modulesIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/utils/errorhandling.js
var require_errorhandling = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/utils/errorhandling.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var debugBuild = require_debug_build4();
    var DEFAULT_SHUTDOWN_TIMEOUT = 2e3;
    function logAndExitProcess(error) {
      utils.consoleSandbox(() => {
        console.error(error);
      });
      const client = core.getClient();
      if (client === void 0) {
        debugBuild.DEBUG_BUILD && utils.logger.warn("No NodeClient was defined, we are exiting the process now.");
        global.process.exit(1);
      }
      const options = client.getOptions();
      const timeout = options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout || DEFAULT_SHUTDOWN_TIMEOUT;
      client.close(timeout).then(
        (result) => {
          if (!result) {
            debugBuild.DEBUG_BUILD && utils.logger.warn("We reached the timeout for emptying the request buffer, still exiting now!");
          }
          global.process.exit(1);
        },
        (error2) => {
          debugBuild.DEBUG_BUILD && utils.logger.error(error2);
        }
      );
    }
    exports.logAndExitProcess = logAndExitProcess;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/onuncaughtexception.js
var require_onuncaughtexception = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/onuncaughtexception.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var debugBuild = require_debug_build4();
    var errorhandling = require_errorhandling();
    var INTEGRATION_NAME = "OnUncaughtException";
    var _onUncaughtExceptionIntegration = (options = {}) => {
      const _options = {
        exitEvenIfOtherHandlersAreRegistered: true,
        ...options
      };
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        setup(client) {
          global.process.on("uncaughtException", makeErrorHandler(client, _options));
        }
      };
    };
    var onUncaughtExceptionIntegration = core.defineIntegration(_onUncaughtExceptionIntegration);
    var OnUncaughtException = core.convertIntegrationFnToClass(
      INTEGRATION_NAME,
      onUncaughtExceptionIntegration
    );
    function makeErrorHandler(client, options) {
      const timeout = 2e3;
      let caughtFirstError = false;
      let caughtSecondError = false;
      let calledFatalError = false;
      let firstError;
      const clientOptions = client.getOptions();
      return Object.assign(
        (error) => {
          let onFatalError = errorhandling.logAndExitProcess;
          if (options.onFatalError) {
            onFatalError = options.onFatalError;
          } else if (clientOptions.onFatalError) {
            onFatalError = clientOptions.onFatalError;
          }
          const userProvidedListenersCount = global.process.listeners("uncaughtException").reduce((acc, listener) => {
            if (
              // There are 3 listeners we ignore:
              listener.name === "domainUncaughtExceptionClear" || // as soon as we're using domains this listener is attached by node itself
              listener.tag && listener.tag === "sentry_tracingErrorCallback" || // the handler we register for tracing
              listener._errorHandler
            ) {
              return acc;
            } else {
              return acc + 1;
            }
          }, 0);
          const processWouldExit = userProvidedListenersCount === 0;
          const shouldApplyFatalHandlingLogic = options.exitEvenIfOtherHandlersAreRegistered || processWouldExit;
          if (!caughtFirstError) {
            firstError = error;
            caughtFirstError = true;
            if (core.getClient() === client) {
              core.captureException(error, {
                originalException: error,
                captureContext: {
                  level: "fatal"
                },
                mechanism: {
                  handled: false,
                  type: "onuncaughtexception"
                }
              });
            }
            if (!calledFatalError && shouldApplyFatalHandlingLogic) {
              calledFatalError = true;
              onFatalError(error);
            }
          } else {
            if (shouldApplyFatalHandlingLogic) {
              if (calledFatalError) {
                debugBuild.DEBUG_BUILD && utils.logger.warn(
                  "uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown"
                );
                errorhandling.logAndExitProcess(error);
              } else if (!caughtSecondError) {
                caughtSecondError = true;
                setTimeout(() => {
                  if (!calledFatalError) {
                    calledFatalError = true;
                    onFatalError(firstError, error);
                  }
                }, timeout);
              }
            }
          }
        },
        { _errorHandler: true }
      );
    }
    exports.OnUncaughtException = OnUncaughtException;
    exports.makeErrorHandler = makeErrorHandler;
    exports.onUncaughtExceptionIntegration = onUncaughtExceptionIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/onunhandledrejection.js
var require_onunhandledrejection = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/onunhandledrejection.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var errorhandling = require_errorhandling();
    var INTEGRATION_NAME = "OnUnhandledRejection";
    var _onUnhandledRejectionIntegration = (options = {}) => {
      const mode = options.mode || "warn";
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        setup(client) {
          global.process.on("unhandledRejection", makeUnhandledPromiseHandler(client, { mode }));
        }
      };
    };
    var onUnhandledRejectionIntegration = core.defineIntegration(_onUnhandledRejectionIntegration);
    var OnUnhandledRejection = core.convertIntegrationFnToClass(
      INTEGRATION_NAME,
      onUnhandledRejectionIntegration
    );
    function makeUnhandledPromiseHandler(client, options) {
      return function sendUnhandledPromise(reason, promise) {
        if (core.getClient() !== client) {
          return;
        }
        core.captureException(reason, {
          originalException: promise,
          captureContext: {
            extra: { unhandledPromiseRejection: true }
          },
          mechanism: {
            handled: false,
            type: "onunhandledrejection"
          }
        });
        handleRejection(reason, options);
      };
    }
    function handleRejection(reason, options) {
      const rejectionWarning = "This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason:";
      if (options.mode === "warn") {
        utils.consoleSandbox(() => {
          console.warn(rejectionWarning);
          console.error(reason && reason.stack ? reason.stack : reason);
        });
      } else if (options.mode === "strict") {
        utils.consoleSandbox(() => {
          console.warn(rejectionWarning);
        });
        errorhandling.logAndExitProcess(reason);
      }
    }
    exports.OnUnhandledRejection = OnUnhandledRejection;
    exports.makeUnhandledPromiseHandler = makeUnhandledPromiseHandler;
    exports.onUnhandledRejectionIntegration = onUnhandledRejectionIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/spotlight.js
var require_spotlight = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/spotlight.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var http = __require("http");
    var url = __require("url");
    var core = require_cjs2();
    var utils = require_cjs();
    var INTEGRATION_NAME = "Spotlight";
    var _spotlightIntegration = (options = {}) => {
      const _options = {
        sidecarUrl: options.sidecarUrl || "http://localhost:8969/stream"
      };
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        setup(client) {
          if (typeof process === "object" && process.env && process.env.NODE_ENV !== "development") {
            utils.logger.warn("[Spotlight] It seems you're not in dev mode. Do you really want to have Spotlight enabled?");
          }
          connectToSpotlight(client, _options);
        }
      };
    };
    var spotlightIntegration = core.defineIntegration(_spotlightIntegration);
    var Spotlight = core.convertIntegrationFnToClass(INTEGRATION_NAME, spotlightIntegration);
    function connectToSpotlight(client, options) {
      const spotlightUrl = parseSidecarUrl(options.sidecarUrl);
      if (!spotlightUrl) {
        return;
      }
      let failedRequests = 0;
      if (typeof client.on !== "function") {
        utils.logger.warn("[Spotlight] Cannot connect to spotlight due to missing method on SDK client (`client.on`)");
        return;
      }
      client.on("beforeEnvelope", (envelope) => {
        if (failedRequests > 3) {
          utils.logger.warn("[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests");
          return;
        }
        const serializedEnvelope = utils.serializeEnvelope(envelope);
        const request = getNativeHttpRequest();
        const req = request(
          {
            method: "POST",
            path: spotlightUrl.pathname,
            hostname: spotlightUrl.hostname,
            port: spotlightUrl.port,
            headers: {
              "Content-Type": "application/x-sentry-envelope"
            }
          },
          (res) => {
            res.on("data", () => {
            });
            res.on("end", () => {
            });
            res.setEncoding("utf8");
          }
        );
        req.on("error", () => {
          failedRequests++;
          utils.logger.warn("[Spotlight] Failed to send envelope to Spotlight Sidecar");
        });
        req.write(serializedEnvelope);
        req.end();
      });
    }
    function parseSidecarUrl(url$1) {
      try {
        return new url.URL(`${url$1}`);
      } catch (e2) {
        utils.logger.warn(`[Spotlight] Invalid sidecar URL: ${url$1}`);
        return void 0;
      }
    }
    function getNativeHttpRequest() {
      const { request } = http;
      if (isWrapped(request)) {
        return request.__sentry_original__;
      }
      return request;
    }
    function isWrapped(impl) {
      return "__sentry_original__" in impl;
    }
    exports.Spotlight = Spotlight;
    exports.getNativeHttpRequest = getNativeHttpRequest;
    exports.spotlightIntegration = spotlightIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/undici/index.js
var require_undici = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/undici/index.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var nodeVersion = require_nodeVersion();
    exports.ChannelName = void 0;
    (function(ChannelName) {
      const RequestCreate = "undici:request:create";
      ChannelName["RequestCreate"] = RequestCreate;
      const RequestEnd = "undici:request:headers";
      ChannelName["RequestEnd"] = RequestEnd;
      const RequestError = "undici:request:error";
      ChannelName["RequestError"] = RequestError;
    })(exports.ChannelName || (exports.ChannelName = {}));
    var _nativeNodeFetchintegration = (options) => {
      return new Undici(options);
    };
    var nativeNodeFetchintegration = core.defineIntegration(_nativeNodeFetchintegration);
    var Undici = class _Undici {
      /**
       * @inheritDoc
       */
      static __initStatic() {
        this.id = "Undici";
      }
      /**
       * @inheritDoc
       */
      // eslint-disable-next-line deprecation/deprecation
      __init() {
        this.name = _Undici.id;
      }
      __init2() {
        this._createSpanUrlMap = new utils.LRUMap(100);
      }
      __init3() {
        this._headersUrlMap = new utils.LRUMap(100);
      }
      constructor(_options = {}) {
        _Undici.prototype.__init.call(this);
        _Undici.prototype.__init2.call(this);
        _Undici.prototype.__init3.call(this);
        _Undici.prototype.__init4.call(this);
        _Undici.prototype.__init5.call(this);
        _Undici.prototype.__init6.call(this);
        this._options = {
          breadcrumbs: _options.breadcrumbs === void 0 ? true : _options.breadcrumbs,
          tracing: _options.tracing,
          shouldCreateSpanForRequest: _options.shouldCreateSpanForRequest
        };
      }
      /**
       * @inheritDoc
       */
      setupOnce(_addGlobalEventProcessor) {
        if (nodeVersion.NODE_VERSION.major < 16) {
          return;
        }
        let ds;
        try {
          ds = __require("diagnostics_channel");
        } catch (e2) {
        }
        if (!ds || !ds.subscribe) {
          return;
        }
        ds.subscribe(exports.ChannelName.RequestCreate, this._onRequestCreate);
        ds.subscribe(exports.ChannelName.RequestEnd, this._onRequestEnd);
        ds.subscribe(exports.ChannelName.RequestError, this._onRequestError);
      }
      /** Helper that wraps shouldCreateSpanForRequest option */
      _shouldCreateSpan(url) {
        if (this._options.tracing === false || this._options.tracing === void 0 && !core.hasTracingEnabled()) {
          return false;
        }
        if (this._options.shouldCreateSpanForRequest === void 0) {
          return true;
        }
        const cachedDecision = this._createSpanUrlMap.get(url);
        if (cachedDecision !== void 0) {
          return cachedDecision;
        }
        const decision = this._options.shouldCreateSpanForRequest(url);
        this._createSpanUrlMap.set(url, decision);
        return decision;
      }
      __init4() {
        this._onRequestCreate = (message) => {
          if (!_optionalChain([core.getClient, "call", (_10) => _10(), "optionalAccess", (_11) => _11.getIntegration, "call", (_12) => _12(_Undici)])) {
            return;
          }
          const { request } = message;
          const stringUrl = request.origin ? request.origin.toString() + request.path : request.path;
          const client = core.getClient();
          if (!client) {
            return;
          }
          if (core.isSentryRequestUrl(stringUrl, client) || request.__sentry_span__ !== void 0) {
            return;
          }
          const clientOptions = client.getOptions();
          const scope = core.getCurrentScope();
          const isolationScope = core.getIsolationScope();
          const parentSpan = core.getActiveSpan();
          const span = this._shouldCreateSpan(stringUrl) ? createRequestSpan(parentSpan, request, stringUrl) : void 0;
          if (span) {
            request.__sentry_span__ = span;
          }
          const shouldAttachTraceData = (url) => {
            if (clientOptions.tracePropagationTargets === void 0) {
              return true;
            }
            const cachedDecision = this._headersUrlMap.get(url);
            if (cachedDecision !== void 0) {
              return cachedDecision;
            }
            const decision = utils.stringMatchesSomePattern(url, clientOptions.tracePropagationTargets);
            this._headersUrlMap.set(url, decision);
            return decision;
          };
          if (shouldAttachTraceData(stringUrl)) {
            const { traceId, spanId, sampled, dsc } = {
              ...isolationScope.getPropagationContext(),
              ...scope.getPropagationContext()
            };
            const sentryTraceHeader = span ? core.spanToTraceHeader(span) : utils.generateSentryTraceHeader(traceId, spanId, sampled);
            const sentryBaggageHeader = utils.dynamicSamplingContextToSentryBaggageHeader(
              dsc || (span ? core.getDynamicSamplingContextFromSpan(span) : core.getDynamicSamplingContextFromClient(traceId, client, scope))
            );
            setHeadersOnRequest(request, sentryTraceHeader, sentryBaggageHeader);
          }
        };
      }
      __init5() {
        this._onRequestEnd = (message) => {
          if (!_optionalChain([core.getClient, "call", (_13) => _13(), "optionalAccess", (_14) => _14.getIntegration, "call", (_15) => _15(_Undici)])) {
            return;
          }
          const { request, response } = message;
          const stringUrl = request.origin ? request.origin.toString() + request.path : request.path;
          if (core.isSentryRequestUrl(stringUrl, core.getClient())) {
            return;
          }
          const span = request.__sentry_span__;
          if (span) {
            core.setHttpStatus(span, response.statusCode);
            span.end();
          }
          if (this._options.breadcrumbs) {
            core.addBreadcrumb(
              {
                category: "http",
                data: {
                  method: request.method,
                  status_code: response.statusCode,
                  url: stringUrl
                },
                type: "http"
              },
              {
                event: "response",
                request,
                response
              }
            );
          }
        };
      }
      __init6() {
        this._onRequestError = (message) => {
          if (!_optionalChain([core.getClient, "call", (_16) => _16(), "optionalAccess", (_17) => _17.getIntegration, "call", (_18) => _18(_Undici)])) {
            return;
          }
          const { request } = message;
          const stringUrl = request.origin ? request.origin.toString() + request.path : request.path;
          if (core.isSentryRequestUrl(stringUrl, core.getClient())) {
            return;
          }
          const span = request.__sentry_span__;
          if (span) {
            span.setStatus("internal_error");
            span.end();
          }
          if (this._options.breadcrumbs) {
            core.addBreadcrumb(
              {
                category: "http",
                data: {
                  method: request.method,
                  url: stringUrl
                },
                level: "error",
                type: "http"
              },
              {
                event: "error",
                request
              }
            );
          }
        };
      }
    };
    Undici.__initStatic();
    function setHeadersOnRequest(request, sentryTrace, sentryBaggageHeader) {
      let hasSentryHeaders;
      if (Array.isArray(request.headers)) {
        hasSentryHeaders = request.headers.some((headerLine) => headerLine === "sentry-trace");
      } else {
        const headerLines = request.headers.split("\r\n");
        hasSentryHeaders = headerLines.some((headerLine) => headerLine.startsWith("sentry-trace:"));
      }
      if (hasSentryHeaders) {
        return;
      }
      request.addHeader("sentry-trace", sentryTrace);
      if (sentryBaggageHeader) {
        request.addHeader("baggage", sentryBaggageHeader);
      }
    }
    function createRequestSpan(activeSpan, request, stringUrl) {
      const url = utils.parseUrl(stringUrl);
      const method = request.method || "GET";
      const data = {
        "http.method": method
      };
      if (url.search) {
        data["http.query"] = url.search;
      }
      if (url.hash) {
        data["http.fragment"] = url.hash;
      }
      return _optionalChain([activeSpan, "optionalAccess", (_19) => _19.startChild, "call", (_20) => _20({
        op: "http.client",
        origin: "auto.http.node.undici",
        description: `${method} ${utils.getSanitizedUrlString(url)}`,
        data
      })]);
    }
    exports.Undici = Undici;
    exports.nativeNodeFetchintegration = nativeNodeFetchintegration;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/module.js
var require_module = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/module.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var path2 = __require("path");
    var utils = require_cjs();
    function normalizeWindowsPath(path3) {
      return path3.replace(/^[A-Z]:/, "").replace(/\\/g, "/");
    }
    function createGetModuleFromFilename(basePath = process.argv[1] ? utils.dirname(process.argv[1]) : process.cwd(), isWindows2 = path2.sep === "\\") {
      const normalizedBase = isWindows2 ? normalizeWindowsPath(basePath) : basePath;
      return (filename) => {
        if (!filename) {
          return;
        }
        const normalizedFilename = isWindows2 ? normalizeWindowsPath(filename) : filename;
        let { dir, base: file, ext } = path2.posix.parse(normalizedFilename);
        if (ext === ".js" || ext === ".mjs" || ext === ".cjs") {
          file = file.slice(0, ext.length * -1);
        }
        if (!dir) {
          dir = ".";
        }
        const n2 = dir.lastIndexOf("/node_modules");
        if (n2 > -1) {
          return `${dir.slice(n2 + 14).replace(/\//g, ".")}:${file}`;
        }
        if (dir.startsWith(normalizedBase)) {
          let moduleName = dir.slice(normalizedBase.length + 1).replace(/\//g, ".");
          if (moduleName) {
            moduleName += ":";
          }
          moduleName += file;
          return moduleName;
        }
        return file;
      };
    }
    exports.createGetModuleFromFilename = createGetModuleFromFilename;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/sdk.js
var require_sdk2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/sdk.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var index$2 = require_async();
    var client = require_client();
    var console2 = require_console2();
    var context2 = require_context();
    var contextlines = require_contextlines();
    var http = require_http3();
    var index$1 = require_local_variables();
    var modules = require_modules();
    var onuncaughtexception = require_onuncaughtexception();
    var onunhandledrejection = require_onunhandledrejection();
    var spotlight = require_spotlight();
    var index = require_undici();
    var module$1 = require_module();
    var http$1 = require_http();
    var defaultIntegrations = [
      // Common
      core.inboundFiltersIntegration(),
      core.functionToStringIntegration(),
      core.linkedErrorsIntegration(),
      core.requestDataIntegration(),
      // Native Wrappers
      console2.consoleIntegration(),
      http.httpIntegration(),
      index.nativeNodeFetchintegration(),
      // Global Handlers
      onuncaughtexception.onUncaughtExceptionIntegration(),
      onunhandledrejection.onUnhandledRejectionIntegration(),
      // Event Info
      contextlines.contextLinesIntegration(),
      index$1.localVariablesIntegration(),
      context2.nodeContextIntegration(),
      modules.modulesIntegration()
    ];
    function getDefaultIntegrations(_options) {
      const carrier = core.getMainCarrier();
      const autoloadedIntegrations = _optionalChain([carrier, "access", (_3) => _3.__SENTRY__, "optionalAccess", (_22) => _22.integrations]) || [];
      return [
        // eslint-disable-next-line deprecation/deprecation
        ...defaultIntegrations,
        ...autoloadedIntegrations
      ];
    }
    function init3(options = {}) {
      index$2.setNodeAsyncContextStrategy();
      if (options.defaultIntegrations === void 0) {
        options.defaultIntegrations = getDefaultIntegrations();
      }
      if (options.dsn === void 0 && process.env.SENTRY_DSN) {
        options.dsn = process.env.SENTRY_DSN;
      }
      const sentryTracesSampleRate = process.env.SENTRY_TRACES_SAMPLE_RATE;
      if (options.tracesSampleRate === void 0 && sentryTracesSampleRate) {
        const tracesSampleRate = parseFloat(sentryTracesSampleRate);
        if (isFinite(tracesSampleRate)) {
          options.tracesSampleRate = tracesSampleRate;
        }
      }
      if (options.release === void 0) {
        const detectedRelease = getSentryRelease();
        if (detectedRelease !== void 0) {
          options.release = detectedRelease;
        } else {
          options.autoSessionTracking = false;
        }
      }
      if (options.environment === void 0 && process.env.SENTRY_ENVIRONMENT) {
        options.environment = process.env.SENTRY_ENVIRONMENT;
      }
      if (options.autoSessionTracking === void 0 && options.dsn !== void 0) {
        options.autoSessionTracking = true;
      }
      if (options.instrumenter === void 0) {
        options.instrumenter = "sentry";
      }
      const clientOptions = {
        ...options,
        stackParser: utils.stackParserFromStackParserOptions(options.stackParser || defaultStackParser),
        integrations: core.getIntegrationsToSetup(options),
        transport: options.transport || http$1.makeNodeTransport
      };
      core.initAndBind(options.clientClass || client.NodeClient, clientOptions);
      if (options.autoSessionTracking) {
        startSessionTracking();
      }
      updateScopeFromEnvVariables();
      if (options.spotlight) {
        const client2 = core.getClient();
        if (client2 && client2.addIntegration) {
          const integrations = client2.getOptions().integrations;
          for (const integration of integrations) {
            client2.addIntegration(integration);
          }
          client2.addIntegration(
            spotlight.spotlightIntegration({ sidecarUrl: typeof options.spotlight === "string" ? options.spotlight : void 0 })
          );
        }
      }
    }
    function isAutoSessionTrackingEnabled(client2) {
      if (client2 === void 0) {
        return false;
      }
      const clientOptions = client2 && client2.getOptions();
      if (clientOptions && clientOptions.autoSessionTracking !== void 0) {
        return clientOptions.autoSessionTracking;
      }
      return false;
    }
    function getSentryRelease(fallback) {
      if (process.env.SENTRY_RELEASE) {
        return process.env.SENTRY_RELEASE;
      }
      if (utils.GLOBAL_OBJ.SENTRY_RELEASE && utils.GLOBAL_OBJ.SENTRY_RELEASE.id) {
        return utils.GLOBAL_OBJ.SENTRY_RELEASE.id;
      }
      return (
        // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables
        process.env.GITHUB_SHA || // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata
        process.env.COMMIT_REF || // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables
        process.env.VERCEL_GIT_COMMIT_SHA || process.env.VERCEL_GITHUB_COMMIT_SHA || process.env.VERCEL_GITLAB_COMMIT_SHA || process.env.VERCEL_BITBUCKET_COMMIT_SHA || // Zeit (now known as Vercel)
        process.env.ZEIT_GITHUB_COMMIT_SHA || process.env.ZEIT_GITLAB_COMMIT_SHA || process.env.ZEIT_BITBUCKET_COMMIT_SHA || // Cloudflare Pages - https://developers.cloudflare.com/pages/platform/build-configuration/#environment-variables
        process.env.CF_PAGES_COMMIT_SHA || fallback
      );
    }
    var defaultStackParser = utils.createStackParser(utils.nodeStackLineParser(module$1.createGetModuleFromFilename()));
    function startSessionTracking() {
      core.startSession();
      process.on("beforeExit", () => {
        const session = core.getIsolationScope().getSession();
        const terminalStates = ["exited", "crashed"];
        if (session && !terminalStates.includes(session.status)) {
          core.endSession();
        }
      });
    }
    function updateScopeFromEnvVariables() {
      const sentryUseEnvironment = (process.env.SENTRY_USE_ENVIRONMENT || "").toLowerCase();
      if (!["false", "n", "no", "off", "0"].includes(sentryUseEnvironment)) {
        const sentryTraceEnv = process.env.SENTRY_TRACE;
        const baggageEnv = process.env.SENTRY_BAGGAGE;
        const propagationContext = utils.propagationContextFromHeaders(sentryTraceEnv, baggageEnv);
        core.getCurrentScope().setPropagationContext(propagationContext);
      }
    }
    exports.defaultIntegrations = defaultIntegrations;
    exports.defaultStackParser = defaultStackParser;
    exports.getDefaultIntegrations = getDefaultIntegrations;
    exports.getSentryRelease = getSentryRelease;
    exports.init = init3;
    exports.isAutoSessionTrackingEnabled = isAutoSessionTrackingEnabled;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/utils.js
var require_utils4 = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/utils.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var fs3 = __require("fs");
    var path2 = __require("path");
    function deepReadDirSync(targetDir) {
      const targetDirAbsPath = path2.resolve(targetDir);
      if (!fs3.existsSync(targetDirAbsPath)) {
        throw new Error(`Cannot read contents of ${targetDirAbsPath}. Directory does not exist.`);
      }
      if (!fs3.statSync(targetDirAbsPath).isDirectory()) {
        throw new Error(`Cannot read contents of ${targetDirAbsPath}, because it is not a directory.`);
      }
      const deepReadCurrentDir = (currentDirAbsPath) => {
        return fs3.readdirSync(currentDirAbsPath).reduce((absPaths, itemName) => {
          const itemAbsPath = path2.join(currentDirAbsPath, itemName);
          if (fs3.statSync(itemAbsPath).isDirectory()) {
            return absPaths.concat(deepReadCurrentDir(itemAbsPath));
          }
          absPaths.push(itemAbsPath);
          return absPaths;
        }, []);
      };
      return deepReadCurrentDir(targetDirAbsPath).map((absPath) => path2.relative(targetDirAbsPath, absPath));
    }
    exports.deepReadDirSync = deepReadDirSync;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/anr/worker-script.js
var require_worker_script = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/anr/worker-script.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    exports.base64WorkerScript = " ";
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/anr/index.js
var require_anr2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/anr/index.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain,
      _optionalChainDelete
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var url = __require("url");
    var core = require_cjs2();
    var utils = require_cjs();
    var nodeVersion = require_nodeVersion();
    var workerScript = require_worker_script();
    var DEFAULT_INTERVAL = 50;
    var DEFAULT_HANG_THRESHOLD = 5e3;
    function log2(message, ...args) {
      utils.logger.log(`[ANR] ${message}`, ...args);
    }
    function globalWithScopeFetchFn() {
      return utils.GLOBAL_OBJ;
    }
    function getScopeData() {
      const scope = core.getGlobalScope().getScopeData();
      core.mergeScopeData(scope, core.getIsolationScope().getScopeData());
      core.mergeScopeData(scope, core.getCurrentScope().getScopeData());
      scope.attachments = [];
      scope.eventProcessors = [];
      return scope;
    }
    function getWorkerThreads() {
      return utils.dynamicRequire(module, "worker_threads");
    }
    async function getContexts(client) {
      let event = { message: "ANR" };
      const eventHint = {};
      for (const processor of client.getEventProcessors()) {
        if (event === null)
          break;
        event = await processor(event, eventHint);
      }
      return _optionalChain([event, "optionalAccess", (_22) => _22.contexts]) || {};
    }
    var INTEGRATION_NAME = "Anr";
    var _anrIntegration = (options = {}) => {
      if (nodeVersion.NODE_VERSION.major < 16 || nodeVersion.NODE_VERSION.major === 16 && nodeVersion.NODE_VERSION.minor < 17) {
        throw new Error("ANR detection requires Node 16.17.0 or later");
      }
      let worker;
      let client;
      const gbl = globalWithScopeFetchFn();
      gbl.__SENTRY_GET_SCOPES__ = getScopeData;
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        startWorker: () => {
          if (worker) {
            return;
          }
          if (client) {
            worker = _startWorker(client, options);
          }
        },
        stopWorker: () => {
          if (worker) {
            worker.then((stop) => {
              stop();
              worker = void 0;
            });
          }
        },
        setup(initClient) {
          client = initClient;
          setImmediate(() => this.startWorker());
        }
      };
    };
    var anrIntegration = core.defineIntegration(_anrIntegration);
    var Anr = core.convertIntegrationFnToClass(INTEGRATION_NAME, anrIntegration);
    async function _startWorker(client, integrationOptions) {
      const dsn = client.getDsn();
      if (!dsn) {
        return () => {
        };
      }
      const contexts = await getContexts(client);
      _optionalChainDelete([contexts, "access", (_3) => _3.app, "optionalAccess", (_4) => delete _4.app_memory]);
      _optionalChainDelete([contexts, "access", (_5) => _5.device, "optionalAccess", (_6) => delete _6.free_memory]);
      const initOptions = client.getOptions();
      const sdkMetadata = client.getSdkMetadata() || {};
      if (sdkMetadata.sdk) {
        sdkMetadata.sdk.integrations = initOptions.integrations.map((i2) => i2.name);
      }
      const options = {
        debug: utils.logger.isEnabled(),
        dsn,
        environment: initOptions.environment || "production",
        release: initOptions.release,
        dist: initOptions.dist,
        sdkMetadata,
        appRootPath: integrationOptions.appRootPath,
        pollInterval: integrationOptions.pollInterval || DEFAULT_INTERVAL,
        anrThreshold: integrationOptions.anrThreshold || DEFAULT_HANG_THRESHOLD,
        captureStackTrace: !!integrationOptions.captureStackTrace,
        staticTags: integrationOptions.staticTags || {},
        contexts
      };
      if (options.captureStackTrace) {
        const inspector = __require("inspector");
        if (!inspector.url()) {
          inspector.open(0);
        }
      }
      const { Worker: Worker2 } = getWorkerThreads();
      const worker = new Worker2(new url.URL(`data:application/javascript;base64,${workerScript.base64WorkerScript}`), {
        workerData: options
      });
      process.on("exit", () => {
        worker.terminate();
      });
      const timer = setInterval(() => {
        try {
          const currentSession = core.getCurrentScope().getSession();
          const session = currentSession ? { ...currentSession, toJSON: void 0 } : void 0;
          worker.postMessage({ session });
        } catch (_3) {
        }
      }, options.pollInterval);
      timer.unref();
      worker.on("message", (msg) => {
        if (msg === "session-ended") {
          log2("ANR event sent from ANR worker. Clearing session in this thread.");
          core.getCurrentScope().setSession(void 0);
        }
      });
      worker.once("error", (err) => {
        clearInterval(timer);
        log2("ANR worker error", err);
      });
      worker.once("exit", (code) => {
        clearInterval(timer);
        log2("ANR worker exit", code);
      });
      worker.unref();
      return () => {
        worker.terminate();
        clearInterval(timer);
      };
    }
    exports.Anr = Anr;
    exports.anrIntegration = anrIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/anr/legacy.js
var require_legacy2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/anr/legacy.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var index = require_anr2();
    function enableAnrDetection(options) {
      const client = core.getClient();
      const integration = new index.Anr(options);
      integration.setup(client);
      return Promise.resolve();
    }
    exports.enableAnrDetection = enableAnrDetection;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/trpc.js
var require_trpc = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/trpc.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    function trpcMiddleware(options = {}) {
      return function({ path: path2, type, next, rawInput }) {
        const clientOptions = _optionalChain([core.getClient, "call", (_3) => _3(), "optionalAccess", (_22) => _22.getOptions, "call", (_3) => _3()]);
        const sentryTransaction = core.getCurrentScope().getTransaction();
        if (sentryTransaction) {
          sentryTransaction.updateName(`trpc/${path2}`);
          sentryTransaction.setAttribute(core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, "route");
          sentryTransaction.op = "rpc.server";
          const trpcContext = {
            procedure_type: type
          };
          if (options.attachRpcInput !== void 0 ? options.attachRpcInput : _optionalChain([clientOptions, "optionalAccess", (_4) => _4.sendDefaultPii])) {
            trpcContext.input = utils.normalize(rawInput);
          }
          sentryTransaction.setContext("trpc", trpcContext);
        }
        function captureIfError(nextResult) {
          if (!nextResult.ok) {
            core.captureException(nextResult.error, { mechanism: { handled: false, data: { function: "trpcMiddleware" } } });
          }
        }
        let maybePromiseResult;
        try {
          maybePromiseResult = next();
        } catch (e2) {
          core.captureException(e2, { mechanism: { handled: false, data: { function: "trpcMiddleware" } } });
          throw e2;
        }
        if (utils.isThenable(maybePromiseResult)) {
          Promise.resolve(maybePromiseResult).then(
            (nextResult) => {
              captureIfError(nextResult);
            },
            (e2) => {
              core.captureException(e2, { mechanism: { handled: false, data: { function: "trpcMiddleware" } } });
            }
          );
        } else {
          captureIfError(maybePromiseResult);
        }
        return maybePromiseResult;
      };
    }
    exports.trpcMiddleware = trpcMiddleware;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/requestDataDeprecated.js
var require_requestDataDeprecated = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/requestDataDeprecated.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    function extractRequestData(req, keys) {
      return utils.extractRequestData(req, { include: keys });
    }
    function parseRequest(event, req, options = {}) {
      return utils.addRequestDataToEvent(event, req, { include: options });
    }
    exports.extractRequestData = extractRequestData;
    exports.parseRequest = parseRequest;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/handlers.js
var require_handlers2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/handlers.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var debugBuild = require_debug_build4();
    var sdk = require_sdk2();
    var trpc = require_trpc();
    var requestDataDeprecated = require_requestDataDeprecated();
    function tracingHandler() {
      return function sentryTracingMiddleware(req, res, next) {
        const options = _optionalChain([core.getClient, "call", (_3) => _3(), "optionalAccess", (_22) => _22.getOptions, "call", (_3) => _3()]);
        if (!options || options.instrumenter !== "sentry" || _optionalChain([req, "access", (_4) => _4.method, "optionalAccess", (_5) => _5.toUpperCase, "call", (_6) => _6()]) === "OPTIONS" || _optionalChain([req, "access", (_7) => _7.method, "optionalAccess", (_8) => _8.toUpperCase, "call", (_9) => _9()]) === "HEAD") {
          return next();
        }
        const sentryTrace = req.headers && utils.isString(req.headers["sentry-trace"]) ? req.headers["sentry-trace"] : void 0;
        const baggage = _optionalChain([req, "access", (_10) => _10.headers, "optionalAccess", (_11) => _11.baggage]);
        if (!core.hasTracingEnabled(options)) {
          return next();
        }
        const [name, source] = utils.extractPathForTransaction(req, { path: true, method: true });
        const transaction = core.continueTrace(
          { sentryTrace, baggage },
          (ctx) => (
            // TODO: Refactor this to use `startSpan()`
            // eslint-disable-next-line deprecation/deprecation
            core.startTransaction(
              {
                name,
                op: "http.server",
                origin: "auto.http.node.tracingHandler",
                ...ctx,
                data: {
                  [core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: source
                },
                metadata: {
                  // eslint-disable-next-line deprecation/deprecation
                  ...ctx.metadata,
                  // The request should already have been stored in `scope.sdkProcessingMetadata` (which will become
                  // `event.sdkProcessingMetadata` the same way the metadata here will) by `sentryRequestMiddleware`, but on the
                  // off chance someone is using `sentryTracingMiddleware` without `sentryRequestMiddleware`, it doesn't hurt to
                  // be sure
                  request: req
                }
              },
              // extra context passed to the tracesSampler
              { request: utils.extractRequestData(req) }
            )
          )
        );
        core.getCurrentScope().setSpan(transaction);
        res.__sentry_transaction = transaction;
        res.once("finish", () => {
          setImmediate(() => {
            utils.addRequestDataToTransaction(transaction, req);
            core.setHttpStatus(transaction, res.statusCode);
            transaction.end();
          });
        });
        next();
      };
    }
    function convertReqHandlerOptsToAddReqDataOpts(reqHandlerOptions = {}) {
      let addRequestDataOptions;
      if ("include" in reqHandlerOptions) {
        addRequestDataOptions = { include: reqHandlerOptions.include };
      } else {
        const { ip, request, transaction, user } = reqHandlerOptions;
        if (ip || request || transaction || user) {
          addRequestDataOptions = { include: utils.dropUndefinedKeys({ ip, request, transaction, user }) };
        }
      }
      return addRequestDataOptions;
    }
    function requestHandler(options) {
      const requestDataOptions = convertReqHandlerOptsToAddReqDataOpts(options);
      const client = core.getClient();
      if (client && sdk.isAutoSessionTrackingEnabled(client)) {
        client.initSessionFlusher();
        const scope = core.getCurrentScope();
        if (scope.getSession()) {
          scope.setSession();
        }
      }
      return function sentryRequestMiddleware(req, res, next) {
        if (options && options.flushTimeout && options.flushTimeout > 0) {
          const _end = res.end;
          res.end = function(chunk, encoding, cb) {
            void core.flush(options.flushTimeout).then(() => {
              _end.call(this, chunk, encoding, cb);
            }).then(null, (e2) => {
              debugBuild.DEBUG_BUILD && utils.logger.error(e2);
              _end.call(this, chunk, encoding, cb);
            });
          };
        }
        core.runWithAsyncContext(() => {
          const scope = core.getCurrentScope();
          scope.setSDKProcessingMetadata({
            request: req,
            // TODO (v8): Stop passing this
            requestDataOptionsFromExpressHandler: requestDataOptions
          });
          const client2 = core.getClient();
          if (sdk.isAutoSessionTrackingEnabled(client2)) {
            scope.setRequestSession({ status: "ok" });
          }
          res.once("finish", () => {
            const client3 = core.getClient();
            if (sdk.isAutoSessionTrackingEnabled(client3)) {
              setImmediate(() => {
                if (client3 && client3._captureRequestSession) {
                  client3._captureRequestSession();
                }
              });
            }
          });
          next();
        });
      };
    }
    function getStatusCodeFromResponse(error) {
      const statusCode = error.status || error.statusCode || error.status_code || error.output && error.output.statusCode;
      return statusCode ? parseInt(statusCode, 10) : 500;
    }
    function defaultShouldHandleError(error) {
      const status = getStatusCodeFromResponse(error);
      return status >= 500;
    }
    function errorHandler(options) {
      return function sentryErrorMiddleware(error, _req, res, next) {
        const shouldHandleError = options && options.shouldHandleError || defaultShouldHandleError;
        if (shouldHandleError(error)) {
          core.withScope((_scope) => {
            _scope.setSDKProcessingMetadata({ request: _req });
            const transaction = res.__sentry_transaction;
            if (transaction && !core.getActiveSpan()) {
              _scope.setSpan(transaction);
            }
            const client = core.getClient();
            if (client && sdk.isAutoSessionTrackingEnabled(client)) {
              const isSessionAggregatesMode = client._sessionFlusher !== void 0;
              if (isSessionAggregatesMode) {
                const requestSession = _scope.getRequestSession();
                if (requestSession && requestSession.status !== void 0) {
                  requestSession.status = "crashed";
                }
              }
            }
            const eventId = core.captureException(error, { mechanism: { type: "middleware", handled: false } });
            res.sentry = eventId;
            next(error);
          });
          return;
        }
        next(error);
      };
    }
    var trpcMiddleware = trpc.trpcMiddleware;
    exports.extractRequestData = requestDataDeprecated.extractRequestData;
    exports.parseRequest = requestDataDeprecated.parseRequest;
    exports.errorHandler = errorHandler;
    exports.requestHandler = requestHandler;
    exports.tracingHandler = tracingHandler;
    exports.trpcMiddleware = trpcMiddleware;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/hapi/index.js
var require_hapi = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/hapi/index.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    function isResponseObject(response) {
      return response && response.statusCode !== void 0;
    }
    function isErrorEvent(event) {
      return event && event.error !== void 0;
    }
    function sendErrorToSentry(errorData) {
      core.captureException(errorData, {
        mechanism: {
          type: "hapi",
          handled: false,
          data: {
            function: "hapiErrorPlugin"
          }
        }
      });
    }
    var hapiErrorPlugin = {
      name: "SentryHapiErrorPlugin",
      version: core.SDK_VERSION,
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      register: async function(serverArg) {
        const server = serverArg;
        server.events.on("request", (request, event) => {
          const transaction = core.getActiveTransaction();
          if (isErrorEvent(event)) {
            sendErrorToSentry(event.error);
          }
          if (transaction) {
            transaction.setStatus("internal_error");
            transaction.end();
          }
        });
      }
    };
    var hapiTracingPlugin = {
      name: "SentryHapiTracingPlugin",
      version: core.SDK_VERSION,
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      register: async function(serverArg) {
        const server = serverArg;
        server.ext("onPreHandler", (request, h2) => {
          const transaction = core.continueTrace(
            {
              sentryTrace: request.headers["sentry-trace"] || void 0,
              baggage: request.headers["baggage"] || void 0
            },
            (transactionContext) => {
              return core.startTransaction({
                ...transactionContext,
                op: "hapi.request",
                name: request.route.path,
                description: `${request.route.method} ${request.path}`
              });
            }
          );
          core.getCurrentScope().setSpan(transaction);
          return h2.continue;
        });
        server.ext("onPreResponse", (request, h2) => {
          const transaction = core.getActiveTransaction();
          if (request.response && isResponseObject(request.response) && transaction) {
            const response = request.response;
            response.header("sentry-trace", core.spanToTraceHeader(transaction));
            const dynamicSamplingContext = utils.dynamicSamplingContextToSentryBaggageHeader(
              core.getDynamicSamplingContextFromSpan(transaction)
            );
            if (dynamicSamplingContext) {
              response.header("baggage", dynamicSamplingContext);
            }
          }
          return h2.continue;
        });
        server.ext("onPostHandler", (request, h2) => {
          const transaction = core.getActiveTransaction();
          if (transaction) {
            if (request.response && isResponseObject(request.response)) {
              core.setHttpStatus(transaction, request.response.statusCode);
            }
            transaction.end();
          }
          return h2.continue;
        });
      }
    };
    var INTEGRATION_NAME = "Hapi";
    var _hapiIntegration = (options = {}) => {
      const server = options.server;
      return {
        name: INTEGRATION_NAME,
        setupOnce() {
          if (!server) {
            return;
          }
          utils.fill(server, "start", (originalStart) => {
            return async function() {
              await this.register(hapiTracingPlugin);
              await this.register(hapiErrorPlugin);
              const result = originalStart.apply(this);
              return result;
            };
          });
        }
      };
    };
    var hapiIntegration = core.defineIntegration(_hapiIntegration);
    var Hapi = core.convertIntegrationFnToClass(INTEGRATION_NAME, hapiIntegration);
    exports.Hapi = Hapi;
    exports.hapiErrorPlugin = hapiErrorPlugin;
    exports.hapiIntegration = hapiIntegration;
    exports.hapiTracingPlugin = hapiTracingPlugin;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/index.js
var require_integrations2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/integrations/index.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var console2 = require_console2();
    var http = require_http3();
    var onuncaughtexception = require_onuncaughtexception();
    var onunhandledrejection = require_onunhandledrejection();
    var modules = require_modules();
    var contextlines = require_contextlines();
    var context2 = require_context();
    var core = require_cjs2();
    var index = require_local_variables();
    var index$1 = require_undici();
    var spotlight = require_spotlight();
    var index$2 = require_anr2();
    var index$3 = require_hapi();
    exports.Console = console2.Console;
    exports.Http = http.Http;
    exports.OnUncaughtException = onuncaughtexception.OnUncaughtException;
    exports.OnUnhandledRejection = onunhandledrejection.OnUnhandledRejection;
    exports.Modules = modules.Modules;
    exports.ContextLines = contextlines.ContextLines;
    exports.Context = context2.Context;
    exports.RequestData = core.RequestData;
    exports.LocalVariables = index.LocalVariables;
    exports.Undici = index$1.Undici;
    exports.Spotlight = spotlight.Spotlight;
    exports.Anr = index$2.Anr;
    exports.Hapi = index$3.Hapi;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/tracing/integrations.js
var require_integrations3 = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/tracing/integrations.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var tracing = require_cjs3();
    exports.Apollo = tracing.Apollo;
    exports.Express = tracing.Express;
    exports.GraphQL = tracing.GraphQL;
    exports.Mongo = tracing.Mongo;
    exports.Mysql = tracing.Mysql;
    exports.Postgres = tracing.Postgres;
    exports.Prisma = tracing.Prisma;
  }
});

// ../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/captureconsole.js
var require_captureconsole = __commonJS({
  "../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/captureconsole.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var INTEGRATION_NAME = "CaptureConsole";
    var _captureConsoleIntegration = (options = {}) => {
      const levels = options.levels || utils.CONSOLE_LEVELS;
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        setup(client) {
          if (!("console" in utils.GLOBAL_OBJ)) {
            return;
          }
          utils.addConsoleInstrumentationHandler(({ args, level }) => {
            if (core.getClient() !== client || !levels.includes(level)) {
              return;
            }
            consoleHandler(args, level);
          });
        }
      };
    };
    var captureConsoleIntegration = core.defineIntegration(_captureConsoleIntegration);
    var CaptureConsole = core.convertIntegrationFnToClass(
      INTEGRATION_NAME,
      captureConsoleIntegration
    );
    function consoleHandler(args, level) {
      const captureContext = {
        level: utils.severityLevelFromString(level),
        extra: {
          arguments: args
        }
      };
      core.withScope((scope) => {
        scope.addEventProcessor((event) => {
          event.logger = "console";
          utils.addExceptionMechanism(event, {
            handled: false,
            type: "console"
          });
          return event;
        });
        if (level === "assert" && args[0] === false) {
          const message2 = `Assertion failed: ${utils.safeJoin(args.slice(1), " ") || "console.assert"}`;
          scope.setExtra("arguments", args.slice(1));
          core.captureMessage(message2, captureContext);
          return;
        }
        const error = args.find((arg) => arg instanceof Error);
        if (level === "error" && error) {
          core.captureException(error, captureContext);
          return;
        }
        const message = utils.safeJoin(args, " ");
        core.captureMessage(message, captureContext);
      });
    }
    exports.CaptureConsole = CaptureConsole;
    exports.captureConsoleIntegration = captureConsoleIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/debug.js
var require_debug = __commonJS({
  "../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/debug.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var INTEGRATION_NAME = "Debug";
    var _debugIntegration = (options = {}) => {
      const _options = {
        debugger: false,
        stringify: false,
        ...options
      };
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        setup(client) {
          if (!client.on) {
            return;
          }
          client.on("beforeSendEvent", (event, hint) => {
            if (_options.debugger) {
              debugger;
            }
            utils.consoleSandbox(() => {
              if (_options.stringify) {
                console.log(JSON.stringify(event, null, 2));
                if (hint && Object.keys(hint).length) {
                  console.log(JSON.stringify(hint, null, 2));
                }
              } else {
                console.log(event);
                if (hint && Object.keys(hint).length) {
                  console.log(hint);
                }
              }
            });
          });
        }
      };
    };
    var debugIntegration = core.defineIntegration(_debugIntegration);
    var Debug = core.convertIntegrationFnToClass(INTEGRATION_NAME, debugIntegration);
    exports.Debug = Debug;
    exports.debugIntegration = debugIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/debug-build.js
var require_debug_build5 = __commonJS({
  "../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/debug-build.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
    exports.DEBUG_BUILD = DEBUG_BUILD;
  }
});

// ../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/dedupe.js
var require_dedupe = __commonJS({
  "../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/dedupe.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var debugBuild = require_debug_build5();
    var INTEGRATION_NAME = "Dedupe";
    var _dedupeIntegration = () => {
      let previousEvent;
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        processEvent(currentEvent) {
          if (currentEvent.type) {
            return currentEvent;
          }
          try {
            if (_shouldDropEvent(currentEvent, previousEvent)) {
              debugBuild.DEBUG_BUILD && utils.logger.warn("Event dropped due to being a duplicate of previously captured event.");
              return null;
            }
          } catch (_oO) {
          }
          return previousEvent = currentEvent;
        }
      };
    };
    var dedupeIntegration = core.defineIntegration(_dedupeIntegration);
    var Dedupe = core.convertIntegrationFnToClass(INTEGRATION_NAME, dedupeIntegration);
    function _shouldDropEvent(currentEvent, previousEvent) {
      if (!previousEvent) {
        return false;
      }
      if (_isSameMessageEvent(currentEvent, previousEvent)) {
        return true;
      }
      if (_isSameExceptionEvent(currentEvent, previousEvent)) {
        return true;
      }
      return false;
    }
    function _isSameMessageEvent(currentEvent, previousEvent) {
      const currentMessage = currentEvent.message;
      const previousMessage = previousEvent.message;
      if (!currentMessage && !previousMessage) {
        return false;
      }
      if (currentMessage && !previousMessage || !currentMessage && previousMessage) {
        return false;
      }
      if (currentMessage !== previousMessage) {
        return false;
      }
      if (!_isSameFingerprint(currentEvent, previousEvent)) {
        return false;
      }
      if (!_isSameStacktrace(currentEvent, previousEvent)) {
        return false;
      }
      return true;
    }
    function _isSameExceptionEvent(currentEvent, previousEvent) {
      const previousException = _getExceptionFromEvent(previousEvent);
      const currentException = _getExceptionFromEvent(currentEvent);
      if (!previousException || !currentException) {
        return false;
      }
      if (previousException.type !== currentException.type || previousException.value !== currentException.value) {
        return false;
      }
      if (!_isSameFingerprint(currentEvent, previousEvent)) {
        return false;
      }
      if (!_isSameStacktrace(currentEvent, previousEvent)) {
        return false;
      }
      return true;
    }
    function _isSameStacktrace(currentEvent, previousEvent) {
      let currentFrames = _getFramesFromEvent(currentEvent);
      let previousFrames = _getFramesFromEvent(previousEvent);
      if (!currentFrames && !previousFrames) {
        return true;
      }
      if (currentFrames && !previousFrames || !currentFrames && previousFrames) {
        return false;
      }
      currentFrames = currentFrames;
      previousFrames = previousFrames;
      if (previousFrames.length !== currentFrames.length) {
        return false;
      }
      for (let i2 = 0; i2 < previousFrames.length; i2++) {
        const frameA = previousFrames[i2];
        const frameB = currentFrames[i2];
        if (frameA.filename !== frameB.filename || frameA.lineno !== frameB.lineno || frameA.colno !== frameB.colno || frameA.function !== frameB.function) {
          return false;
        }
      }
      return true;
    }
    function _isSameFingerprint(currentEvent, previousEvent) {
      let currentFingerprint = currentEvent.fingerprint;
      let previousFingerprint = previousEvent.fingerprint;
      if (!currentFingerprint && !previousFingerprint) {
        return true;
      }
      if (currentFingerprint && !previousFingerprint || !currentFingerprint && previousFingerprint) {
        return false;
      }
      currentFingerprint = currentFingerprint;
      previousFingerprint = previousFingerprint;
      try {
        return !!(currentFingerprint.join("") === previousFingerprint.join(""));
      } catch (_oO) {
        return false;
      }
    }
    function _getExceptionFromEvent(event) {
      return event.exception && event.exception.values && event.exception.values[0];
    }
    function _getFramesFromEvent(event) {
      const exception = event.exception;
      if (exception) {
        try {
          return exception.values[0].stacktrace.frames;
        } catch (_oO) {
          return void 0;
        }
      }
      return void 0;
    }
    exports.Dedupe = Dedupe;
    exports._shouldDropEvent = _shouldDropEvent;
    exports.dedupeIntegration = dedupeIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/extraerrordata.js
var require_extraerrordata = __commonJS({
  "../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/extraerrordata.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var debugBuild = require_debug_build5();
    var INTEGRATION_NAME = "ExtraErrorData";
    var _extraErrorDataIntegration = (options = {}) => {
      const depth = options.depth || 3;
      const captureErrorCause = options.captureErrorCause || false;
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        processEvent(event, hint) {
          return _enhanceEventWithErrorData(event, hint, depth, captureErrorCause);
        }
      };
    };
    var extraErrorDataIntegration = core.defineIntegration(_extraErrorDataIntegration);
    var ExtraErrorData = core.convertIntegrationFnToClass(
      INTEGRATION_NAME,
      extraErrorDataIntegration
    );
    function _enhanceEventWithErrorData(event, hint = {}, depth, captureErrorCause) {
      if (!hint.originalException || !utils.isError(hint.originalException)) {
        return event;
      }
      const exceptionName = hint.originalException.name || hint.originalException.constructor.name;
      const errorData = _extractErrorData(hint.originalException, captureErrorCause);
      if (errorData) {
        const contexts = {
          ...event.contexts
        };
        const normalizedErrorData = utils.normalize(errorData, depth);
        if (utils.isPlainObject(normalizedErrorData)) {
          utils.addNonEnumerableProperty(normalizedErrorData, "__sentry_skip_normalization__", true);
          contexts[exceptionName] = normalizedErrorData;
        }
        return {
          ...event,
          contexts
        };
      }
      return event;
    }
    function _extractErrorData(error, captureErrorCause) {
      try {
        const nativeKeys = [
          "name",
          "message",
          "stack",
          "line",
          "column",
          "fileName",
          "lineNumber",
          "columnNumber",
          "toJSON"
        ];
        const extraErrorInfo = {};
        for (const key of Object.keys(error)) {
          if (nativeKeys.indexOf(key) !== -1) {
            continue;
          }
          const value = error[key];
          extraErrorInfo[key] = utils.isError(value) ? value.toString() : value;
        }
        if (captureErrorCause && error.cause !== void 0) {
          extraErrorInfo.cause = utils.isError(error.cause) ? error.cause.toString() : error.cause;
        }
        if (typeof error.toJSON === "function") {
          const serializedError = error.toJSON();
          for (const key of Object.keys(serializedError)) {
            const value = serializedError[key];
            extraErrorInfo[key] = utils.isError(value) ? value.toString() : value;
          }
        }
        return extraErrorInfo;
      } catch (oO) {
        debugBuild.DEBUG_BUILD && utils.logger.error("Unable to extract extra data from the Error object:", oO);
      }
      return null;
    }
    exports.ExtraErrorData = ExtraErrorData;
    exports.extraErrorDataIntegration = extraErrorDataIntegration;
  }
});

// ../../node_modules/.pnpm/localforage@1.10.0/node_modules/localforage/dist/localforage.js
var require_localforage = __commonJS({
  "../../node_modules/.pnpm/localforage@1.10.0/node_modules/localforage/dist/localforage.js"(exports, module) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    (function(f2) {
      if (typeof exports === "object" && typeof module !== "undefined") {
        module.exports = f2();
      } else if (typeof define === "function" && define.amd) {
        define([], f2);
      } else {
        var g;
        if (typeof window !== "undefined") {
          g = window;
        } else if (typeof global !== "undefined") {
          g = global;
        } else if (typeof self !== "undefined") {
          g = self;
        } else {
          g = this;
        }
        g.localforage = f2();
      }
    })(function() {
      var define2, module2, exports2;
      return function e2(t2, n2, r3) {
        function s2(o2, u3) {
          if (!n2[o2]) {
            if (!t2[o2]) {
              var a3 = typeof __require == "function" && __require;
              if (!u3 && a3)
                return a3(o2, true);
              if (i2)
                return i2(o2, true);
              var f2 = new Error("Cannot find module '" + o2 + "'");
              throw f2.code = "MODULE_NOT_FOUND", f2;
            }
            var l2 = n2[o2] = { exports: {} };
            t2[o2][0].call(l2.exports, function(e3) {
              var n3 = t2[o2][1][e3];
              return s2(n3 ? n3 : e3);
            }, l2, l2.exports, e2, t2, n2, r3);
          }
          return n2[o2].exports;
        }
        var i2 = typeof __require == "function" && __require;
        for (var o = 0; o < r3.length; o++)
          s2(r3[o]);
        return s2;
      }({ 1: [function(_dereq_, module3, exports3) {
        (function(global2) {
          "use strict";
          var Mutation = global2.MutationObserver || global2.WebKitMutationObserver;
          var scheduleDrain;
          {
            if (Mutation) {
              var called = 0;
              var observer = new Mutation(nextTick);
              var element = global2.document.createTextNode("");
              observer.observe(element, {
                characterData: true
              });
              scheduleDrain = function() {
                element.data = called = ++called % 2;
              };
            } else if (!global2.setImmediate && typeof global2.MessageChannel !== "undefined") {
              var channel = new global2.MessageChannel();
              channel.port1.onmessage = nextTick;
              scheduleDrain = function() {
                channel.port2.postMessage(0);
              };
            } else if ("document" in global2 && "onreadystatechange" in global2.document.createElement("script")) {
              scheduleDrain = function() {
                var scriptEl = global2.document.createElement("script");
                scriptEl.onreadystatechange = function() {
                  nextTick();
                  scriptEl.onreadystatechange = null;
                  scriptEl.parentNode.removeChild(scriptEl);
                  scriptEl = null;
                };
                global2.document.documentElement.appendChild(scriptEl);
              };
            } else {
              scheduleDrain = function() {
                setTimeout(nextTick, 0);
              };
            }
          }
          var draining;
          var queue2 = [];
          function nextTick() {
            draining = true;
            var i2, oldQueue;
            var len = queue2.length;
            while (len) {
              oldQueue = queue2;
              queue2 = [];
              i2 = -1;
              while (++i2 < len) {
                oldQueue[i2]();
              }
              len = queue2.length;
            }
            draining = false;
          }
          module3.exports = immediate;
          function immediate(task) {
            if (queue2.push(task) === 1 && !draining) {
              scheduleDrain();
            }
          }
        }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
      }, {}], 2: [function(_dereq_, module3, exports3) {
        "use strict";
        var immediate = _dereq_(1);
        function INTERNAL() {
        }
        var handlers = {};
        var REJECTED = ["REJECTED"];
        var FULFILLED = ["FULFILLED"];
        var PENDING = ["PENDING"];
        module3.exports = Promise2;
        function Promise2(resolver) {
          if (typeof resolver !== "function") {
            throw new TypeError("resolver must be a function");
          }
          this.state = PENDING;
          this.queue = [];
          this.outcome = void 0;
          if (resolver !== INTERNAL) {
            safelyResolveThenable(this, resolver);
          }
        }
        Promise2.prototype["catch"] = function(onRejected) {
          return this.then(null, onRejected);
        };
        Promise2.prototype.then = function(onFulfilled, onRejected) {
          if (typeof onFulfilled !== "function" && this.state === FULFILLED || typeof onRejected !== "function" && this.state === REJECTED) {
            return this;
          }
          var promise = new this.constructor(INTERNAL);
          if (this.state !== PENDING) {
            var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
            unwrap(promise, resolver, this.outcome);
          } else {
            this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
          }
          return promise;
        };
        function QueueItem(promise, onFulfilled, onRejected) {
          this.promise = promise;
          if (typeof onFulfilled === "function") {
            this.onFulfilled = onFulfilled;
            this.callFulfilled = this.otherCallFulfilled;
          }
          if (typeof onRejected === "function") {
            this.onRejected = onRejected;
            this.callRejected = this.otherCallRejected;
          }
        }
        QueueItem.prototype.callFulfilled = function(value) {
          handlers.resolve(this.promise, value);
        };
        QueueItem.prototype.otherCallFulfilled = function(value) {
          unwrap(this.promise, this.onFulfilled, value);
        };
        QueueItem.prototype.callRejected = function(value) {
          handlers.reject(this.promise, value);
        };
        QueueItem.prototype.otherCallRejected = function(value) {
          unwrap(this.promise, this.onRejected, value);
        };
        function unwrap(promise, func, value) {
          immediate(function() {
            var returnValue;
            try {
              returnValue = func(value);
            } catch (e2) {
              return handlers.reject(promise, e2);
            }
            if (returnValue === promise) {
              handlers.reject(promise, new TypeError("Cannot resolve promise with itself"));
            } else {
              handlers.resolve(promise, returnValue);
            }
          });
        }
        handlers.resolve = function(self2, value) {
          var result = tryCatch(getThen, value);
          if (result.status === "error") {
            return handlers.reject(self2, result.value);
          }
          var thenable = result.value;
          if (thenable) {
            safelyResolveThenable(self2, thenable);
          } else {
            self2.state = FULFILLED;
            self2.outcome = value;
            var i2 = -1;
            var len = self2.queue.length;
            while (++i2 < len) {
              self2.queue[i2].callFulfilled(value);
            }
          }
          return self2;
        };
        handlers.reject = function(self2, error) {
          self2.state = REJECTED;
          self2.outcome = error;
          var i2 = -1;
          var len = self2.queue.length;
          while (++i2 < len) {
            self2.queue[i2].callRejected(error);
          }
          return self2;
        };
        function getThen(obj) {
          var then = obj && obj.then;
          if (obj && (typeof obj === "object" || typeof obj === "function") && typeof then === "function") {
            return function appyThen() {
              then.apply(obj, arguments);
            };
          }
        }
        function safelyResolveThenable(self2, thenable) {
          var called = false;
          function onError(value) {
            if (called) {
              return;
            }
            called = true;
            handlers.reject(self2, value);
          }
          function onSuccess(value) {
            if (called) {
              return;
            }
            called = true;
            handlers.resolve(self2, value);
          }
          function tryToUnwrap() {
            thenable(onSuccess, onError);
          }
          var result = tryCatch(tryToUnwrap);
          if (result.status === "error") {
            onError(result.value);
          }
        }
        function tryCatch(func, value) {
          var out = {};
          try {
            out.value = func(value);
            out.status = "success";
          } catch (e2) {
            out.status = "error";
            out.value = e2;
          }
          return out;
        }
        Promise2.resolve = resolve2;
        function resolve2(value) {
          if (value instanceof this) {
            return value;
          }
          return handlers.resolve(new this(INTERNAL), value);
        }
        Promise2.reject = reject;
        function reject(reason) {
          var promise = new this(INTERNAL);
          return handlers.reject(promise, reason);
        }
        Promise2.all = all;
        function all(iterable) {
          var self2 = this;
          if (Object.prototype.toString.call(iterable) !== "[object Array]") {
            return this.reject(new TypeError("must be an array"));
          }
          var len = iterable.length;
          var called = false;
          if (!len) {
            return this.resolve([]);
          }
          var values = new Array(len);
          var resolved = 0;
          var i2 = -1;
          var promise = new this(INTERNAL);
          while (++i2 < len) {
            allResolver(iterable[i2], i2);
          }
          return promise;
          function allResolver(value, i3) {
            self2.resolve(value).then(resolveFromAll, function(error) {
              if (!called) {
                called = true;
                handlers.reject(promise, error);
              }
            });
            function resolveFromAll(outValue) {
              values[i3] = outValue;
              if (++resolved === len && !called) {
                called = true;
                handlers.resolve(promise, values);
              }
            }
          }
        }
        Promise2.race = race;
        function race(iterable) {
          var self2 = this;
          if (Object.prototype.toString.call(iterable) !== "[object Array]") {
            return this.reject(new TypeError("must be an array"));
          }
          var len = iterable.length;
          var called = false;
          if (!len) {
            return this.resolve([]);
          }
          var i2 = -1;
          var promise = new this(INTERNAL);
          while (++i2 < len) {
            resolver(iterable[i2]);
          }
          return promise;
          function resolver(value) {
            self2.resolve(value).then(function(response) {
              if (!called) {
                called = true;
                handlers.resolve(promise, response);
              }
            }, function(error) {
              if (!called) {
                called = true;
                handlers.reject(promise, error);
              }
            });
          }
        }
      }, { "1": 1 }], 3: [function(_dereq_, module3, exports3) {
        (function(global2) {
          "use strict";
          if (typeof global2.Promise !== "function") {
            global2.Promise = _dereq_(2);
          }
        }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
      }, { "2": 2 }], 4: [function(_dereq_, module3, exports3) {
        "use strict";
        var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
          return typeof obj;
        } : function(obj) {
          return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
        function _classCallCheck(instance, Constructor) {
          if (!(instance instanceof Constructor)) {
            throw new TypeError("Cannot call a class as a function");
          }
        }
        function getIDB() {
          try {
            if (typeof indexedDB !== "undefined") {
              return indexedDB;
            }
            if (typeof webkitIndexedDB !== "undefined") {
              return webkitIndexedDB;
            }
            if (typeof mozIndexedDB !== "undefined") {
              return mozIndexedDB;
            }
            if (typeof OIndexedDB !== "undefined") {
              return OIndexedDB;
            }
            if (typeof msIndexedDB !== "undefined") {
              return msIndexedDB;
            }
          } catch (e2) {
            return;
          }
        }
        var idb = getIDB();
        function isIndexedDBValid() {
          try {
            if (!idb || !idb.open) {
              return false;
            }
            var isSafari = typeof openDatabase !== "undefined" && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);
            var hasFetch = typeof fetch === "function" && fetch.toString().indexOf("[native code") !== -1;
            return (!isSafari || hasFetch) && typeof indexedDB !== "undefined" && // some outdated implementations of IDB that appear on Samsung
            // and HTC Android devices <4.4 are missing IDBKeyRange
            // See: https://github.com/mozilla/localForage/issues/128
            // See: https://github.com/mozilla/localForage/issues/272
            typeof IDBKeyRange !== "undefined";
          } catch (e2) {
            return false;
          }
        }
        function createBlob(parts, properties) {
          parts = parts || [];
          properties = properties || {};
          try {
            return new Blob(parts, properties);
          } catch (e2) {
            if (e2.name !== "TypeError") {
              throw e2;
            }
            var Builder = typeof BlobBuilder !== "undefined" ? BlobBuilder : typeof MSBlobBuilder !== "undefined" ? MSBlobBuilder : typeof MozBlobBuilder !== "undefined" ? MozBlobBuilder : WebKitBlobBuilder;
            var builder = new Builder();
            for (var i2 = 0; i2 < parts.length; i2 += 1) {
              builder.append(parts[i2]);
            }
            return builder.getBlob(properties.type);
          }
        }
        if (typeof Promise === "undefined") {
          _dereq_(3);
        }
        var Promise$1 = Promise;
        function executeCallback(promise, callback) {
          if (callback) {
            promise.then(function(result) {
              callback(null, result);
            }, function(error) {
              callback(error);
            });
          }
        }
        function executeTwoCallbacks(promise, callback, errorCallback) {
          if (typeof callback === "function") {
            promise.then(callback);
          }
          if (typeof errorCallback === "function") {
            promise["catch"](errorCallback);
          }
        }
        function normalizeKey(key2) {
          if (typeof key2 !== "string") {
            console.warn(key2 + " used as a key, but it is not a string.");
            key2 = String(key2);
          }
          return key2;
        }
        function getCallback() {
          if (arguments.length && typeof arguments[arguments.length - 1] === "function") {
            return arguments[arguments.length - 1];
          }
        }
        var DETECT_BLOB_SUPPORT_STORE = "local-forage-detect-blob-support";
        var supportsBlobs = void 0;
        var dbContexts = {};
        var toString2 = Object.prototype.toString;
        var READ_ONLY = "readonly";
        var READ_WRITE = "readwrite";
        function _binStringToArrayBuffer(bin) {
          var length2 = bin.length;
          var buf = new ArrayBuffer(length2);
          var arr = new Uint8Array(buf);
          for (var i2 = 0; i2 < length2; i2++) {
            arr[i2] = bin.charCodeAt(i2);
          }
          return buf;
        }
        function _checkBlobSupportWithoutCaching(idb2) {
          return new Promise$1(function(resolve2) {
            var txn = idb2.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
            var blob = createBlob([""]);
            txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, "key");
            txn.onabort = function(e2) {
              e2.preventDefault();
              e2.stopPropagation();
              resolve2(false);
            };
            txn.oncomplete = function() {
              var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
              var matchedEdge = navigator.userAgent.match(/Edge\//);
              resolve2(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
            };
          })["catch"](function() {
            return false;
          });
        }
        function _checkBlobSupport(idb2) {
          if (typeof supportsBlobs === "boolean") {
            return Promise$1.resolve(supportsBlobs);
          }
          return _checkBlobSupportWithoutCaching(idb2).then(function(value) {
            supportsBlobs = value;
            return supportsBlobs;
          });
        }
        function _deferReadiness(dbInfo) {
          var dbContext = dbContexts[dbInfo.name];
          var deferredOperation = {};
          deferredOperation.promise = new Promise$1(function(resolve2, reject) {
            deferredOperation.resolve = resolve2;
            deferredOperation.reject = reject;
          });
          dbContext.deferredOperations.push(deferredOperation);
          if (!dbContext.dbReady) {
            dbContext.dbReady = deferredOperation.promise;
          } else {
            dbContext.dbReady = dbContext.dbReady.then(function() {
              return deferredOperation.promise;
            });
          }
        }
        function _advanceReadiness(dbInfo) {
          var dbContext = dbContexts[dbInfo.name];
          var deferredOperation = dbContext.deferredOperations.pop();
          if (deferredOperation) {
            deferredOperation.resolve();
            return deferredOperation.promise;
          }
        }
        function _rejectReadiness(dbInfo, err) {
          var dbContext = dbContexts[dbInfo.name];
          var deferredOperation = dbContext.deferredOperations.pop();
          if (deferredOperation) {
            deferredOperation.reject(err);
            return deferredOperation.promise;
          }
        }
        function _getConnection(dbInfo, upgradeNeeded) {
          return new Promise$1(function(resolve2, reject) {
            dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();
            if (dbInfo.db) {
              if (upgradeNeeded) {
                _deferReadiness(dbInfo);
                dbInfo.db.close();
              } else {
                return resolve2(dbInfo.db);
              }
            }
            var dbArgs = [dbInfo.name];
            if (upgradeNeeded) {
              dbArgs.push(dbInfo.version);
            }
            var openreq = idb.open.apply(idb, dbArgs);
            if (upgradeNeeded) {
              openreq.onupgradeneeded = function(e2) {
                var db = openreq.result;
                try {
                  db.createObjectStore(dbInfo.storeName);
                  if (e2.oldVersion <= 1) {
                    db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
                  }
                } catch (ex) {
                  if (ex.name === "ConstraintError") {
                    console.warn('The database "' + dbInfo.name + '" has been upgraded from version ' + e2.oldVersion + " to version " + e2.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
                  } else {
                    throw ex;
                  }
                }
              };
            }
            openreq.onerror = function(e2) {
              e2.preventDefault();
              reject(openreq.error);
            };
            openreq.onsuccess = function() {
              var db = openreq.result;
              db.onversionchange = function(e2) {
                e2.target.close();
              };
              resolve2(db);
              _advanceReadiness(dbInfo);
            };
          });
        }
        function _getOriginalConnection(dbInfo) {
          return _getConnection(dbInfo, false);
        }
        function _getUpgradedConnection(dbInfo) {
          return _getConnection(dbInfo, true);
        }
        function _isUpgradeNeeded(dbInfo, defaultVersion) {
          if (!dbInfo.db) {
            return true;
          }
          var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
          var isDowngrade = dbInfo.version < dbInfo.db.version;
          var isUpgrade = dbInfo.version > dbInfo.db.version;
          if (isDowngrade) {
            if (dbInfo.version !== defaultVersion) {
              console.warn('The database "' + dbInfo.name + `" can't be downgraded from version ` + dbInfo.db.version + " to version " + dbInfo.version + ".");
            }
            dbInfo.version = dbInfo.db.version;
          }
          if (isUpgrade || isNewStore) {
            if (isNewStore) {
              var incVersion = dbInfo.db.version + 1;
              if (incVersion > dbInfo.version) {
                dbInfo.version = incVersion;
              }
            }
            return true;
          }
          return false;
        }
        function _encodeBlob(blob) {
          return new Promise$1(function(resolve2, reject) {
            var reader = new FileReader();
            reader.onerror = reject;
            reader.onloadend = function(e2) {
              var base64 = btoa(e2.target.result || "");
              resolve2({
                __local_forage_encoded_blob: true,
                data: base64,
                type: blob.type
              });
            };
            reader.readAsBinaryString(blob);
          });
        }
        function _decodeBlob(encodedBlob) {
          var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
          return createBlob([arrayBuff], { type: encodedBlob.type });
        }
        function _isEncodedBlob(value) {
          return value && value.__local_forage_encoded_blob;
        }
        function _fullyReady(callback) {
          var self2 = this;
          var promise = self2._initReady().then(function() {
            var dbContext = dbContexts[self2._dbInfo.name];
            if (dbContext && dbContext.dbReady) {
              return dbContext.dbReady;
            }
          });
          executeTwoCallbacks(promise, callback, callback);
          return promise;
        }
        function _tryReconnect(dbInfo) {
          _deferReadiness(dbInfo);
          var dbContext = dbContexts[dbInfo.name];
          var forages = dbContext.forages;
          for (var i2 = 0; i2 < forages.length; i2++) {
            var forage = forages[i2];
            if (forage._dbInfo.db) {
              forage._dbInfo.db.close();
              forage._dbInfo.db = null;
            }
          }
          dbInfo.db = null;
          return _getOriginalConnection(dbInfo).then(function(db) {
            dbInfo.db = db;
            if (_isUpgradeNeeded(dbInfo)) {
              return _getUpgradedConnection(dbInfo);
            }
            return db;
          }).then(function(db) {
            dbInfo.db = dbContext.db = db;
            for (var i3 = 0; i3 < forages.length; i3++) {
              forages[i3]._dbInfo.db = db;
            }
          })["catch"](function(err) {
            _rejectReadiness(dbInfo, err);
            throw err;
          });
        }
        function createTransaction(dbInfo, mode, callback, retries) {
          if (retries === void 0) {
            retries = 1;
          }
          try {
            var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
            callback(null, tx);
          } catch (err) {
            if (retries > 0 && (!dbInfo.db || err.name === "InvalidStateError" || err.name === "NotFoundError")) {
              return Promise$1.resolve().then(function() {
                if (!dbInfo.db || err.name === "NotFoundError" && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
                  if (dbInfo.db) {
                    dbInfo.version = dbInfo.db.version + 1;
                  }
                  return _getUpgradedConnection(dbInfo);
                }
              }).then(function() {
                return _tryReconnect(dbInfo).then(function() {
                  createTransaction(dbInfo, mode, callback, retries - 1);
                });
              })["catch"](callback);
            }
            callback(err);
          }
        }
        function createDbContext() {
          return {
            // Running localForages sharing a database.
            forages: [],
            // Shared database.
            db: null,
            // Database readiness (promise).
            dbReady: null,
            // Deferred operations on the database.
            deferredOperations: []
          };
        }
        function _initStorage(options) {
          var self2 = this;
          var dbInfo = {
            db: null
          };
          if (options) {
            for (var i2 in options) {
              dbInfo[i2] = options[i2];
            }
          }
          var dbContext = dbContexts[dbInfo.name];
          if (!dbContext) {
            dbContext = createDbContext();
            dbContexts[dbInfo.name] = dbContext;
          }
          dbContext.forages.push(self2);
          if (!self2._initReady) {
            self2._initReady = self2.ready;
            self2.ready = _fullyReady;
          }
          var initPromises = [];
          function ignoreErrors() {
            return Promise$1.resolve();
          }
          for (var j2 = 0; j2 < dbContext.forages.length; j2++) {
            var forage = dbContext.forages[j2];
            if (forage !== self2) {
              initPromises.push(forage._initReady()["catch"](ignoreErrors));
            }
          }
          var forages = dbContext.forages.slice(0);
          return Promise$1.all(initPromises).then(function() {
            dbInfo.db = dbContext.db;
            return _getOriginalConnection(dbInfo);
          }).then(function(db) {
            dbInfo.db = db;
            if (_isUpgradeNeeded(dbInfo, self2._defaultConfig.version)) {
              return _getUpgradedConnection(dbInfo);
            }
            return db;
          }).then(function(db) {
            dbInfo.db = dbContext.db = db;
            self2._dbInfo = dbInfo;
            for (var k2 = 0; k2 < forages.length; k2++) {
              var forage2 = forages[k2];
              if (forage2 !== self2) {
                forage2._dbInfo.db = dbInfo.db;
                forage2._dbInfo.version = dbInfo.version;
              }
            }
          });
        }
        function getItem(key2, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = new Promise$1(function(resolve2, reject) {
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var req = store.get(key2);
                  req.onsuccess = function() {
                    var value = req.result;
                    if (value === void 0) {
                      value = null;
                    }
                    if (_isEncodedBlob(value)) {
                      value = _decodeBlob(value);
                    }
                    resolve2(value);
                  };
                  req.onerror = function() {
                    reject(req.error);
                  };
                } catch (e2) {
                  reject(e2);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function iterate(iterator, callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve2, reject) {
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var req = store.openCursor();
                  var iterationNumber = 1;
                  req.onsuccess = function() {
                    var cursor = req.result;
                    if (cursor) {
                      var value = cursor.value;
                      if (_isEncodedBlob(value)) {
                        value = _decodeBlob(value);
                      }
                      var result = iterator(value, cursor.key, iterationNumber++);
                      if (result !== void 0) {
                        resolve2(result);
                      } else {
                        cursor["continue"]();
                      }
                    } else {
                      resolve2();
                    }
                  };
                  req.onerror = function() {
                    reject(req.error);
                  };
                } catch (e2) {
                  reject(e2);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function setItem(key2, value, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = new Promise$1(function(resolve2, reject) {
            var dbInfo;
            self2.ready().then(function() {
              dbInfo = self2._dbInfo;
              if (toString2.call(value) === "[object Blob]") {
                return _checkBlobSupport(dbInfo.db).then(function(blobSupport) {
                  if (blobSupport) {
                    return value;
                  }
                  return _encodeBlob(value);
                });
              }
              return value;
            }).then(function(value2) {
              createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  if (value2 === null) {
                    value2 = void 0;
                  }
                  var req = store.put(value2, key2);
                  transaction.oncomplete = function() {
                    if (value2 === void 0) {
                      value2 = null;
                    }
                    resolve2(value2);
                  };
                  transaction.onabort = transaction.onerror = function() {
                    var err2 = req.error ? req.error : req.transaction.error;
                    reject(err2);
                  };
                } catch (e2) {
                  reject(e2);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function removeItem(key2, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = new Promise$1(function(resolve2, reject) {
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var req = store["delete"](key2);
                  transaction.oncomplete = function() {
                    resolve2();
                  };
                  transaction.onerror = function() {
                    reject(req.error);
                  };
                  transaction.onabort = function() {
                    var err2 = req.error ? req.error : req.transaction.error;
                    reject(err2);
                  };
                } catch (e2) {
                  reject(e2);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function clear(callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve2, reject) {
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var req = store.clear();
                  transaction.oncomplete = function() {
                    resolve2();
                  };
                  transaction.onabort = transaction.onerror = function() {
                    var err2 = req.error ? req.error : req.transaction.error;
                    reject(err2);
                  };
                } catch (e2) {
                  reject(e2);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function length(callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve2, reject) {
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var req = store.count();
                  req.onsuccess = function() {
                    resolve2(req.result);
                  };
                  req.onerror = function() {
                    reject(req.error);
                  };
                } catch (e2) {
                  reject(e2);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function key(n2, callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve2, reject) {
            if (n2 < 0) {
              resolve2(null);
              return;
            }
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var advanced = false;
                  var req = store.openKeyCursor();
                  req.onsuccess = function() {
                    var cursor = req.result;
                    if (!cursor) {
                      resolve2(null);
                      return;
                    }
                    if (n2 === 0) {
                      resolve2(cursor.key);
                    } else {
                      if (!advanced) {
                        advanced = true;
                        cursor.advance(n2);
                      } else {
                        resolve2(cursor.key);
                      }
                    }
                  };
                  req.onerror = function() {
                    reject(req.error);
                  };
                } catch (e2) {
                  reject(e2);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function keys(callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve2, reject) {
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var req = store.openKeyCursor();
                  var keys2 = [];
                  req.onsuccess = function() {
                    var cursor = req.result;
                    if (!cursor) {
                      resolve2(keys2);
                      return;
                    }
                    keys2.push(cursor.key);
                    cursor["continue"]();
                  };
                  req.onerror = function() {
                    reject(req.error);
                  };
                } catch (e2) {
                  reject(e2);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function dropInstance(options, callback) {
          callback = getCallback.apply(this, arguments);
          var currentConfig = this.config();
          options = typeof options !== "function" && options || {};
          if (!options.name) {
            options.name = options.name || currentConfig.name;
            options.storeName = options.storeName || currentConfig.storeName;
          }
          var self2 = this;
          var promise;
          if (!options.name) {
            promise = Promise$1.reject("Invalid arguments");
          } else {
            var isCurrentDb = options.name === currentConfig.name && self2._dbInfo.db;
            var dbPromise = isCurrentDb ? Promise$1.resolve(self2._dbInfo.db) : _getOriginalConnection(options).then(function(db) {
              var dbContext = dbContexts[options.name];
              var forages = dbContext.forages;
              dbContext.db = db;
              for (var i2 = 0; i2 < forages.length; i2++) {
                forages[i2]._dbInfo.db = db;
              }
              return db;
            });
            if (!options.storeName) {
              promise = dbPromise.then(function(db) {
                _deferReadiness(options);
                var dbContext = dbContexts[options.name];
                var forages = dbContext.forages;
                db.close();
                for (var i2 = 0; i2 < forages.length; i2++) {
                  var forage = forages[i2];
                  forage._dbInfo.db = null;
                }
                var dropDBPromise = new Promise$1(function(resolve2, reject) {
                  var req = idb.deleteDatabase(options.name);
                  req.onerror = function() {
                    var db2 = req.result;
                    if (db2) {
                      db2.close();
                    }
                    reject(req.error);
                  };
                  req.onblocked = function() {
                    console.warn('dropInstance blocked for database "' + options.name + '" until all open connections are closed');
                  };
                  req.onsuccess = function() {
                    var db2 = req.result;
                    if (db2) {
                      db2.close();
                    }
                    resolve2(db2);
                  };
                });
                return dropDBPromise.then(function(db2) {
                  dbContext.db = db2;
                  for (var i3 = 0; i3 < forages.length; i3++) {
                    var _forage = forages[i3];
                    _advanceReadiness(_forage._dbInfo);
                  }
                })["catch"](function(err) {
                  (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function() {
                  });
                  throw err;
                });
              });
            } else {
              promise = dbPromise.then(function(db) {
                if (!db.objectStoreNames.contains(options.storeName)) {
                  return;
                }
                var newVersion = db.version + 1;
                _deferReadiness(options);
                var dbContext = dbContexts[options.name];
                var forages = dbContext.forages;
                db.close();
                for (var i2 = 0; i2 < forages.length; i2++) {
                  var forage = forages[i2];
                  forage._dbInfo.db = null;
                  forage._dbInfo.version = newVersion;
                }
                var dropObjectPromise = new Promise$1(function(resolve2, reject) {
                  var req = idb.open(options.name, newVersion);
                  req.onerror = function(err) {
                    var db2 = req.result;
                    db2.close();
                    reject(err);
                  };
                  req.onupgradeneeded = function() {
                    var db2 = req.result;
                    db2.deleteObjectStore(options.storeName);
                  };
                  req.onsuccess = function() {
                    var db2 = req.result;
                    db2.close();
                    resolve2(db2);
                  };
                });
                return dropObjectPromise.then(function(db2) {
                  dbContext.db = db2;
                  for (var j2 = 0; j2 < forages.length; j2++) {
                    var _forage2 = forages[j2];
                    _forage2._dbInfo.db = db2;
                    _advanceReadiness(_forage2._dbInfo);
                  }
                })["catch"](function(err) {
                  (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function() {
                  });
                  throw err;
                });
              });
            }
          }
          executeCallback(promise, callback);
          return promise;
        }
        var asyncStorage = {
          _driver: "asyncStorage",
          _initStorage,
          _support: isIndexedDBValid(),
          iterate,
          getItem,
          setItem,
          removeItem,
          clear,
          length,
          key,
          keys,
          dropInstance
        };
        function isWebSQLValid() {
          return typeof openDatabase === "function";
        }
        var BASE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var BLOB_TYPE_PREFIX = "~~local_forage_type~";
        var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
        var SERIALIZED_MARKER = "__lfsc__:";
        var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
        var TYPE_ARRAYBUFFER = "arbf";
        var TYPE_BLOB = "blob";
        var TYPE_INT8ARRAY = "si08";
        var TYPE_UINT8ARRAY = "ui08";
        var TYPE_UINT8CLAMPEDARRAY = "uic8";
        var TYPE_INT16ARRAY = "si16";
        var TYPE_INT32ARRAY = "si32";
        var TYPE_UINT16ARRAY = "ur16";
        var TYPE_UINT32ARRAY = "ui32";
        var TYPE_FLOAT32ARRAY = "fl32";
        var TYPE_FLOAT64ARRAY = "fl64";
        var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
        var toString$1 = Object.prototype.toString;
        function stringToBuffer(serializedString) {
          var bufferLength = serializedString.length * 0.75;
          var len = serializedString.length;
          var i2;
          var p3 = 0;
          var encoded1, encoded2, encoded3, encoded4;
          if (serializedString[serializedString.length - 1] === "=") {
            bufferLength--;
            if (serializedString[serializedString.length - 2] === "=") {
              bufferLength--;
            }
          }
          var buffer = new ArrayBuffer(bufferLength);
          var bytes = new Uint8Array(buffer);
          for (i2 = 0; i2 < len; i2 += 4) {
            encoded1 = BASE_CHARS.indexOf(serializedString[i2]);
            encoded2 = BASE_CHARS.indexOf(serializedString[i2 + 1]);
            encoded3 = BASE_CHARS.indexOf(serializedString[i2 + 2]);
            encoded4 = BASE_CHARS.indexOf(serializedString[i2 + 3]);
            bytes[p3++] = encoded1 << 2 | encoded2 >> 4;
            bytes[p3++] = (encoded2 & 15) << 4 | encoded3 >> 2;
            bytes[p3++] = (encoded3 & 3) << 6 | encoded4 & 63;
          }
          return buffer;
        }
        function bufferToString(buffer) {
          var bytes = new Uint8Array(buffer);
          var base64String = "";
          var i2;
          for (i2 = 0; i2 < bytes.length; i2 += 3) {
            base64String += BASE_CHARS[bytes[i2] >> 2];
            base64String += BASE_CHARS[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];
            base64String += BASE_CHARS[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];
            base64String += BASE_CHARS[bytes[i2 + 2] & 63];
          }
          if (bytes.length % 3 === 2) {
            base64String = base64String.substring(0, base64String.length - 1) + "=";
          } else if (bytes.length % 3 === 1) {
            base64String = base64String.substring(0, base64String.length - 2) + "==";
          }
          return base64String;
        }
        function serialize(value, callback) {
          var valueType = "";
          if (value) {
            valueType = toString$1.call(value);
          }
          if (value && (valueType === "[object ArrayBuffer]" || value.buffer && toString$1.call(value.buffer) === "[object ArrayBuffer]")) {
            var buffer;
            var marker = SERIALIZED_MARKER;
            if (value instanceof ArrayBuffer) {
              buffer = value;
              marker += TYPE_ARRAYBUFFER;
            } else {
              buffer = value.buffer;
              if (valueType === "[object Int8Array]") {
                marker += TYPE_INT8ARRAY;
              } else if (valueType === "[object Uint8Array]") {
                marker += TYPE_UINT8ARRAY;
              } else if (valueType === "[object Uint8ClampedArray]") {
                marker += TYPE_UINT8CLAMPEDARRAY;
              } else if (valueType === "[object Int16Array]") {
                marker += TYPE_INT16ARRAY;
              } else if (valueType === "[object Uint16Array]") {
                marker += TYPE_UINT16ARRAY;
              } else if (valueType === "[object Int32Array]") {
                marker += TYPE_INT32ARRAY;
              } else if (valueType === "[object Uint32Array]") {
                marker += TYPE_UINT32ARRAY;
              } else if (valueType === "[object Float32Array]") {
                marker += TYPE_FLOAT32ARRAY;
              } else if (valueType === "[object Float64Array]") {
                marker += TYPE_FLOAT64ARRAY;
              } else {
                callback(new Error("Failed to get type for BinaryArray"));
              }
            }
            callback(marker + bufferToString(buffer));
          } else if (valueType === "[object Blob]") {
            var fileReader = new FileReader();
            fileReader.onload = function() {
              var str = BLOB_TYPE_PREFIX + value.type + "~" + bufferToString(this.result);
              callback(SERIALIZED_MARKER + TYPE_BLOB + str);
            };
            fileReader.readAsArrayBuffer(value);
          } else {
            try {
              callback(JSON.stringify(value));
            } catch (e2) {
              console.error("Couldn't convert value into a JSON string: ", value);
              callback(null, e2);
            }
          }
        }
        function deserialize(value) {
          if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
            return JSON.parse(value);
          }
          var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
          var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
          var blobType;
          if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
            var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
            blobType = matcher[1];
            serializedString = serializedString.substring(matcher[0].length);
          }
          var buffer = stringToBuffer(serializedString);
          switch (type) {
            case TYPE_ARRAYBUFFER:
              return buffer;
            case TYPE_BLOB:
              return createBlob([buffer], { type: blobType });
            case TYPE_INT8ARRAY:
              return new Int8Array(buffer);
            case TYPE_UINT8ARRAY:
              return new Uint8Array(buffer);
            case TYPE_UINT8CLAMPEDARRAY:
              return new Uint8ClampedArray(buffer);
            case TYPE_INT16ARRAY:
              return new Int16Array(buffer);
            case TYPE_UINT16ARRAY:
              return new Uint16Array(buffer);
            case TYPE_INT32ARRAY:
              return new Int32Array(buffer);
            case TYPE_UINT32ARRAY:
              return new Uint32Array(buffer);
            case TYPE_FLOAT32ARRAY:
              return new Float32Array(buffer);
            case TYPE_FLOAT64ARRAY:
              return new Float64Array(buffer);
            default:
              throw new Error("Unkown type: " + type);
          }
        }
        var localforageSerializer = {
          serialize,
          deserialize,
          stringToBuffer,
          bufferToString
        };
        function createDbTable(t2, dbInfo, callback, errorCallback) {
          t2.executeSql("CREATE TABLE IF NOT EXISTS " + dbInfo.storeName + " (id INTEGER PRIMARY KEY, key unique, value)", [], callback, errorCallback);
        }
        function _initStorage$1(options) {
          var self2 = this;
          var dbInfo = {
            db: null
          };
          if (options) {
            for (var i2 in options) {
              dbInfo[i2] = typeof options[i2] !== "string" ? options[i2].toString() : options[i2];
            }
          }
          var dbInfoPromise = new Promise$1(function(resolve2, reject) {
            try {
              dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
            } catch (e2) {
              return reject(e2);
            }
            dbInfo.db.transaction(function(t2) {
              createDbTable(t2, dbInfo, function() {
                self2._dbInfo = dbInfo;
                resolve2();
              }, function(t3, error) {
                reject(error);
              });
            }, reject);
          });
          dbInfo.serializer = localforageSerializer;
          return dbInfoPromise;
        }
        function tryExecuteSql(t2, dbInfo, sqlStatement, args, callback, errorCallback) {
          t2.executeSql(sqlStatement, args, callback, function(t3, error) {
            if (error.code === error.SYNTAX_ERR) {
              t3.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?", [dbInfo.storeName], function(t4, results) {
                if (!results.rows.length) {
                  createDbTable(t4, dbInfo, function() {
                    t4.executeSql(sqlStatement, args, callback, errorCallback);
                  }, errorCallback);
                } else {
                  errorCallback(t4, error);
                }
              }, errorCallback);
            } else {
              errorCallback(t3, error);
            }
          }, errorCallback);
        }
        function getItem$1(key2, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = new Promise$1(function(resolve2, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t2) {
                tryExecuteSql(t2, dbInfo, "SELECT * FROM " + dbInfo.storeName + " WHERE key = ? LIMIT 1", [key2], function(t3, results) {
                  var result = results.rows.length ? results.rows.item(0).value : null;
                  if (result) {
                    result = dbInfo.serializer.deserialize(result);
                  }
                  resolve2(result);
                }, function(t3, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function iterate$1(iterator, callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve2, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t2) {
                tryExecuteSql(t2, dbInfo, "SELECT * FROM " + dbInfo.storeName, [], function(t3, results) {
                  var rows = results.rows;
                  var length2 = rows.length;
                  for (var i2 = 0; i2 < length2; i2++) {
                    var item = rows.item(i2);
                    var result = item.value;
                    if (result) {
                      result = dbInfo.serializer.deserialize(result);
                    }
                    result = iterator(result, item.key, i2 + 1);
                    if (result !== void 0) {
                      resolve2(result);
                      return;
                    }
                  }
                  resolve2();
                }, function(t3, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function _setItem(key2, value, callback, retriesLeft) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = new Promise$1(function(resolve2, reject) {
            self2.ready().then(function() {
              if (value === void 0) {
                value = null;
              }
              var originalValue = value;
              var dbInfo = self2._dbInfo;
              dbInfo.serializer.serialize(value, function(value2, error) {
                if (error) {
                  reject(error);
                } else {
                  dbInfo.db.transaction(function(t2) {
                    tryExecuteSql(t2, dbInfo, "INSERT OR REPLACE INTO " + dbInfo.storeName + " (key, value) VALUES (?, ?)", [key2, value2], function() {
                      resolve2(originalValue);
                    }, function(t3, error2) {
                      reject(error2);
                    });
                  }, function(sqlError) {
                    if (sqlError.code === sqlError.QUOTA_ERR) {
                      if (retriesLeft > 0) {
                        resolve2(_setItem.apply(self2, [key2, originalValue, callback, retriesLeft - 1]));
                        return;
                      }
                      reject(sqlError);
                    }
                  });
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function setItem$1(key2, value, callback) {
          return _setItem.apply(this, [key2, value, callback, 1]);
        }
        function removeItem$1(key2, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = new Promise$1(function(resolve2, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t2) {
                tryExecuteSql(t2, dbInfo, "DELETE FROM " + dbInfo.storeName + " WHERE key = ?", [key2], function() {
                  resolve2();
                }, function(t3, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function clear$1(callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve2, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t2) {
                tryExecuteSql(t2, dbInfo, "DELETE FROM " + dbInfo.storeName, [], function() {
                  resolve2();
                }, function(t3, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function length$1(callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve2, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t2) {
                tryExecuteSql(t2, dbInfo, "SELECT COUNT(key) as c FROM " + dbInfo.storeName, [], function(t3, results) {
                  var result = results.rows.item(0).c;
                  resolve2(result);
                }, function(t3, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function key$1(n2, callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve2, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t2) {
                tryExecuteSql(t2, dbInfo, "SELECT key FROM " + dbInfo.storeName + " WHERE id = ? LIMIT 1", [n2 + 1], function(t3, results) {
                  var result = results.rows.length ? results.rows.item(0).key : null;
                  resolve2(result);
                }, function(t3, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function keys$1(callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve2, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t2) {
                tryExecuteSql(t2, dbInfo, "SELECT key FROM " + dbInfo.storeName, [], function(t3, results) {
                  var keys2 = [];
                  for (var i2 = 0; i2 < results.rows.length; i2++) {
                    keys2.push(results.rows.item(i2).key);
                  }
                  resolve2(keys2);
                }, function(t3, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function getAllStoreNames(db) {
          return new Promise$1(function(resolve2, reject) {
            db.transaction(function(t2) {
              t2.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function(t3, results) {
                var storeNames = [];
                for (var i2 = 0; i2 < results.rows.length; i2++) {
                  storeNames.push(results.rows.item(i2).name);
                }
                resolve2({
                  db,
                  storeNames
                });
              }, function(t3, error) {
                reject(error);
              });
            }, function(sqlError) {
              reject(sqlError);
            });
          });
        }
        function dropInstance$1(options, callback) {
          callback = getCallback.apply(this, arguments);
          var currentConfig = this.config();
          options = typeof options !== "function" && options || {};
          if (!options.name) {
            options.name = options.name || currentConfig.name;
            options.storeName = options.storeName || currentConfig.storeName;
          }
          var self2 = this;
          var promise;
          if (!options.name) {
            promise = Promise$1.reject("Invalid arguments");
          } else {
            promise = new Promise$1(function(resolve2) {
              var db;
              if (options.name === currentConfig.name) {
                db = self2._dbInfo.db;
              } else {
                db = openDatabase(options.name, "", "", 0);
              }
              if (!options.storeName) {
                resolve2(getAllStoreNames(db));
              } else {
                resolve2({
                  db,
                  storeNames: [options.storeName]
                });
              }
            }).then(function(operationInfo) {
              return new Promise$1(function(resolve2, reject) {
                operationInfo.db.transaction(function(t2) {
                  function dropTable(storeName) {
                    return new Promise$1(function(resolve3, reject2) {
                      t2.executeSql("DROP TABLE IF EXISTS " + storeName, [], function() {
                        resolve3();
                      }, function(t3, error) {
                        reject2(error);
                      });
                    });
                  }
                  var operations = [];
                  for (var i2 = 0, len = operationInfo.storeNames.length; i2 < len; i2++) {
                    operations.push(dropTable(operationInfo.storeNames[i2]));
                  }
                  Promise$1.all(operations).then(function() {
                    resolve2();
                  })["catch"](function(e2) {
                    reject(e2);
                  });
                }, function(sqlError) {
                  reject(sqlError);
                });
              });
            });
          }
          executeCallback(promise, callback);
          return promise;
        }
        var webSQLStorage = {
          _driver: "webSQLStorage",
          _initStorage: _initStorage$1,
          _support: isWebSQLValid(),
          iterate: iterate$1,
          getItem: getItem$1,
          setItem: setItem$1,
          removeItem: removeItem$1,
          clear: clear$1,
          length: length$1,
          key: key$1,
          keys: keys$1,
          dropInstance: dropInstance$1
        };
        function isLocalStorageValid() {
          try {
            return typeof localStorage !== "undefined" && "setItem" in localStorage && // in IE8 typeof localStorage.setItem === 'object'
            !!localStorage.setItem;
          } catch (e2) {
            return false;
          }
        }
        function _getKeyPrefix(options, defaultConfig) {
          var keyPrefix = options.name + "/";
          if (options.storeName !== defaultConfig.storeName) {
            keyPrefix += options.storeName + "/";
          }
          return keyPrefix;
        }
        function checkIfLocalStorageThrows() {
          var localStorageTestKey = "_localforage_support_test";
          try {
            localStorage.setItem(localStorageTestKey, true);
            localStorage.removeItem(localStorageTestKey);
            return false;
          } catch (e2) {
            return true;
          }
        }
        function _isLocalStorageUsable() {
          return !checkIfLocalStorageThrows() || localStorage.length > 0;
        }
        function _initStorage$2(options) {
          var self2 = this;
          var dbInfo = {};
          if (options) {
            for (var i2 in options) {
              dbInfo[i2] = options[i2];
            }
          }
          dbInfo.keyPrefix = _getKeyPrefix(options, self2._defaultConfig);
          if (!_isLocalStorageUsable()) {
            return Promise$1.reject();
          }
          self2._dbInfo = dbInfo;
          dbInfo.serializer = localforageSerializer;
          return Promise$1.resolve();
        }
        function clear$2(callback) {
          var self2 = this;
          var promise = self2.ready().then(function() {
            var keyPrefix = self2._dbInfo.keyPrefix;
            for (var i2 = localStorage.length - 1; i2 >= 0; i2--) {
              var key2 = localStorage.key(i2);
              if (key2.indexOf(keyPrefix) === 0) {
                localStorage.removeItem(key2);
              }
            }
          });
          executeCallback(promise, callback);
          return promise;
        }
        function getItem$2(key2, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = self2.ready().then(function() {
            var dbInfo = self2._dbInfo;
            var result = localStorage.getItem(dbInfo.keyPrefix + key2);
            if (result) {
              result = dbInfo.serializer.deserialize(result);
            }
            return result;
          });
          executeCallback(promise, callback);
          return promise;
        }
        function iterate$2(iterator, callback) {
          var self2 = this;
          var promise = self2.ready().then(function() {
            var dbInfo = self2._dbInfo;
            var keyPrefix = dbInfo.keyPrefix;
            var keyPrefixLength = keyPrefix.length;
            var length2 = localStorage.length;
            var iterationNumber = 1;
            for (var i2 = 0; i2 < length2; i2++) {
              var key2 = localStorage.key(i2);
              if (key2.indexOf(keyPrefix) !== 0) {
                continue;
              }
              var value = localStorage.getItem(key2);
              if (value) {
                value = dbInfo.serializer.deserialize(value);
              }
              value = iterator(value, key2.substring(keyPrefixLength), iterationNumber++);
              if (value !== void 0) {
                return value;
              }
            }
          });
          executeCallback(promise, callback);
          return promise;
        }
        function key$2(n2, callback) {
          var self2 = this;
          var promise = self2.ready().then(function() {
            var dbInfo = self2._dbInfo;
            var result;
            try {
              result = localStorage.key(n2);
            } catch (error) {
              result = null;
            }
            if (result) {
              result = result.substring(dbInfo.keyPrefix.length);
            }
            return result;
          });
          executeCallback(promise, callback);
          return promise;
        }
        function keys$2(callback) {
          var self2 = this;
          var promise = self2.ready().then(function() {
            var dbInfo = self2._dbInfo;
            var length2 = localStorage.length;
            var keys2 = [];
            for (var i2 = 0; i2 < length2; i2++) {
              var itemKey = localStorage.key(i2);
              if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
                keys2.push(itemKey.substring(dbInfo.keyPrefix.length));
              }
            }
            return keys2;
          });
          executeCallback(promise, callback);
          return promise;
        }
        function length$2(callback) {
          var self2 = this;
          var promise = self2.keys().then(function(keys2) {
            return keys2.length;
          });
          executeCallback(promise, callback);
          return promise;
        }
        function removeItem$2(key2, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = self2.ready().then(function() {
            var dbInfo = self2._dbInfo;
            localStorage.removeItem(dbInfo.keyPrefix + key2);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function setItem$2(key2, value, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = self2.ready().then(function() {
            if (value === void 0) {
              value = null;
            }
            var originalValue = value;
            return new Promise$1(function(resolve2, reject) {
              var dbInfo = self2._dbInfo;
              dbInfo.serializer.serialize(value, function(value2, error) {
                if (error) {
                  reject(error);
                } else {
                  try {
                    localStorage.setItem(dbInfo.keyPrefix + key2, value2);
                    resolve2(originalValue);
                  } catch (e2) {
                    if (e2.name === "QuotaExceededError" || e2.name === "NS_ERROR_DOM_QUOTA_REACHED") {
                      reject(e2);
                    }
                    reject(e2);
                  }
                }
              });
            });
          });
          executeCallback(promise, callback);
          return promise;
        }
        function dropInstance$2(options, callback) {
          callback = getCallback.apply(this, arguments);
          options = typeof options !== "function" && options || {};
          if (!options.name) {
            var currentConfig = this.config();
            options.name = options.name || currentConfig.name;
            options.storeName = options.storeName || currentConfig.storeName;
          }
          var self2 = this;
          var promise;
          if (!options.name) {
            promise = Promise$1.reject("Invalid arguments");
          } else {
            promise = new Promise$1(function(resolve2) {
              if (!options.storeName) {
                resolve2(options.name + "/");
              } else {
                resolve2(_getKeyPrefix(options, self2._defaultConfig));
              }
            }).then(function(keyPrefix) {
              for (var i2 = localStorage.length - 1; i2 >= 0; i2--) {
                var key2 = localStorage.key(i2);
                if (key2.indexOf(keyPrefix) === 0) {
                  localStorage.removeItem(key2);
                }
              }
            });
          }
          executeCallback(promise, callback);
          return promise;
        }
        var localStorageWrapper = {
          _driver: "localStorageWrapper",
          _initStorage: _initStorage$2,
          _support: isLocalStorageValid(),
          iterate: iterate$2,
          getItem: getItem$2,
          setItem: setItem$2,
          removeItem: removeItem$2,
          clear: clear$2,
          length: length$2,
          key: key$2,
          keys: keys$2,
          dropInstance: dropInstance$2
        };
        var sameValue = function sameValue2(x2, y3) {
          return x2 === y3 || typeof x2 === "number" && typeof y3 === "number" && isNaN(x2) && isNaN(y3);
        };
        var includes = function includes2(array, searchElement) {
          var len = array.length;
          var i2 = 0;
          while (i2 < len) {
            if (sameValue(array[i2], searchElement)) {
              return true;
            }
            i2++;
          }
          return false;
        };
        var isArray = Array.isArray || function(arg) {
          return Object.prototype.toString.call(arg) === "[object Array]";
        };
        var DefinedDrivers = {};
        var DriverSupport = {};
        var DefaultDrivers = {
          INDEXEDDB: asyncStorage,
          WEBSQL: webSQLStorage,
          LOCALSTORAGE: localStorageWrapper
        };
        var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];
        var OptionalDriverMethods = ["dropInstance"];
        var LibraryMethods = ["clear", "getItem", "iterate", "key", "keys", "length", "removeItem", "setItem"].concat(OptionalDriverMethods);
        var DefaultConfig = {
          description: "",
          driver: DefaultDriverOrder.slice(),
          name: "localforage",
          // Default DB size is _JUST UNDER_ 5MB, as it's the highest size
          // we can use without a prompt.
          size: 4980736,
          storeName: "keyvaluepairs",
          version: 1
        };
        function callWhenReady(localForageInstance, libraryMethod) {
          localForageInstance[libraryMethod] = function() {
            var _args = arguments;
            return localForageInstance.ready().then(function() {
              return localForageInstance[libraryMethod].apply(localForageInstance, _args);
            });
          };
        }
        function extend() {
          for (var i2 = 1; i2 < arguments.length; i2++) {
            var arg = arguments[i2];
            if (arg) {
              for (var _key in arg) {
                if (arg.hasOwnProperty(_key)) {
                  if (isArray(arg[_key])) {
                    arguments[0][_key] = arg[_key].slice();
                  } else {
                    arguments[0][_key] = arg[_key];
                  }
                }
              }
            }
          }
          return arguments[0];
        }
        var LocalForage = function() {
          function LocalForage2(options) {
            _classCallCheck(this, LocalForage2);
            for (var driverTypeKey in DefaultDrivers) {
              if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {
                var driver = DefaultDrivers[driverTypeKey];
                var driverName = driver._driver;
                this[driverTypeKey] = driverName;
                if (!DefinedDrivers[driverName]) {
                  this.defineDriver(driver);
                }
              }
            }
            this._defaultConfig = extend({}, DefaultConfig);
            this._config = extend({}, this._defaultConfig, options);
            this._driverSet = null;
            this._initDriver = null;
            this._ready = false;
            this._dbInfo = null;
            this._wrapLibraryMethodsWithReady();
            this.setDriver(this._config.driver)["catch"](function() {
            });
          }
          LocalForage2.prototype.config = function config(options) {
            if ((typeof options === "undefined" ? "undefined" : _typeof(options)) === "object") {
              if (this._ready) {
                return new Error("Can't call config() after localforage has been used.");
              }
              for (var i2 in options) {
                if (i2 === "storeName") {
                  options[i2] = options[i2].replace(/\W/g, "_");
                }
                if (i2 === "version" && typeof options[i2] !== "number") {
                  return new Error("Database version must be a number.");
                }
                this._config[i2] = options[i2];
              }
              if ("driver" in options && options.driver) {
                return this.setDriver(this._config.driver);
              }
              return true;
            } else if (typeof options === "string") {
              return this._config[options];
            } else {
              return this._config;
            }
          };
          LocalForage2.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
            var promise = new Promise$1(function(resolve2, reject) {
              try {
                var driverName = driverObject._driver;
                var complianceError = new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");
                if (!driverObject._driver) {
                  reject(complianceError);
                  return;
                }
                var driverMethods = LibraryMethods.concat("_initStorage");
                for (var i2 = 0, len = driverMethods.length; i2 < len; i2++) {
                  var driverMethodName = driverMethods[i2];
                  var isRequired = !includes(OptionalDriverMethods, driverMethodName);
                  if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== "function") {
                    reject(complianceError);
                    return;
                  }
                }
                var configureMissingMethods = function configureMissingMethods2() {
                  var methodNotImplementedFactory = function methodNotImplementedFactory2(methodName) {
                    return function() {
                      var error = new Error("Method " + methodName + " is not implemented by the current driver");
                      var promise2 = Promise$1.reject(error);
                      executeCallback(promise2, arguments[arguments.length - 1]);
                      return promise2;
                    };
                  };
                  for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {
                    var optionalDriverMethod = OptionalDriverMethods[_i];
                    if (!driverObject[optionalDriverMethod]) {
                      driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);
                    }
                  }
                };
                configureMissingMethods();
                var setDriverSupport = function setDriverSupport2(support) {
                  if (DefinedDrivers[driverName]) {
                    console.info("Redefining LocalForage driver: " + driverName);
                  }
                  DefinedDrivers[driverName] = driverObject;
                  DriverSupport[driverName] = support;
                  resolve2();
                };
                if ("_support" in driverObject) {
                  if (driverObject._support && typeof driverObject._support === "function") {
                    driverObject._support().then(setDriverSupport, reject);
                  } else {
                    setDriverSupport(!!driverObject._support);
                  }
                } else {
                  setDriverSupport(true);
                }
              } catch (e2) {
                reject(e2);
              }
            });
            executeTwoCallbacks(promise, callback, errorCallback);
            return promise;
          };
          LocalForage2.prototype.driver = function driver() {
            return this._driver || null;
          };
          LocalForage2.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
            var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error("Driver not found."));
            executeTwoCallbacks(getDriverPromise, callback, errorCallback);
            return getDriverPromise;
          };
          LocalForage2.prototype.getSerializer = function getSerializer(callback) {
            var serializerPromise = Promise$1.resolve(localforageSerializer);
            executeTwoCallbacks(serializerPromise, callback);
            return serializerPromise;
          };
          LocalForage2.prototype.ready = function ready(callback) {
            var self2 = this;
            var promise = self2._driverSet.then(function() {
              if (self2._ready === null) {
                self2._ready = self2._initDriver();
              }
              return self2._ready;
            });
            executeTwoCallbacks(promise, callback, callback);
            return promise;
          };
          LocalForage2.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
            var self2 = this;
            if (!isArray(drivers)) {
              drivers = [drivers];
            }
            var supportedDrivers = this._getSupportedDrivers(drivers);
            function setDriverToConfig() {
              self2._config.driver = self2.driver();
            }
            function extendSelfWithDriver(driver) {
              self2._extend(driver);
              setDriverToConfig();
              self2._ready = self2._initStorage(self2._config);
              return self2._ready;
            }
            function initDriver(supportedDrivers2) {
              return function() {
                var currentDriverIndex = 0;
                function driverPromiseLoop() {
                  while (currentDriverIndex < supportedDrivers2.length) {
                    var driverName = supportedDrivers2[currentDriverIndex];
                    currentDriverIndex++;
                    self2._dbInfo = null;
                    self2._ready = null;
                    return self2.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop);
                  }
                  setDriverToConfig();
                  var error = new Error("No available storage method found.");
                  self2._driverSet = Promise$1.reject(error);
                  return self2._driverSet;
                }
                return driverPromiseLoop();
              };
            }
            var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function() {
              return Promise$1.resolve();
            }) : Promise$1.resolve();
            this._driverSet = oldDriverSetDone.then(function() {
              var driverName = supportedDrivers[0];
              self2._dbInfo = null;
              self2._ready = null;
              return self2.getDriver(driverName).then(function(driver) {
                self2._driver = driver._driver;
                setDriverToConfig();
                self2._wrapLibraryMethodsWithReady();
                self2._initDriver = initDriver(supportedDrivers);
              });
            })["catch"](function() {
              setDriverToConfig();
              var error = new Error("No available storage method found.");
              self2._driverSet = Promise$1.reject(error);
              return self2._driverSet;
            });
            executeTwoCallbacks(this._driverSet, callback, errorCallback);
            return this._driverSet;
          };
          LocalForage2.prototype.supports = function supports(driverName) {
            return !!DriverSupport[driverName];
          };
          LocalForage2.prototype._extend = function _extend(libraryMethodsAndProperties) {
            extend(this, libraryMethodsAndProperties);
          };
          LocalForage2.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
            var supportedDrivers = [];
            for (var i2 = 0, len = drivers.length; i2 < len; i2++) {
              var driverName = drivers[i2];
              if (this.supports(driverName)) {
                supportedDrivers.push(driverName);
              }
            }
            return supportedDrivers;
          };
          LocalForage2.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
            for (var i2 = 0, len = LibraryMethods.length; i2 < len; i2++) {
              callWhenReady(this, LibraryMethods[i2]);
            }
          };
          LocalForage2.prototype.createInstance = function createInstance(options) {
            return new LocalForage2(options);
          };
          return LocalForage2;
        }();
        var localforage_js = new LocalForage();
        module3.exports = localforage_js;
      }, { "3": 3 }] }, {}, [4])(4);
    });
  }
});

// ../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/offline.js
var require_offline2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/offline.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var utils = require_cjs();
    var localForage = require_localforage();
    var debugBuild = require_debug_build5();
    var WINDOW = utils.GLOBAL_OBJ;
    var Offline = class _Offline {
      /**
       * @inheritDoc
       */
      static __initStatic() {
        this.id = "Offline";
      }
      /**
       * @inheritDoc
       */
      /**
       * the current hub instance
       */
      /**
       * maximum number of events to store while offline
       */
      /**
       * event cache
       */
      /**
       * @inheritDoc
       */
      constructor(options = {}) {
        this.name = _Offline.id;
        this.maxStoredEvents = options.maxStoredEvents || 30;
        this.offlineEventStore = localForage.createInstance({
          name: "sentry/offlineEventStore"
        });
      }
      /**
       * @inheritDoc
       */
      setupOnce(addGlobalEventProcessor, getCurrentHub) {
        this.hub = getCurrentHub();
        if ("addEventListener" in WINDOW) {
          WINDOW.addEventListener("online", () => {
            void this._sendEvents().catch(() => {
              debugBuild.DEBUG_BUILD && utils.logger.warn("could not send cached events");
            });
          });
        }
        const eventProcessor = (event) => {
          if (this.hub && this.hub.getIntegration(_Offline)) {
            if ("navigator" in WINDOW && "onLine" in WINDOW.navigator && !WINDOW.navigator.onLine) {
              debugBuild.DEBUG_BUILD && utils.logger.log("Event dropped due to being a offline - caching instead");
              void this._cacheEvent(event).then((_event) => this._enforceMaxEvents()).catch((_error) => {
                debugBuild.DEBUG_BUILD && utils.logger.warn("could not cache event while offline");
              });
              return null;
            }
          }
          return event;
        };
        eventProcessor.id = this.name;
        addGlobalEventProcessor(eventProcessor);
        if ("navigator" in WINDOW && "onLine" in WINDOW.navigator && WINDOW.navigator.onLine) {
          void this._sendEvents().catch(() => {
            debugBuild.DEBUG_BUILD && utils.logger.warn("could not send cached events");
          });
        }
      }
      /**
       * cache an event to send later
       * @param event an event
       */
      async _cacheEvent(event) {
        return this.offlineEventStore.setItem(utils.uuid4(), utils.normalize(event));
      }
      /**
       * purge excess events if necessary
       */
      async _enforceMaxEvents() {
        const events = [];
        return this.offlineEventStore.iterate((event, cacheKey, _index) => {
          events.push({ cacheKey, event });
        }).then(
          () => (
            // this promise resolves when the iteration is finished
            this._purgeEvents(
              // purge all events past maxStoredEvents in reverse chronological order
              events.sort((a3, b) => (b.event.timestamp || 0) - (a3.event.timestamp || 0)).slice(this.maxStoredEvents < events.length ? this.maxStoredEvents : events.length).map((event) => event.cacheKey)
            )
          )
        ).catch((_error) => {
          debugBuild.DEBUG_BUILD && utils.logger.warn("could not enforce max events");
        });
      }
      /**
       * purge event from cache
       */
      async _purgeEvent(cacheKey) {
        return this.offlineEventStore.removeItem(cacheKey);
      }
      /**
       * purge events from cache
       */
      async _purgeEvents(cacheKeys) {
        return Promise.all(cacheKeys.map((cacheKey) => this._purgeEvent(cacheKey))).then();
      }
      /**
       * send all events
       */
      async _sendEvents() {
        return this.offlineEventStore.iterate((event, cacheKey, _index) => {
          if (this.hub) {
            this.hub.captureEvent(event);
            void this._purgeEvent(cacheKey).catch((_error) => {
              debugBuild.DEBUG_BUILD && utils.logger.warn("could not purge event from cache");
            });
          } else {
            debugBuild.DEBUG_BUILD && utils.logger.warn("no hub found - could not send cached event");
          }
        });
      }
    };
    Offline.__initStatic();
    exports.Offline = Offline;
  }
});

// ../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/reportingobserver.js
var require_reportingobserver = __commonJS({
  "../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/reportingobserver.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var WINDOW = utils.GLOBAL_OBJ;
    var INTEGRATION_NAME = "ReportingObserver";
    var SETUP_CLIENTS = /* @__PURE__ */ new WeakMap();
    var _reportingObserverIntegration = (options = {}) => {
      const types = options.types || ["crash", "deprecation", "intervention"];
      function handler(reports) {
        if (!SETUP_CLIENTS.has(core.getClient())) {
          return;
        }
        for (const report of reports) {
          core.withScope((scope) => {
            scope.setExtra("url", report.url);
            const label = `ReportingObserver [${report.type}]`;
            let details = "No details available";
            if (report.body) {
              const plainBody = {};
              for (const prop in report.body) {
                plainBody[prop] = report.body[prop];
              }
              scope.setExtra("body", plainBody);
              if (report.type === "crash") {
                const body = report.body;
                details = [body.crashId || "", body.reason || ""].join(" ").trim() || details;
              } else {
                const body = report.body;
                details = body.message || details;
              }
            }
            core.captureMessage(`${label}: ${details}`);
          });
        }
      }
      return {
        name: INTEGRATION_NAME,
        setupOnce() {
          if (!utils.supportsReportingObserver()) {
            return;
          }
          const observer = new WINDOW.ReportingObserver(handler, {
            buffered: true,
            types
          });
          observer.observe();
        },
        setup(client) {
          SETUP_CLIENTS.set(client, true);
        }
      };
    };
    var reportingObserverIntegration = core.defineIntegration(_reportingObserverIntegration);
    var ReportingObserver = core.convertIntegrationFnToClass(
      INTEGRATION_NAME,
      reportingObserverIntegration
    );
    exports.ReportingObserver = ReportingObserver;
    exports.reportingObserverIntegration = reportingObserverIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/rewriteframes.js
var require_rewriteframes = __commonJS({
  "../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/rewriteframes.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var INTEGRATION_NAME = "RewriteFrames";
    var _rewriteFramesIntegration = (options = {}) => {
      const root = options.root;
      const prefix = options.prefix || "app:///";
      const iteratee = options.iteratee || ((frame) => {
        if (!frame.filename) {
          return frame;
        }
        const isWindowsFrame = /^[a-zA-Z]:\\/.test(frame.filename) || // or the presence of a backslash without a forward slash (which are not allowed on Windows)
        frame.filename.includes("\\") && !frame.filename.includes("/");
        const startsWithSlash = /^\//.test(frame.filename);
        if (isWindowsFrame || startsWithSlash) {
          const filename = isWindowsFrame ? frame.filename.replace(/^[a-zA-Z]:/, "").replace(/\\/g, "/") : frame.filename;
          const base = root ? utils.relative(root, filename) : utils.basename(filename);
          frame.filename = `${prefix}${base}`;
        }
        return frame;
      });
      function _processExceptionsEvent(event) {
        try {
          return {
            ...event,
            exception: {
              ...event.exception,
              // The check for this is performed inside `process` call itself, safe to skip here
              // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
              values: event.exception.values.map((value) => ({
                ...value,
                ...value.stacktrace && { stacktrace: _processStacktrace(value.stacktrace) }
              }))
            }
          };
        } catch (_oO) {
          return event;
        }
      }
      function _processStacktrace(stacktrace) {
        return {
          ...stacktrace,
          frames: stacktrace && stacktrace.frames && stacktrace.frames.map((f2) => iteratee(f2))
        };
      }
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        processEvent(originalEvent) {
          let processedEvent = originalEvent;
          if (originalEvent.exception && Array.isArray(originalEvent.exception.values)) {
            processedEvent = _processExceptionsEvent(processedEvent);
          }
          return processedEvent;
        }
      };
    };
    var rewriteFramesIntegration = core.defineIntegration(_rewriteFramesIntegration);
    var RewriteFrames = core.convertIntegrationFnToClass(
      INTEGRATION_NAME,
      rewriteFramesIntegration
    );
    exports.RewriteFrames = RewriteFrames;
    exports.rewriteFramesIntegration = rewriteFramesIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/sessiontiming.js
var require_sessiontiming = __commonJS({
  "../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/sessiontiming.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var INTEGRATION_NAME = "SessionTiming";
    var _sessionTimingIntegration = () => {
      const startTime = Date.now();
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        processEvent(event) {
          const now = Date.now();
          return {
            ...event,
            extra: {
              ...event.extra,
              ["session:start"]: startTime,
              ["session:duration"]: now - startTime,
              ["session:end"]: now
            }
          };
        }
      };
    };
    var sessionTimingIntegration = core.defineIntegration(_sessionTimingIntegration);
    var SessionTiming = core.convertIntegrationFnToClass(
      INTEGRATION_NAME,
      sessionTimingIntegration
    );
    exports.SessionTiming = SessionTiming;
    exports.sessionTimingIntegration = sessionTimingIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/transaction.js
var require_transaction2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/transaction.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var INTEGRATION_NAME = "Transaction";
    var transactionIntegration = () => {
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        processEvent(event) {
          const frames = _getFramesFromEvent(event);
          for (let i2 = frames.length - 1; i2 >= 0; i2--) {
            const frame = frames[i2];
            if (frame.in_app === true) {
              event.transaction = _getTransaction(frame);
              break;
            }
          }
          return event;
        }
      };
    };
    var Transaction2 = core.convertIntegrationFnToClass(INTEGRATION_NAME, transactionIntegration);
    function _getFramesFromEvent(event) {
      const exception = event.exception && event.exception.values && event.exception.values[0];
      return exception && exception.stacktrace && exception.stacktrace.frames || [];
    }
    function _getTransaction(frame) {
      return frame.module || frame.function ? `${frame.module || "?"}/${frame.function || "?"}` : "<unknown>";
    }
    exports.Transaction = Transaction2;
  }
});

// ../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/httpclient.js
var require_httpclient = __commonJS({
  "../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/httpclient.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var debugBuild = require_debug_build5();
    var INTEGRATION_NAME = "HttpClient";
    var _httpClientIntegration = (options = {}) => {
      const _options = {
        failedRequestStatusCodes: [[500, 599]],
        failedRequestTargets: [/.*/],
        ...options
      };
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        setup(client) {
          _wrapFetch(client, _options);
          _wrapXHR(client, _options);
        }
      };
    };
    var httpClientIntegration = core.defineIntegration(_httpClientIntegration);
    var HttpClient = core.convertIntegrationFnToClass(INTEGRATION_NAME, httpClientIntegration);
    function _fetchResponseHandler(options, requestInfo, response, requestInit) {
      if (_shouldCaptureResponse(options, response.status, response.url)) {
        const request = _getRequest(requestInfo, requestInit);
        let requestHeaders, responseHeaders, requestCookies, responseCookies;
        if (_shouldSendDefaultPii()) {
          [{ headers: requestHeaders, cookies: requestCookies }, { headers: responseHeaders, cookies: responseCookies }] = [
            { cookieHeader: "Cookie", obj: request },
            { cookieHeader: "Set-Cookie", obj: response }
          ].map(({ cookieHeader, obj }) => {
            const headers = _extractFetchHeaders(obj.headers);
            let cookies;
            try {
              const cookieString = headers[cookieHeader] || headers[cookieHeader.toLowerCase()] || void 0;
              if (cookieString) {
                cookies = _parseCookieString(cookieString);
              }
            } catch (e2) {
              debugBuild.DEBUG_BUILD && utils.logger.log(`Could not extract cookies from header ${cookieHeader}`);
            }
            return {
              headers,
              cookies
            };
          });
        }
        const event = _createEvent({
          url: request.url,
          method: request.method,
          status: response.status,
          requestHeaders,
          responseHeaders,
          requestCookies,
          responseCookies
        });
        core.captureEvent(event);
      }
    }
    function _xhrResponseHandler(options, xhr, method, headers) {
      if (_shouldCaptureResponse(options, xhr.status, xhr.responseURL)) {
        let requestHeaders, responseCookies, responseHeaders;
        if (_shouldSendDefaultPii()) {
          try {
            const cookieString = xhr.getResponseHeader("Set-Cookie") || xhr.getResponseHeader("set-cookie") || void 0;
            if (cookieString) {
              responseCookies = _parseCookieString(cookieString);
            }
          } catch (e2) {
            debugBuild.DEBUG_BUILD && utils.logger.log("Could not extract cookies from response headers");
          }
          try {
            responseHeaders = _getXHRResponseHeaders(xhr);
          } catch (e2) {
            debugBuild.DEBUG_BUILD && utils.logger.log("Could not extract headers from response");
          }
          requestHeaders = headers;
        }
        const event = _createEvent({
          url: xhr.responseURL,
          method,
          status: xhr.status,
          requestHeaders,
          // Can't access request cookies from XHR
          responseHeaders,
          responseCookies
        });
        core.captureEvent(event);
      }
    }
    function _getResponseSizeFromHeaders(headers) {
      if (headers) {
        const contentLength = headers["Content-Length"] || headers["content-length"];
        if (contentLength) {
          return parseInt(contentLength, 10);
        }
      }
      return void 0;
    }
    function _parseCookieString(cookieString) {
      return cookieString.split("; ").reduce((acc, cookie) => {
        const [key, value] = cookie.split("=");
        acc[key] = value;
        return acc;
      }, {});
    }
    function _extractFetchHeaders(headers) {
      const result = {};
      headers.forEach((value, key) => {
        result[key] = value;
      });
      return result;
    }
    function _getXHRResponseHeaders(xhr) {
      const headers = xhr.getAllResponseHeaders();
      if (!headers) {
        return {};
      }
      return headers.split("\r\n").reduce((acc, line) => {
        const [key, value] = line.split(": ");
        acc[key] = value;
        return acc;
      }, {});
    }
    function _isInGivenRequestTargets(failedRequestTargets, target) {
      return failedRequestTargets.some((givenRequestTarget) => {
        if (typeof givenRequestTarget === "string") {
          return target.includes(givenRequestTarget);
        }
        return givenRequestTarget.test(target);
      });
    }
    function _isInGivenStatusRanges(failedRequestStatusCodes, status) {
      return failedRequestStatusCodes.some((range) => {
        if (typeof range === "number") {
          return range === status;
        }
        return status >= range[0] && status <= range[1];
      });
    }
    function _wrapFetch(client, options) {
      if (!utils.supportsNativeFetch()) {
        return;
      }
      utils.addFetchInstrumentationHandler((handlerData) => {
        if (core.getClient() !== client) {
          return;
        }
        const { response, args } = handlerData;
        const [requestInfo, requestInit] = args;
        if (!response) {
          return;
        }
        _fetchResponseHandler(options, requestInfo, response, requestInit);
      });
    }
    function _wrapXHR(client, options) {
      if (!("XMLHttpRequest" in utils.GLOBAL_OBJ)) {
        return;
      }
      utils.addXhrInstrumentationHandler((handlerData) => {
        if (core.getClient() !== client) {
          return;
        }
        const xhr = handlerData.xhr;
        const sentryXhrData = xhr[utils.SENTRY_XHR_DATA_KEY];
        if (!sentryXhrData) {
          return;
        }
        const { method, request_headers: headers } = sentryXhrData;
        try {
          _xhrResponseHandler(options, xhr, method, headers);
        } catch (e2) {
          debugBuild.DEBUG_BUILD && utils.logger.warn("Error while extracting response event form XHR response", e2);
        }
      });
    }
    function _shouldCaptureResponse(options, status, url) {
      return _isInGivenStatusRanges(options.failedRequestStatusCodes, status) && _isInGivenRequestTargets(options.failedRequestTargets, url) && !core.isSentryRequestUrl(url, core.getClient());
    }
    function _createEvent(data) {
      const message = `HTTP Client Error with status code: ${data.status}`;
      const event = {
        message,
        exception: {
          values: [
            {
              type: "Error",
              value: message
            }
          ]
        },
        request: {
          url: data.url,
          method: data.method,
          headers: data.requestHeaders,
          cookies: data.requestCookies
        },
        contexts: {
          response: {
            status_code: data.status,
            headers: data.responseHeaders,
            cookies: data.responseCookies,
            body_size: _getResponseSizeFromHeaders(data.responseHeaders)
          }
        }
      };
      utils.addExceptionMechanism(event, {
        type: "http.client",
        handled: false
      });
      return event;
    }
    function _getRequest(requestInfo, requestInit) {
      if (!requestInit && requestInfo instanceof Request) {
        return requestInfo;
      }
      if (requestInfo instanceof Request && requestInfo.bodyUsed) {
        return requestInfo;
      }
      return new Request(requestInfo, requestInit);
    }
    function _shouldSendDefaultPii() {
      const client = core.getClient();
      return client ? Boolean(client.getOptions().sendDefaultPii) : false;
    }
    exports.HttpClient = HttpClient;
    exports.httpClientIntegration = httpClientIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/contextlines.js
var require_contextlines2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/contextlines.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var utils = require_cjs();
    var WINDOW = utils.GLOBAL_OBJ;
    var DEFAULT_LINES_OF_CONTEXT = 7;
    var INTEGRATION_NAME = "ContextLines";
    var _contextLinesIntegration = (options = {}) => {
      const contextLines = options.frameContextLines != null ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT;
      return {
        name: INTEGRATION_NAME,
        // TODO v8: Remove this
        setupOnce() {
        },
        // eslint-disable-line @typescript-eslint/no-empty-function
        processEvent(event) {
          return addSourceContext(event, contextLines);
        }
      };
    };
    var contextLinesIntegration = core.defineIntegration(_contextLinesIntegration);
    var ContextLines = core.convertIntegrationFnToClass(INTEGRATION_NAME, contextLinesIntegration);
    function addSourceContext(event, contextLines) {
      const doc = WINDOW.document;
      const htmlFilename = WINDOW.location && utils.stripUrlQueryAndFragment(WINDOW.location.href);
      if (!doc || !htmlFilename) {
        return event;
      }
      const exceptions = event.exception && event.exception.values;
      if (!exceptions || !exceptions.length) {
        return event;
      }
      const html = doc.documentElement.innerHTML;
      if (!html) {
        return event;
      }
      const htmlLines = ["<!DOCTYPE html>", "<html>", ...html.split("\n"), "</html>"];
      exceptions.forEach((exception) => {
        const stacktrace = exception.stacktrace;
        if (stacktrace && stacktrace.frames) {
          stacktrace.frames = stacktrace.frames.map(
            (frame) => applySourceContextToFrame(frame, htmlLines, htmlFilename, contextLines)
          );
        }
      });
      return event;
    }
    function applySourceContextToFrame(frame, htmlLines, htmlFilename, linesOfContext) {
      if (frame.filename !== htmlFilename || !frame.lineno || !htmlLines.length) {
        return frame;
      }
      utils.addContextToFrame(htmlLines, frame, linesOfContext);
      return frame;
    }
    exports.ContextLines = ContextLines;
    exports.applySourceContextToFrame = applySourceContextToFrame;
    exports.contextLinesIntegration = contextLinesIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/index.js
var require_cjs4 = __commonJS({
  "../../node_modules/.pnpm/@sentry+integrations@7.120.3/node_modules/@sentry/integrations/cjs/index.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var captureconsole = require_captureconsole();
    var debug = require_debug();
    var dedupe = require_dedupe();
    var extraerrordata = require_extraerrordata();
    var offline = require_offline2();
    var reportingobserver = require_reportingobserver();
    var rewriteframes = require_rewriteframes();
    var sessiontiming = require_sessiontiming();
    var transaction = require_transaction2();
    var httpclient = require_httpclient();
    var contextlines = require_contextlines2();
    exports.CaptureConsole = captureconsole.CaptureConsole;
    exports.captureConsoleIntegration = captureconsole.captureConsoleIntegration;
    exports.Debug = debug.Debug;
    exports.debugIntegration = debug.debugIntegration;
    exports.Dedupe = dedupe.Dedupe;
    exports.dedupeIntegration = dedupe.dedupeIntegration;
    exports.ExtraErrorData = extraerrordata.ExtraErrorData;
    exports.extraErrorDataIntegration = extraerrordata.extraErrorDataIntegration;
    exports.Offline = offline.Offline;
    exports.ReportingObserver = reportingobserver.ReportingObserver;
    exports.reportingObserverIntegration = reportingobserver.reportingObserverIntegration;
    exports.RewriteFrames = rewriteframes.RewriteFrames;
    exports.rewriteFramesIntegration = rewriteframes.rewriteFramesIntegration;
    exports.SessionTiming = sessiontiming.SessionTiming;
    exports.sessionTimingIntegration = sessiontiming.sessionTimingIntegration;
    exports.Transaction = transaction.Transaction;
    exports.HttpClient = httpclient.HttpClient;
    exports.httpClientIntegration = httpclient.httpClientIntegration;
    exports.ContextLines = contextlines.ContextLines;
    exports.contextLinesIntegration = contextlines.contextLinesIntegration;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/cron/common.js
var require_common2 = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/cron/common.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var replacements = [
      ["january", "1"],
      ["february", "2"],
      ["march", "3"],
      ["april", "4"],
      ["may", "5"],
      ["june", "6"],
      ["july", "7"],
      ["august", "8"],
      ["september", "9"],
      ["october", "10"],
      ["november", "11"],
      ["december", "12"],
      ["jan", "1"],
      ["feb", "2"],
      ["mar", "3"],
      ["apr", "4"],
      ["may", "5"],
      ["jun", "6"],
      ["jul", "7"],
      ["aug", "8"],
      ["sep", "9"],
      ["oct", "10"],
      ["nov", "11"],
      ["dec", "12"],
      ["sunday", "0"],
      ["monday", "1"],
      ["tuesday", "2"],
      ["wednesday", "3"],
      ["thursday", "4"],
      ["friday", "5"],
      ["saturday", "6"],
      ["sun", "0"],
      ["mon", "1"],
      ["tue", "2"],
      ["wed", "3"],
      ["thu", "4"],
      ["fri", "5"],
      ["sat", "6"]
    ];
    function replaceCronNames(cronExpression) {
      return replacements.reduce(
        // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor
        (acc, [name, replacement]) => acc.replace(new RegExp(name, "gi"), replacement),
        cronExpression
      );
    }
    exports.replaceCronNames = replaceCronNames;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/cron/cron.js
var require_cron = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/cron/cron.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var common = require_common2();
    var ERROR_TEXT = "Automatic instrumentation of CronJob only supports crontab string";
    function instrumentCron(lib, monitorSlug) {
      let jobScheduled = false;
      return new Proxy(lib, {
        construct(target, args) {
          const [cronTime, onTick, onComplete, start, timeZone, ...rest] = args;
          if (typeof cronTime !== "string") {
            throw new Error(ERROR_TEXT);
          }
          if (jobScheduled) {
            throw new Error(`A job named '${monitorSlug}' has already been scheduled`);
          }
          jobScheduled = true;
          const cronString = common.replaceCronNames(cronTime);
          function monitoredTick(context2, onComplete2) {
            return core.withMonitor(
              monitorSlug,
              () => {
                return onTick(context2, onComplete2);
              },
              {
                schedule: { type: "crontab", value: cronString },
                timezone: timeZone || void 0
              }
            );
          }
          return new target(cronTime, monitoredTick, onComplete, start, timeZone, ...rest);
        },
        get(target, prop) {
          if (prop === "from") {
            return (param) => {
              const { cronTime, onTick, timeZone } = param;
              if (typeof cronTime !== "string") {
                throw new Error(ERROR_TEXT);
              }
              if (jobScheduled) {
                throw new Error(`A job named '${monitorSlug}' has already been scheduled`);
              }
              jobScheduled = true;
              const cronString = common.replaceCronNames(cronTime);
              param.onTick = (context2, onComplete) => {
                return core.withMonitor(
                  monitorSlug,
                  () => {
                    return onTick(context2, onComplete);
                  },
                  {
                    schedule: { type: "crontab", value: cronString },
                    timezone: timeZone || void 0
                  }
                );
              };
              return target.from(param);
            };
          } else {
            return target[prop];
          }
        }
      });
    }
    exports.instrumentCron = instrumentCron;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/cron/node-cron.js
var require_node_cron = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/cron/node-cron.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    var {
      _optionalChain
    } = require_cjs();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var common = require_common2();
    function instrumentNodeCron(lib) {
      return new Proxy(lib, {
        get(target, prop) {
          if (prop === "schedule" && target.schedule) {
            return new Proxy(target.schedule, {
              apply(target2, thisArg, argArray) {
                const [expression, , options] = argArray;
                if (!_optionalChain([options, "optionalAccess", (_3) => _3.name])) {
                  throw new Error('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.');
                }
                return core.withMonitor(
                  options.name,
                  () => {
                    return target2.apply(thisArg, argArray);
                  },
                  {
                    schedule: { type: "crontab", value: common.replaceCronNames(expression) },
                    timezone: _optionalChain([options, "optionalAccess", (_22) => _22.timezone])
                  }
                );
              }
            });
          } else {
            return target[prop];
          }
        }
      });
    }
    exports.instrumentNodeCron = instrumentNodeCron;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/cron/node-schedule.js
var require_node_schedule = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/cron/node-schedule.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var common = require_common2();
    function instrumentNodeSchedule(lib) {
      return new Proxy(lib, {
        get(target, prop) {
          if (prop === "scheduleJob") {
            return new Proxy(target.scheduleJob, {
              apply(target2, thisArg, argArray) {
                const [nameOrExpression, expressionOrCallback] = argArray;
                if (typeof nameOrExpression !== "string" || typeof expressionOrCallback !== "string") {
                  throw new Error(
                    "Automatic instrumentation of 'node-schedule' requires the first parameter of 'scheduleJob' to be a job name string and the second parameter to be a crontab string"
                  );
                }
                const monitorSlug = nameOrExpression;
                const expression = expressionOrCallback;
                return core.withMonitor(
                  monitorSlug,
                  () => {
                    return target2.apply(thisArg, argArray);
                  },
                  {
                    schedule: { type: "crontab", value: common.replaceCronNames(expression) }
                  }
                );
              }
            });
          }
          return target[prop];
        }
      });
    }
    exports.instrumentNodeSchedule = instrumentNodeSchedule;
  }
});

// ../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/index.js
var require_cjs5 = __commonJS({
  "../../node_modules/.pnpm/@sentry+node@7.120.3/node_modules/@sentry/node/cjs/index.js"(exports) {
    init_define_ENV_DEFINED_IN_BUILD_STEP();
    Object.defineProperty(exports, "__esModule", { value: true });
    var core = require_cjs2();
    var index = require_tracing2();
    var client = require_client();
    var http = require_http();
    var sdk = require_sdk2();
    var utils = require_cjs();
    var utils$1 = require_utils4();
    var module$1 = require_module();
    var legacy = require_legacy2();
    var handlers = require_handlers2();
    var index$5 = require_integrations2();
    var integrations$1 = require_integrations3();
    var integrations = require_cjs4();
    var console2 = require_console2();
    var onuncaughtexception = require_onuncaughtexception();
    var onunhandledrejection = require_onunhandledrejection();
    var modules = require_modules();
    var contextlines = require_contextlines();
    var context2 = require_context();
    var index$1 = require_local_variables();
    var spotlight = require_spotlight();
    var index$2 = require_anr2();
    var index$3 = require_hapi();
    var index$4 = require_undici();
    var http$1 = require_http3();
    var trpc = require_trpc();
    var cron$1 = require_cron();
    var nodeCron = require_node_cron();
    var nodeSchedule = require_node_schedule();
    var getModuleFromFilename = module$1.createGetModuleFromFilename();
    var Integrations = {
      // eslint-disable-next-line deprecation/deprecation
      ...core.Integrations,
      ...index$5,
      ...integrations$1
    };
    var cron = {
      instrumentCron: cron$1.instrumentCron,
      instrumentNodeCron: nodeCron.instrumentNodeCron,
      instrumentNodeSchedule: nodeSchedule.instrumentNodeSchedule
    };
    exports.Hub = core.Hub;
    exports.SDK_VERSION = core.SDK_VERSION;
    exports.SEMANTIC_ATTRIBUTE_SENTRY_OP = core.SEMANTIC_ATTRIBUTE_SENTRY_OP;
    exports.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN;
    exports.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = core.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE;
    exports.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE;
    exports.Scope = core.Scope;
    exports.addBreadcrumb = core.addBreadcrumb;
    exports.addEventProcessor = core.addEventProcessor;
    exports.addGlobalEventProcessor = core.addGlobalEventProcessor;
    exports.addIntegration = core.addIntegration;
    exports.captureCheckIn = core.captureCheckIn;
    exports.captureEvent = core.captureEvent;
    exports.captureException = core.captureException;
    exports.captureMessage = core.captureMessage;
    exports.captureSession = core.captureSession;
    exports.close = core.close;
    exports.configureScope = core.configureScope;
    exports.continueTrace = core.continueTrace;
    exports.createTransport = core.createTransport;
    exports.endSession = core.endSession;
    exports.extractTraceparentData = core.extractTraceparentData;
    exports.flush = core.flush;
    exports.functionToStringIntegration = core.functionToStringIntegration;
    exports.getActiveSpan = core.getActiveSpan;
    exports.getActiveTransaction = core.getActiveTransaction;
    exports.getClient = core.getClient;
    exports.getCurrentHub = core.getCurrentHub;
    exports.getCurrentScope = core.getCurrentScope;
    exports.getGlobalScope = core.getGlobalScope;
    exports.getHubFromCarrier = core.getHubFromCarrier;
    exports.getIsolationScope = core.getIsolationScope;
    exports.getSpanStatusFromHttpCode = core.getSpanStatusFromHttpCode;
    exports.inboundFiltersIntegration = core.inboundFiltersIntegration;
    exports.isInitialized = core.isInitialized;
    exports.lastEventId = core.lastEventId;
    exports.linkedErrorsIntegration = core.linkedErrorsIntegration;
    exports.makeMain = core.makeMain;
    exports.metrics = core.metrics;
    exports.parameterize = core.parameterize;
    exports.requestDataIntegration = core.requestDataIntegration;
    exports.runWithAsyncContext = core.runWithAsyncContext;
    exports.setContext = core.setContext;
    exports.setCurrentClient = core.setCurrentClient;
    exports.setExtra = core.setExtra;
    exports.setExtras = core.setExtras;
    exports.setHttpStatus = core.setHttpStatus;
    exports.setMeasurement = core.setMeasurement;
    exports.setTag = core.setTag;
    exports.setTags = core.setTags;
    exports.setUser = core.setUser;
    exports.spanStatusfromHttpCode = core.spanStatusfromHttpCode;
    exports.startActiveSpan = core.startActiveSpan;
    exports.startInactiveSpan = core.startInactiveSpan;
    exports.startSession = core.startSession;
    exports.startSpan = core.startSpan;
    exports.startSpanManual = core.startSpanManual;
    exports.startTransaction = core.startTransaction;
    exports.trace = core.trace;
    exports.withActiveSpan = core.withActiveSpan;
    exports.withIsolationScope = core.withIsolationScope;
    exports.withMonitor = core.withMonitor;
    exports.withScope = core.withScope;
    exports.autoDiscoverNodePerformanceMonitoringIntegrations = index.autoDiscoverNodePerformanceMonitoringIntegrations;
    exports.NodeClient = client.NodeClient;
    exports.makeNodeTransport = http.makeNodeTransport;
    exports.defaultIntegrations = sdk.defaultIntegrations;
    exports.defaultStackParser = sdk.defaultStackParser;
    exports.getDefaultIntegrations = sdk.getDefaultIntegrations;
    exports.getSentryRelease = sdk.getSentryRelease;
    exports.init = sdk.init;
    exports.DEFAULT_USER_INCLUDES = utils.DEFAULT_USER_INCLUDES;
    exports.addRequestDataToEvent = utils.addRequestDataToEvent;
    exports.extractRequestData = utils.extractRequestData;
    exports.deepReadDirSync = utils$1.deepReadDirSync;
    exports.createGetModuleFromFilename = module$1.createGetModuleFromFilename;
    exports.enableAnrDetection = legacy.enableAnrDetection;
    exports.Handlers = handlers;
    exports.captureConsoleIntegration = integrations.captureConsoleIntegration;
    exports.debugIntegration = integrations.debugIntegration;
    exports.dedupeIntegration = integrations.dedupeIntegration;
    exports.extraErrorDataIntegration = integrations.extraErrorDataIntegration;
    exports.httpClientIntegration = integrations.httpClientIntegration;
    exports.reportingObserverIntegration = integrations.reportingObserverIntegration;
    exports.rewriteFramesIntegration = integrations.rewriteFramesIntegration;
    exports.sessionTimingIntegration = integrations.sessionTimingIntegration;
    exports.consoleIntegration = console2.consoleIntegration;
    exports.onUncaughtExceptionIntegration = onuncaughtexception.onUncaughtExceptionIntegration;
    exports.onUnhandledRejectionIntegration = onunhandledrejection.onUnhandledRejectionIntegration;
    exports.modulesIntegration = modules.modulesIntegration;
    exports.contextLinesIntegration = contextlines.contextLinesIntegration;
    exports.nodeContextIntegration = context2.nodeContextIntegration;
    exports.localVariablesIntegration = index$1.localVariablesIntegration;
    exports.spotlightIntegration = spotlight.spotlightIntegration;
    exports.anrIntegration = index$2.anrIntegration;
    exports.hapiErrorPlugin = index$3.hapiErrorPlugin;
    exports.hapiIntegration = index$3.hapiIntegration;
    exports.Undici = index$4.Undici;
    exports.nativeNodeFetchintegration = index$4.nativeNodeFetchintegration;
    exports.Http = http$1.Http;
    exports.httpIntegration = http$1.httpIntegration;
    exports.trpcMiddleware = trpc.trpcMiddleware;
    exports.Integrations = Integrations;
    exports.cron = cron;
    exports.getModuleFromFilename = getModuleFromFilename;
  }
});

// src/main.ts
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/esm.mjs
init_define_ENV_DEFINED_IN_BUILD_STEP();
var import_index = __toESM(require_commander(), 1);
var {
  program,
  createCommand,
  createArgument,
  createOption,
  CommanderError,
  InvalidArgumentError,
  InvalidOptionArgumentError,
  // deprecated old name
  Command,
  Argument,
  Option,
  Help
} = import_index.default;

// src/commands/machine/index.ts
init_define_ENV_DEFINED_IN_BUILD_STEP();

// src/commands/machine/translate.ts
init_define_ENV_DEFINED_IN_BUILD_STEP();

// src/utilities/getInlangProject.ts
init_define_ENV_DEFINED_IN_BUILD_STEP();
import fs from "node:fs";

// ../sdk/dist/index.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../sdk/dist/project/newProject.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/account/database-schema.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var import_human_id = __toESM(require_dist(), 1);
function applyAccountDatabaseSchema(sqlite2) {
  const anonymousAccountName = `Anonymous ${(0, import_human_id.humanId)({
    capitalize: true,
    adjectiveCount: 0,
    separator: "_"
  }).split("_")[0].slice(0, -1)}`;
  const sql2 = `
  CREATE TABLE IF NOT EXISTS account (
    id TEXT PRIMARY KEY DEFAULT (uuid_v7()),
    name TEXT NOT NULL
  ) STRICT;

  -- current account(s)
  -- temp table because current accounts are session
  -- specific and should not be persisted
  CREATE TEMP TABLE IF NOT EXISTS active_account (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL
    -- can't use foreign keys in temp tables... :(
  ) STRICT;

  -- default to a new account
  INSERT INTO active_account (id, name) values (uuid_v7(), '${anonymousAccountName}');
`;
  return sqlite2.exec(sql2);
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/change/create-change.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/kysely.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/schema.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/alter-table-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/util/object-utils.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function isUndefined(obj) {
  return typeof obj === "undefined" || obj === void 0;
}
function isString(obj) {
  return typeof obj === "string";
}
function isNumber(obj) {
  return typeof obj === "number";
}
function isBoolean(obj) {
  return typeof obj === "boolean";
}
function isNull(obj) {
  return obj === null;
}
function isDate(obj) {
  return obj instanceof Date;
}
function isBigInt(obj) {
  return typeof obj === "bigint";
}
function isFunction(obj) {
  return typeof obj === "function";
}
function isObject(obj) {
  return typeof obj === "object" && obj !== null;
}
function isPlainObject(obj) {
  if (!isObject(obj) || getTag(obj) !== "[object Object]") {
    return false;
  }
  if (Object.getPrototypeOf(obj) === null) {
    return true;
  }
  let proto = obj;
  while (Object.getPrototypeOf(proto) !== null) {
    proto = Object.getPrototypeOf(proto);
  }
  return Object.getPrototypeOf(obj) === proto;
}
function freeze(obj) {
  return Object.freeze(obj);
}
function asArray(arg) {
  if (isReadonlyArray(arg)) {
    return arg;
  } else {
    return [arg];
  }
}
function isReadonlyArray(arg) {
  return Array.isArray(arg);
}
function noop(obj) {
  return obj;
}
var toString = Object.prototype.toString;
function getTag(value) {
  if (value == null) {
    return value === void 0 ? "[object Undefined]" : "[object Null]";
  }
  return toString.call(value);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/alter-table-node.js
var AlterTableNode = freeze({
  is(node) {
    return node.kind === "AlterTableNode";
  },
  create(table) {
    return freeze({
      kind: "AlterTableNode",
      table
    });
  },
  cloneWithTableProps(node, props) {
    return freeze({
      ...node,
      ...props
    });
  },
  cloneWithColumnAlteration(node, columnAlteration) {
    return freeze({
      ...node,
      columnAlterations: node.columnAlterations ? [...node.columnAlterations, columnAlteration] : [columnAlteration]
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/create-index-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/identifier-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var IdentifierNode = freeze({
  is(node) {
    return node.kind === "IdentifierNode";
  },
  create(name) {
    return freeze({
      kind: "IdentifierNode",
      name
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/create-index-node.js
var CreateIndexNode = freeze({
  is(node) {
    return node.kind === "CreateIndexNode";
  },
  create(name) {
    return freeze({
      kind: "CreateIndexNode",
      name: IdentifierNode.create(name)
    });
  },
  cloneWith(node, props) {
    return freeze({
      ...node,
      ...props
    });
  },
  cloneWithColumns(node, columns) {
    return freeze({
      ...node,
      columns: [...node.columns || [], ...columns]
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/create-schema-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var CreateSchemaNode = freeze({
  is(node) {
    return node.kind === "CreateSchemaNode";
  },
  create(schema, params) {
    return freeze({
      kind: "CreateSchemaNode",
      schema: IdentifierNode.create(schema),
      ...params
    });
  },
  cloneWith(createSchema, params) {
    return freeze({
      ...createSchema,
      ...params
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/create-table-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ON_COMMIT_ACTIONS = ["preserve rows", "delete rows", "drop"];
var CreateTableNode = freeze({
  is(node) {
    return node.kind === "CreateTableNode";
  },
  create(table) {
    return freeze({
      kind: "CreateTableNode",
      table,
      columns: freeze([])
    });
  },
  cloneWithColumn(createTable, column) {
    return freeze({
      ...createTable,
      columns: freeze([...createTable.columns, column])
    });
  },
  cloneWithConstraint(createTable, constraint) {
    return freeze({
      ...createTable,
      constraints: createTable.constraints ? freeze([...createTable.constraints, constraint]) : freeze([constraint])
    });
  },
  cloneWithFrontModifier(createTable, modifier) {
    return freeze({
      ...createTable,
      frontModifiers: createTable.frontModifiers ? freeze([...createTable.frontModifiers, modifier]) : freeze([modifier])
    });
  },
  cloneWithEndModifier(createTable, modifier) {
    return freeze({
      ...createTable,
      endModifiers: createTable.endModifiers ? freeze([...createTable.endModifiers, modifier]) : freeze([modifier])
    });
  },
  cloneWith(createTable, params) {
    return freeze({
      ...createTable,
      ...params
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/drop-index-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/schemable-identifier-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var SchemableIdentifierNode = freeze({
  is(node) {
    return node.kind === "SchemableIdentifierNode";
  },
  create(identifier) {
    return freeze({
      kind: "SchemableIdentifierNode",
      identifier: IdentifierNode.create(identifier)
    });
  },
  createWithSchema(schema, identifier) {
    return freeze({
      kind: "SchemableIdentifierNode",
      schema: IdentifierNode.create(schema),
      identifier: IdentifierNode.create(identifier)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/drop-index-node.js
var DropIndexNode = freeze({
  is(node) {
    return node.kind === "DropIndexNode";
  },
  create(name, params) {
    return freeze({
      kind: "DropIndexNode",
      name: SchemableIdentifierNode.create(name),
      ...params
    });
  },
  cloneWith(dropIndex, props) {
    return freeze({
      ...dropIndex,
      ...props
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/drop-schema-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DropSchemaNode = freeze({
  is(node) {
    return node.kind === "DropSchemaNode";
  },
  create(schema, params) {
    return freeze({
      kind: "DropSchemaNode",
      schema: IdentifierNode.create(schema),
      ...params
    });
  },
  cloneWith(dropSchema, params) {
    return freeze({
      ...dropSchema,
      ...params
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/drop-table-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DropTableNode = freeze({
  is(node) {
    return node.kind === "DropTableNode";
  },
  create(table, params) {
    return freeze({
      kind: "DropTableNode",
      table,
      ...params
    });
  },
  cloneWith(dropIndex, params) {
    return freeze({
      ...dropIndex,
      ...params
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/table-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/alias-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var AliasNode = freeze({
  is(node) {
    return node.kind === "AliasNode";
  },
  create(node, alias) {
    return freeze({
      kind: "AliasNode",
      node,
      alias
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/table-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var TableNode = freeze({
  is(node) {
    return node.kind === "TableNode";
  },
  create(table) {
    return freeze({
      kind: "TableNode",
      table: SchemableIdentifierNode.create(table)
    });
  },
  createWithSchema(schema, table) {
    return freeze({
      kind: "TableNode",
      table: SchemableIdentifierNode.createWithSchema(schema, table)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/expression-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/expression/expression.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/operation-node-source.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function isOperationNodeSource(obj) {
  return isObject(obj) && isFunction(obj.toOperationNode);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/expression/expression.js
function isExpression(obj) {
  return isObject(obj) && "expressionType" in obj && isOperationNodeSource(obj);
}
function isAliasedExpression(obj) {
  return isObject(obj) && "expression" in obj && isString(obj.alias) && isOperationNodeSource(obj);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/expression/expression-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/select-query-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/select-modifier-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var SelectModifierNode = freeze({
  is(node) {
    return node.kind === "SelectModifierNode";
  },
  create(modifier, of) {
    return freeze({
      kind: "SelectModifierNode",
      modifier,
      of
    });
  },
  createWithExpression(modifier) {
    return freeze({
      kind: "SelectModifierNode",
      rawModifier: modifier
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/join-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/join-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/on-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/and-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var AndNode = freeze({
  is(node) {
    return node.kind === "AndNode";
  },
  create(left, right) {
    return freeze({
      kind: "AndNode",
      left,
      right
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/or-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var OrNode = freeze({
  is(node) {
    return node.kind === "OrNode";
  },
  create(left, right) {
    return freeze({
      kind: "OrNode",
      left,
      right
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/on-node.js
var OnNode = freeze({
  is(node) {
    return node.kind === "OnNode";
  },
  create(filter) {
    return freeze({
      kind: "OnNode",
      on: filter
    });
  },
  cloneWithOperation(onNode, operator, operation) {
    return freeze({
      ...onNode,
      on: operator === "And" ? AndNode.create(onNode.on, operation) : OrNode.create(onNode.on, operation)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/join-node.js
var JoinNode = freeze({
  is(node) {
    return node.kind === "JoinNode";
  },
  create(joinType, table) {
    return freeze({
      kind: "JoinNode",
      joinType,
      table,
      on: void 0
    });
  },
  createWithOn(joinType, table, on) {
    return freeze({
      kind: "JoinNode",
      joinType,
      table,
      on: OnNode.create(on)
    });
  },
  cloneWithOn(joinNode, operation) {
    return freeze({
      ...joinNode,
      on: joinNode.on ? OnNode.cloneWithOperation(joinNode.on, "And", operation) : OnNode.create(operation)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/binary-operation-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/binary-operation-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var BinaryOperationNode = freeze({
  is(node) {
    return node.kind === "BinaryOperationNode";
  },
  create(leftOperand, operator, rightOperand) {
    return freeze({
      kind: "BinaryOperationNode",
      leftOperand,
      operator,
      rightOperand
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/operator-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var COMPARISON_OPERATORS = [
  "=",
  "==",
  "!=",
  "<>",
  ">",
  ">=",
  "<",
  "<=",
  "in",
  "not in",
  "is",
  "is not",
  "like",
  "not like",
  "match",
  "ilike",
  "not ilike",
  "@>",
  "<@",
  "^@",
  "&&",
  "?",
  "?&",
  "?|",
  "!<",
  "!>",
  "<=>",
  "!~",
  "~",
  "~*",
  "!~*",
  "@@",
  "@@@",
  "!!",
  "<->",
  "regexp",
  "is distinct from",
  "is not distinct from"
];
var ARITHMETIC_OPERATORS = [
  "+",
  "-",
  "*",
  "/",
  "%",
  "^",
  "&",
  "|",
  "#",
  "<<",
  ">>"
];
var JSON_OPERATORS = ["->", "->>"];
var BINARY_OPERATORS = [
  ...COMPARISON_OPERATORS,
  ...ARITHMETIC_OPERATORS,
  "&&",
  "||"
];
var UNARY_FILTER_OPERATORS = ["exists", "not exists"];
var UNARY_OPERATORS = ["not", "-", ...UNARY_FILTER_OPERATORS];
var OPERATORS = [
  ...BINARY_OPERATORS,
  ...JSON_OPERATORS,
  ...UNARY_OPERATORS,
  "between",
  "between symmetric"
];
var OperatorNode = freeze({
  is(node) {
    return node.kind === "OperatorNode";
  },
  create(operator) {
    return freeze({
      kind: "OperatorNode",
      operator
    });
  }
});
function isJSONOperator(op) {
  return isString(op) && JSON_OPERATORS.includes(op);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/reference-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/column-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ColumnNode = freeze({
  is(node) {
    return node.kind === "ColumnNode";
  },
  create(column) {
    return freeze({
      kind: "ColumnNode",
      column: IdentifierNode.create(column)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/reference-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/select-all-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var SelectAllNode = freeze({
  is(node) {
    return node.kind === "SelectAllNode";
  },
  create() {
    return freeze({
      kind: "SelectAllNode"
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/reference-node.js
var ReferenceNode = freeze({
  is(node) {
    return node.kind === "ReferenceNode";
  },
  create(column, table) {
    return freeze({
      kind: "ReferenceNode",
      table,
      column
    });
  },
  createSelectAll(table) {
    return freeze({
      kind: "ReferenceNode",
      table,
      column: SelectAllNode.create()
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/order-by-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/dynamic/dynamic-reference-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DynamicReferenceBuilder = class {
  #dynamicReference;
  get dynamicReference() {
    return this.#dynamicReference;
  }
  /**
   * @private
   *
   * This needs to be here just so that the typings work. Without this
   * the generated .d.ts file contains no reference to the type param R
   * which causes this type to be equal to DynamicReferenceBuilder with
   * any R.
   */
  get refType() {
    return void 0;
  }
  constructor(reference) {
    this.#dynamicReference = reference;
  }
  toOperationNode() {
    return parseSimpleReferenceExpression(this.#dynamicReference);
  }
};
function isDynamicReferenceBuilder(obj) {
  return isObject(obj) && isOperationNodeSource(obj) && isString(obj.dynamicReference);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/order-by-item-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var OrderByItemNode = freeze({
  is(node) {
    return node.kind === "OrderByItemNode";
  },
  create(orderBy, direction) {
    return freeze({
      kind: "OrderByItemNode",
      orderBy,
      direction
    });
  },
  cloneWith(node, props) {
    return freeze({
      ...node,
      ...props
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/raw-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var RawNode = freeze({
  is(node) {
    return node.kind === "RawNode";
  },
  create(sqlFragments, parameters) {
    return freeze({
      kind: "RawNode",
      sqlFragments: freeze(sqlFragments),
      parameters: freeze(parameters)
    });
  },
  createWithSql(sql2) {
    return RawNode.create([sql2], []);
  },
  createWithChild(child) {
    return RawNode.create(["", ""], [child]);
  },
  createWithChildren(children) {
    return RawNode.create(new Array(children.length + 1).fill(""), children);
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/order-by-item-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/collate-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var CollateNode = freeze({
  is(node) {
    return node.kind === "CollateNode";
  },
  create(collation) {
    return freeze({
      kind: "CollateNode",
      collation: IdentifierNode.create(collation)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/order-by-item-builder.js
var OrderByItemBuilder = class _OrderByItemBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  /**
   * Adds `desc` to the `order by` item.
   *
   * See {@link asc} for the opposite.
   */
  desc() {
    return new _OrderByItemBuilder({
      node: OrderByItemNode.cloneWith(this.#props.node, {
        direction: RawNode.createWithSql("desc")
      })
    });
  }
  /**
   * Adds `asc` to the `order by` item.
   *
   * See {@link desc} for the opposite.
   */
  asc() {
    return new _OrderByItemBuilder({
      node: OrderByItemNode.cloneWith(this.#props.node, {
        direction: RawNode.createWithSql("asc")
      })
    });
  }
  /**
   * Adds `nulls last` to the `order by` item.
   *
   * This is only supported by some dialects like PostgreSQL and SQLite.
   *
   * See {@link nullsFirst} for the opposite.
   */
  nullsLast() {
    return new _OrderByItemBuilder({
      node: OrderByItemNode.cloneWith(this.#props.node, { nulls: "last" })
    });
  }
  /**
   * Adds `nulls first` to the `order by` item.
   *
   * This is only supported by some dialects like PostgreSQL and SQLite.
   *
   * See {@link nullsLast} for the opposite.
   */
  nullsFirst() {
    return new _OrderByItemBuilder({
      node: OrderByItemNode.cloneWith(this.#props.node, { nulls: "first" })
    });
  }
  /**
   * Adds `collate <collationName>` to the `order by` item.
   */
  collate(collation) {
    return new _OrderByItemBuilder({
      node: OrderByItemNode.cloneWith(this.#props.node, {
        collation: CollateNode.create(collation)
      })
    });
  }
  toOperationNode() {
    return this.#props.node;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/util/log-once.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var LOGGED_MESSAGES = /* @__PURE__ */ new Set();
function logOnce(message) {
  if (LOGGED_MESSAGES.has(message)) {
    return;
  }
  LOGGED_MESSAGES.add(message);
  console.log(message);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/order-by-parser.js
function isOrderByDirection(thing) {
  return thing === "asc" || thing === "desc";
}
function parseOrderBy(args) {
  if (args.length === 2) {
    return [parseOrderByItem(args[0], args[1])];
  }
  if (args.length === 1) {
    const [orderBy] = args;
    if (Array.isArray(orderBy)) {
      logOnce("orderBy(array) is deprecated, use multiple orderBy calls instead.");
      return orderBy.map((item) => parseOrderByItem(item));
    }
    return [parseOrderByItem(orderBy)];
  }
  throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${args.length}`);
}
function parseOrderByItem(expr, modifiers) {
  const parsedRef = parseOrderByExpression(expr);
  if (OrderByItemNode.is(parsedRef)) {
    if (modifiers) {
      throw new Error("Cannot specify direction twice!");
    }
    return parsedRef;
  }
  return parseOrderByWithModifiers(parsedRef, modifiers);
}
function parseOrderByExpression(expr) {
  if (isExpressionOrFactory(expr)) {
    return parseExpression(expr);
  }
  if (isDynamicReferenceBuilder(expr)) {
    return expr.toOperationNode();
  }
  const [ref, direction] = expr.split(" ");
  if (direction) {
    logOnce("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead.");
    return parseOrderByWithModifiers(parseStringReference(ref), direction);
  }
  return parseStringReference(expr);
}
function parseOrderByWithModifiers(expr, modifiers) {
  if (typeof modifiers === "string") {
    if (!isOrderByDirection(modifiers)) {
      throw new Error(`Invalid order by direction: ${modifiers}`);
    }
    return OrderByItemNode.create(expr, RawNode.createWithSql(modifiers));
  }
  if (isExpression(modifiers)) {
    logOnce("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead.");
    return OrderByItemNode.create(expr, modifiers.toOperationNode());
  }
  const node = OrderByItemNode.create(expr);
  if (!modifiers) {
    return node;
  }
  return modifiers(new OrderByItemBuilder({ node })).toOperationNode();
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/json-reference-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var JSONReferenceNode = freeze({
  is(node) {
    return node.kind === "JSONReferenceNode";
  },
  create(reference, traversal) {
    return freeze({
      kind: "JSONReferenceNode",
      reference,
      traversal
    });
  },
  cloneWithTraversal(node, traversal) {
    return freeze({
      ...node,
      traversal
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/json-operator-chain-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var JSONOperatorChainNode = freeze({
  is(node) {
    return node.kind === "JSONOperatorChainNode";
  },
  create(operator) {
    return freeze({
      kind: "JSONOperatorChainNode",
      operator,
      values: freeze([])
    });
  },
  cloneWithValue(node, value) {
    return freeze({
      ...node,
      values: freeze([...node.values, value])
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/json-path-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var JSONPathNode = freeze({
  is(node) {
    return node.kind === "JSONPathNode";
  },
  create(inOperator) {
    return freeze({
      kind: "JSONPathNode",
      inOperator,
      pathLegs: freeze([])
    });
  },
  cloneWithLeg(jsonPathNode, pathLeg) {
    return freeze({
      ...jsonPathNode,
      pathLegs: freeze([...jsonPathNode.pathLegs, pathLeg])
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/reference-parser.js
function parseSimpleReferenceExpression(exp) {
  if (isString(exp)) {
    return parseStringReference(exp);
  }
  return exp.toOperationNode();
}
function parseReferenceExpressionOrList(arg) {
  if (isReadonlyArray(arg)) {
    return arg.map((it) => parseReferenceExpression(it));
  } else {
    return [parseReferenceExpression(arg)];
  }
}
function parseReferenceExpression(exp) {
  if (isExpressionOrFactory(exp)) {
    return parseExpression(exp);
  }
  return parseSimpleReferenceExpression(exp);
}
function parseJSONReference(ref, op) {
  const referenceNode = parseStringReference(ref);
  if (isJSONOperator(op)) {
    return JSONReferenceNode.create(referenceNode, JSONOperatorChainNode.create(OperatorNode.create(op)));
  }
  const opWithoutLastChar = op.slice(0, -1);
  if (isJSONOperator(opWithoutLastChar)) {
    return JSONReferenceNode.create(referenceNode, JSONPathNode.create(OperatorNode.create(opWithoutLastChar)));
  }
  throw new Error(`Invalid JSON operator: ${op}`);
}
function parseStringReference(ref) {
  const COLUMN_SEPARATOR = ".";
  if (!ref.includes(COLUMN_SEPARATOR)) {
    return ReferenceNode.create(ColumnNode.create(ref));
  }
  const parts = ref.split(COLUMN_SEPARATOR).map(trim);
  if (parts.length === 3) {
    return parseStringReferenceWithTableAndSchema(parts);
  }
  if (parts.length === 2) {
    return parseStringReferenceWithTable(parts);
  }
  throw new Error(`invalid column reference ${ref}`);
}
function parseAliasedStringReference(ref) {
  const ALIAS_SEPARATOR = " as ";
  if (ref.includes(ALIAS_SEPARATOR)) {
    const [columnRef, alias] = ref.split(ALIAS_SEPARATOR).map(trim);
    return AliasNode.create(parseStringReference(columnRef), IdentifierNode.create(alias));
  } else {
    return parseStringReference(ref);
  }
}
function parseColumnName(column) {
  return ColumnNode.create(column);
}
function parseOrderedColumnName(column) {
  const ORDER_SEPARATOR = " ";
  if (column.includes(ORDER_SEPARATOR)) {
    const [columnName, order] = column.split(ORDER_SEPARATOR).map(trim);
    if (!isOrderByDirection(order)) {
      throw new Error(`invalid order direction "${order}" next to "${columnName}"`);
    }
    return parseOrderBy([columnName, order])[0];
  } else {
    return parseColumnName(column);
  }
}
function parseStringReferenceWithTableAndSchema(parts) {
  const [schema, table, column] = parts;
  return ReferenceNode.create(ColumnNode.create(column), TableNode.createWithSchema(schema, table));
}
function parseStringReferenceWithTable(parts) {
  const [table, column] = parts;
  return ReferenceNode.create(ColumnNode.create(column), TableNode.create(table));
}
function trim(str) {
  return str.trim();
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/value-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/primitive-value-list-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var PrimitiveValueListNode = freeze({
  is(node) {
    return node.kind === "PrimitiveValueListNode";
  },
  create(values) {
    return freeze({
      kind: "PrimitiveValueListNode",
      values: freeze([...values])
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/value-list-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ValueListNode = freeze({
  is(node) {
    return node.kind === "ValueListNode";
  },
  create(values) {
    return freeze({
      kind: "ValueListNode",
      values: freeze(values)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/value-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ValueNode = freeze({
  is(node) {
    return node.kind === "ValueNode";
  },
  create(value) {
    return freeze({
      kind: "ValueNode",
      value
    });
  },
  createImmediate(value) {
    return freeze({
      kind: "ValueNode",
      value,
      immediate: true
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/value-parser.js
function parseValueExpressionOrList(arg) {
  if (isReadonlyArray(arg)) {
    return parseValueExpressionList(arg);
  }
  return parseValueExpression(arg);
}
function parseValueExpression(exp) {
  if (isExpressionOrFactory(exp)) {
    return parseExpression(exp);
  }
  return ValueNode.create(exp);
}
function isSafeImmediateValue(value) {
  return isNumber(value) || isBoolean(value) || isNull(value);
}
function parseSafeImmediateValue(value) {
  if (!isSafeImmediateValue(value)) {
    throw new Error(`unsafe immediate value ${JSON.stringify(value)}`);
  }
  return ValueNode.createImmediate(value);
}
function parseValueExpressionList(arg) {
  if (arg.some(isExpressionOrFactory)) {
    return ValueListNode.create(arg.map((it) => parseValueExpression(it)));
  }
  return PrimitiveValueListNode.create(arg);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/parens-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ParensNode = freeze({
  is(node) {
    return node.kind === "ParensNode";
  },
  create(node) {
    return freeze({
      kind: "ParensNode",
      node
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/binary-operation-parser.js
function parseValueBinaryOperationOrExpression(args) {
  if (args.length === 3) {
    return parseValueBinaryOperation(args[0], args[1], args[2]);
  } else if (args.length === 1) {
    return parseValueExpression(args[0]);
  }
  throw new Error(`invalid arguments: ${JSON.stringify(args)}`);
}
function parseValueBinaryOperation(left, operator, right) {
  if (isIsOperator(operator) && needsIsOperator(right)) {
    return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), ValueNode.createImmediate(right));
  }
  return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseValueExpressionOrList(right));
}
function parseReferentialBinaryOperation(left, operator, right) {
  return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseReferenceExpression(right));
}
function parseFilterObject(obj, combinator) {
  return parseFilterList(Object.entries(obj).filter(([, v3]) => !isUndefined(v3)).map(([k2, v3]) => parseValueBinaryOperation(k2, needsIsOperator(v3) ? "is" : "=", v3)), combinator);
}
function parseFilterList(list, combinator, withParens = true) {
  const combine = combinator === "and" ? AndNode.create : OrNode.create;
  if (list.length === 0) {
    return BinaryOperationNode.create(ValueNode.createImmediate(1), OperatorNode.create("="), ValueNode.createImmediate(combinator === "and" ? 1 : 0));
  }
  let node = toOperationNode(list[0]);
  for (let i2 = 1; i2 < list.length; ++i2) {
    node = combine(node, toOperationNode(list[i2]));
  }
  if (list.length > 1 && withParens) {
    return ParensNode.create(node);
  }
  return node;
}
function isIsOperator(operator) {
  return operator === "is" || operator === "is not";
}
function needsIsOperator(value) {
  return isNull(value) || isBoolean(value);
}
function parseOperator(operator) {
  if (isString(operator) && OPERATORS.includes(operator)) {
    return OperatorNode.create(operator);
  }
  if (isOperationNodeSource(operator)) {
    return operator.toOperationNode();
  }
  throw new Error(`invalid operator ${JSON.stringify(operator)}`);
}
function toOperationNode(nodeOrSource) {
  return isOperationNodeSource(nodeOrSource) ? nodeOrSource.toOperationNode() : nodeOrSource;
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/parse-utils.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/over-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/order-by-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var OrderByNode = freeze({
  is(node) {
    return node.kind === "OrderByNode";
  },
  create(items) {
    return freeze({
      kind: "OrderByNode",
      items: freeze([...items])
    });
  },
  cloneWithItems(orderBy, items) {
    return freeze({
      ...orderBy,
      items: freeze([...orderBy.items, ...items])
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/partition-by-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var PartitionByNode = freeze({
  is(node) {
    return node.kind === "PartitionByNode";
  },
  create(items) {
    return freeze({
      kind: "PartitionByNode",
      items: freeze(items)
    });
  },
  cloneWithItems(partitionBy, items) {
    return freeze({
      ...partitionBy,
      items: freeze([...partitionBy.items, ...items])
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/over-node.js
var OverNode = freeze({
  is(node) {
    return node.kind === "OverNode";
  },
  create() {
    return freeze({
      kind: "OverNode"
    });
  },
  cloneWithOrderByItems(overNode, items) {
    return freeze({
      ...overNode,
      orderBy: overNode.orderBy ? OrderByNode.cloneWithItems(overNode.orderBy, items) : OrderByNode.create(items)
    });
  },
  cloneWithPartitionByItems(overNode, items) {
    return freeze({
      ...overNode,
      partitionBy: overNode.partitionBy ? PartitionByNode.cloneWithItems(overNode.partitionBy, items) : PartitionByNode.create(items)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/select-query-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/from-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var FromNode = freeze({
  is(node) {
    return node.kind === "FromNode";
  },
  create(froms) {
    return freeze({
      kind: "FromNode",
      froms: freeze(froms)
    });
  },
  cloneWithFroms(from, froms) {
    return freeze({
      ...from,
      froms: freeze([...from.froms, ...froms])
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/group-by-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var GroupByNode = freeze({
  is(node) {
    return node.kind === "GroupByNode";
  },
  create(items) {
    return freeze({
      kind: "GroupByNode",
      items: freeze(items)
    });
  },
  cloneWithItems(groupBy, items) {
    return freeze({
      ...groupBy,
      items: freeze([...groupBy.items, ...items])
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/having-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var HavingNode = freeze({
  is(node) {
    return node.kind === "HavingNode";
  },
  create(filter) {
    return freeze({
      kind: "HavingNode",
      having: filter
    });
  },
  cloneWithOperation(havingNode, operator, operation) {
    return freeze({
      ...havingNode,
      having: operator === "And" ? AndNode.create(havingNode.having, operation) : OrNode.create(havingNode.having, operation)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/query-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/insert-query-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var InsertQueryNode = freeze({
  is(node) {
    return node.kind === "InsertQueryNode";
  },
  create(into, withNode, replace) {
    return freeze({
      kind: "InsertQueryNode",
      into,
      ...withNode && { with: withNode },
      replace
    });
  },
  createWithoutInto() {
    return freeze({
      kind: "InsertQueryNode"
    });
  },
  cloneWith(insertQuery, props) {
    return freeze({
      ...insertQuery,
      ...props
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/update-query-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/list-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ListNode = freeze({
  is(node) {
    return node.kind === "ListNode";
  },
  create(items) {
    return freeze({
      kind: "ListNode",
      items: freeze(items)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/update-query-node.js
var UpdateQueryNode = freeze({
  is(node) {
    return node.kind === "UpdateQueryNode";
  },
  create(tables, withNode) {
    return freeze({
      kind: "UpdateQueryNode",
      // For backwards compatibility, use the raw table node when there's only one table
      // and don't rename the property to something like `tables`.
      table: tables.length === 1 ? tables[0] : ListNode.create(tables),
      ...withNode && { with: withNode }
    });
  },
  createWithoutTable() {
    return freeze({
      kind: "UpdateQueryNode"
    });
  },
  cloneWithFromItems(updateQuery, fromItems) {
    return freeze({
      ...updateQuery,
      from: updateQuery.from ? FromNode.cloneWithFroms(updateQuery.from, fromItems) : FromNode.create(fromItems)
    });
  },
  cloneWithUpdates(updateQuery, updates) {
    return freeze({
      ...updateQuery,
      updates: updateQuery.updates ? freeze([...updateQuery.updates, ...updates]) : updates
    });
  },
  cloneWithLimit(updateQuery, limit) {
    return freeze({
      ...updateQuery,
      limit
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/delete-query-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/using-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var UsingNode = freeze({
  is(node) {
    return node.kind === "UsingNode";
  },
  create(tables) {
    return freeze({
      kind: "UsingNode",
      tables: freeze(tables)
    });
  },
  cloneWithTables(using, tables) {
    return freeze({
      ...using,
      tables: freeze([...using.tables, ...tables])
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/delete-query-node.js
var DeleteQueryNode = freeze({
  is(node) {
    return node.kind === "DeleteQueryNode";
  },
  create(fromItems, withNode) {
    return freeze({
      kind: "DeleteQueryNode",
      from: FromNode.create(fromItems),
      ...withNode && { with: withNode }
    });
  },
  // TODO: remove in v0.29
  /**
   * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.
   */
  cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items),
  // TODO: remove in v0.29
  /**
   * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.
   */
  cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node),
  cloneWithLimit(deleteNode, limit) {
    return freeze({
      ...deleteNode,
      limit
    });
  },
  cloneWithoutLimit(deleteNode) {
    return freeze({
      ...deleteNode,
      limit: void 0
    });
  },
  cloneWithUsing(deleteNode, tables) {
    return freeze({
      ...deleteNode,
      using: deleteNode.using !== void 0 ? UsingNode.cloneWithTables(deleteNode.using, tables) : UsingNode.create(tables)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/where-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var WhereNode = freeze({
  is(node) {
    return node.kind === "WhereNode";
  },
  create(filter) {
    return freeze({
      kind: "WhereNode",
      where: filter
    });
  },
  cloneWithOperation(whereNode, operator, operation) {
    return freeze({
      ...whereNode,
      where: operator === "And" ? AndNode.create(whereNode.where, operation) : OrNode.create(whereNode.where, operation)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/returning-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ReturningNode = freeze({
  is(node) {
    return node.kind === "ReturningNode";
  },
  create(selections) {
    return freeze({
      kind: "ReturningNode",
      selections: freeze(selections)
    });
  },
  cloneWithSelections(returning, selections) {
    return freeze({
      ...returning,
      selections: returning.selections ? freeze([...returning.selections, ...selections]) : freeze(selections)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/explain-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ExplainNode = freeze({
  is(node) {
    return node.kind === "ExplainNode";
  },
  create(format, options) {
    return freeze({
      kind: "ExplainNode",
      format,
      options
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/merge-query-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/when-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var WhenNode = freeze({
  is(node) {
    return node.kind === "WhenNode";
  },
  create(condition) {
    return freeze({
      kind: "WhenNode",
      condition
    });
  },
  cloneWithResult(whenNode, result) {
    return freeze({
      ...whenNode,
      result
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/merge-query-node.js
var MergeQueryNode = freeze({
  is(node) {
    return node.kind === "MergeQueryNode";
  },
  create(into, withNode) {
    return freeze({
      kind: "MergeQueryNode",
      into,
      ...withNode && { with: withNode }
    });
  },
  cloneWithUsing(mergeNode, using) {
    return freeze({
      ...mergeNode,
      using
    });
  },
  cloneWithWhen(mergeNode, when) {
    return freeze({
      ...mergeNode,
      whens: mergeNode.whens ? freeze([...mergeNode.whens, when]) : freeze([when])
    });
  },
  cloneWithThen(mergeNode, then) {
    return freeze({
      ...mergeNode,
      whens: mergeNode.whens ? freeze([
        ...mergeNode.whens.slice(0, -1),
        WhenNode.cloneWithResult(mergeNode.whens[mergeNode.whens.length - 1], then)
      ]) : void 0
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/output-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var OutputNode = freeze({
  is(node) {
    return node.kind === "OutputNode";
  },
  create(selections) {
    return freeze({
      kind: "OutputNode",
      selections: freeze(selections)
    });
  },
  cloneWithSelections(output, selections) {
    return freeze({
      ...output,
      selections: output.selections ? freeze([...output.selections, ...selections]) : freeze(selections)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/query-node.js
var QueryNode = freeze({
  is(node) {
    return SelectQueryNode.is(node) || InsertQueryNode.is(node) || UpdateQueryNode.is(node) || DeleteQueryNode.is(node) || MergeQueryNode.is(node);
  },
  cloneWithEndModifier(node, modifier) {
    return freeze({
      ...node,
      endModifiers: node.endModifiers ? freeze([...node.endModifiers, modifier]) : freeze([modifier])
    });
  },
  cloneWithWhere(node, operation) {
    return freeze({
      ...node,
      where: node.where ? WhereNode.cloneWithOperation(node.where, "And", operation) : WhereNode.create(operation)
    });
  },
  cloneWithJoin(node, join) {
    return freeze({
      ...node,
      joins: node.joins ? freeze([...node.joins, join]) : freeze([join])
    });
  },
  cloneWithReturning(node, selections) {
    return freeze({
      ...node,
      returning: node.returning ? ReturningNode.cloneWithSelections(node.returning, selections) : ReturningNode.create(selections)
    });
  },
  cloneWithoutReturning(node) {
    return freeze({
      ...node,
      returning: void 0
    });
  },
  cloneWithoutWhere(node) {
    return freeze({
      ...node,
      where: void 0
    });
  },
  cloneWithExplain(node, format, options) {
    return freeze({
      ...node,
      explain: ExplainNode.create(format, options == null ? void 0 : options.toOperationNode())
    });
  },
  cloneWithTop(node, top) {
    return freeze({
      ...node,
      top
    });
  },
  cloneWithOutput(node, selections) {
    return freeze({
      ...node,
      output: node.output ? OutputNode.cloneWithSelections(node.output, selections) : OutputNode.create(selections)
    });
  },
  cloneWithOrderByItems(node, items) {
    return freeze({
      ...node,
      orderBy: node.orderBy ? OrderByNode.cloneWithItems(node.orderBy, items) : OrderByNode.create(items)
    });
  },
  cloneWithoutOrderBy(node) {
    return freeze({
      ...node,
      orderBy: void 0
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/select-query-node.js
var SelectQueryNode = freeze({
  is(node) {
    return node.kind === "SelectQueryNode";
  },
  create(withNode) {
    return freeze({
      kind: "SelectQueryNode",
      ...withNode && { with: withNode }
    });
  },
  createFrom(fromItems, withNode) {
    return freeze({
      kind: "SelectQueryNode",
      from: FromNode.create(fromItems),
      ...withNode && { with: withNode }
    });
  },
  cloneWithSelections(select, selections) {
    return freeze({
      ...select,
      selections: select.selections ? freeze([...select.selections, ...selections]) : freeze(selections)
    });
  },
  cloneWithDistinctOn(select, expressions) {
    return freeze({
      ...select,
      distinctOn: select.distinctOn ? freeze([...select.distinctOn, ...expressions]) : freeze(expressions)
    });
  },
  cloneWithFrontModifier(select, modifier) {
    return freeze({
      ...select,
      frontModifiers: select.frontModifiers ? freeze([...select.frontModifiers, modifier]) : freeze([modifier])
    });
  },
  // TODO: remove in v0.29
  /**
   * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.
   */
  cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items),
  cloneWithGroupByItems(selectNode, items) {
    return freeze({
      ...selectNode,
      groupBy: selectNode.groupBy ? GroupByNode.cloneWithItems(selectNode.groupBy, items) : GroupByNode.create(items)
    });
  },
  cloneWithLimit(selectNode, limit) {
    return freeze({
      ...selectNode,
      limit
    });
  },
  cloneWithOffset(selectNode, offset) {
    return freeze({
      ...selectNode,
      offset
    });
  },
  cloneWithFetch(selectNode, fetch2) {
    return freeze({
      ...selectNode,
      fetch: fetch2
    });
  },
  cloneWithHaving(selectNode, operation) {
    return freeze({
      ...selectNode,
      having: selectNode.having ? HavingNode.cloneWithOperation(selectNode.having, "And", operation) : HavingNode.create(operation)
    });
  },
  cloneWithSetOperations(selectNode, setOperations) {
    return freeze({
      ...selectNode,
      setOperations: selectNode.setOperations ? freeze([...selectNode.setOperations, ...setOperations]) : freeze([...setOperations])
    });
  },
  cloneWithoutSelections(select) {
    return freeze({
      ...select,
      selections: []
    });
  },
  cloneWithoutLimit(select) {
    return freeze({
      ...select,
      limit: void 0
    });
  },
  cloneWithoutOffset(select) {
    return freeze({
      ...select,
      offset: void 0
    });
  },
  // TODO: remove in v0.29
  /**
   * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.
   */
  cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node),
  cloneWithoutGroupBy(select) {
    return freeze({
      ...select,
      groupBy: void 0
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/join-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var JoinBuilder = class _JoinBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  on(...args) {
    return new _JoinBuilder({
      ...this.#props,
      joinNode: JoinNode.cloneWithOn(this.#props.joinNode, parseValueBinaryOperationOrExpression(args))
    });
  }
  /**
   * Just like {@link WhereInterface.whereRef} but adds an item to the join's
   * `on` clause instead.
   *
   * See {@link WhereInterface.whereRef} for documentation and examples.
   */
  onRef(lhs, op, rhs) {
    return new _JoinBuilder({
      ...this.#props,
      joinNode: JoinNode.cloneWithOn(this.#props.joinNode, parseReferentialBinaryOperation(lhs, op, rhs))
    });
  }
  /**
   * Adds `on true`.
   */
  onTrue() {
    return new _JoinBuilder({
      ...this.#props,
      joinNode: JoinNode.cloneWithOn(this.#props.joinNode, RawNode.createWithSql("true"))
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#props.joinNode;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/over-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/partition-by-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/partition-by-item-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var PartitionByItemNode = freeze({
  is(node) {
    return node.kind === "PartitionByItemNode";
  },
  create(partitionBy) {
    return freeze({
      kind: "PartitionByItemNode",
      partitionBy
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/partition-by-parser.js
function parsePartitionBy(partitionBy) {
  return parseReferenceExpressionOrList(partitionBy).map(PartitionByItemNode.create);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/over-builder.js
var OverBuilder = class _OverBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  orderBy(...args) {
    return new _OverBuilder({
      overNode: OverNode.cloneWithOrderByItems(this.#props.overNode, parseOrderBy(args))
    });
  }
  clearOrderBy() {
    return new _OverBuilder({
      overNode: QueryNode.cloneWithoutOrderBy(this.#props.overNode)
    });
  }
  partitionBy(partitionBy) {
    return new _OverBuilder({
      overNode: OverNode.cloneWithPartitionByItems(this.#props.overNode, parsePartitionBy(partitionBy))
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#props.overNode;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-creator.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/insert-query-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/select-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/selection-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var SelectionNode = freeze({
  is(node) {
    return node.kind === "SelectionNode";
  },
  create(selection) {
    return freeze({
      kind: "SelectionNode",
      selection
    });
  },
  createSelectAll() {
    return freeze({
      kind: "SelectionNode",
      selection: SelectAllNode.create()
    });
  },
  createSelectAllFromTable(table) {
    return freeze({
      kind: "SelectionNode",
      selection: ReferenceNode.createSelectAll(table)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/select-parser.js
function parseSelectArg(selection) {
  if (isFunction(selection)) {
    return parseSelectArg(selection(expressionBuilder()));
  } else if (isReadonlyArray(selection)) {
    return selection.map((it) => parseSelectExpression(it));
  } else {
    return [parseSelectExpression(selection)];
  }
}
function parseSelectExpression(selection) {
  if (isString(selection)) {
    return SelectionNode.create(parseAliasedStringReference(selection));
  } else if (isDynamicReferenceBuilder(selection)) {
    return SelectionNode.create(selection.toOperationNode());
  } else {
    return SelectionNode.create(parseAliasedExpression(selection));
  }
}
function parseSelectAll(table) {
  if (!table) {
    return [SelectionNode.createSelectAll()];
  } else if (Array.isArray(table)) {
    return table.map(parseSelectAllArg);
  } else {
    return [parseSelectAllArg(table)];
  }
}
function parseSelectAllArg(table) {
  if (isString(table)) {
    return SelectionNode.createSelectAllFromTable(parseTable(table));
  }
  throw new Error(`invalid value selectAll expression: ${JSON.stringify(table)}`);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/insert-values-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/values-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ValuesNode = freeze({
  is(node) {
    return node.kind === "ValuesNode";
  },
  create(values) {
    return freeze({
      kind: "ValuesNode",
      values: freeze(values)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/default-insert-value-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DefaultInsertValueNode = freeze({
  is(node) {
    return node.kind === "DefaultInsertValueNode";
  },
  create() {
    return freeze({
      kind: "DefaultInsertValueNode"
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/insert-values-parser.js
function parseInsertExpression(arg) {
  const objectOrList = isFunction(arg) ? arg(expressionBuilder()) : arg;
  const list = isReadonlyArray(objectOrList) ? objectOrList : freeze([objectOrList]);
  return parseInsertColumnsAndValues(list);
}
function parseInsertColumnsAndValues(rows) {
  const columns = parseColumnNamesAndIndexes(rows);
  return [
    freeze([...columns.keys()].map(ColumnNode.create)),
    ValuesNode.create(rows.map((row) => parseRowValues(row, columns)))
  ];
}
function parseColumnNamesAndIndexes(rows) {
  const columns = /* @__PURE__ */ new Map();
  for (const row of rows) {
    const cols = Object.keys(row);
    for (const col of cols) {
      if (!columns.has(col) && row[col] !== void 0) {
        columns.set(col, columns.size);
      }
    }
  }
  return columns;
}
function parseRowValues(row, columns) {
  const rowColumns = Object.keys(row);
  const rowValues = Array.from({
    length: columns.size
  });
  let hasUndefinedOrComplexColumns = false;
  let indexedRowColumns = rowColumns.length;
  for (const col of rowColumns) {
    const columnIdx = columns.get(col);
    if (isUndefined(columnIdx)) {
      indexedRowColumns--;
      continue;
    }
    const value = row[col];
    if (isUndefined(value) || isExpressionOrFactory(value)) {
      hasUndefinedOrComplexColumns = true;
    }
    rowValues[columnIdx] = value;
  }
  const hasMissingColumns = indexedRowColumns < columns.size;
  if (hasMissingColumns || hasUndefinedOrComplexColumns) {
    const defaultValue = DefaultInsertValueNode.create();
    return ValueListNode.create(rowValues.map((it) => isUndefined(it) ? defaultValue : parseValueExpression(it)));
  }
  return PrimitiveValueListNode.create(rowValues);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/update-set-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/column-update-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ColumnUpdateNode = freeze({
  is(node) {
    return node.kind === "ColumnUpdateNode";
  },
  create(column, value) {
    return freeze({
      kind: "ColumnUpdateNode",
      column,
      value
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/update-set-parser.js
function parseUpdate(...args) {
  if (args.length === 2) {
    return [
      ColumnUpdateNode.create(parseReferenceExpression(args[0]), parseValueExpression(args[1]))
    ];
  }
  return parseUpdateObjectExpression(args[0]);
}
function parseUpdateObjectExpression(update) {
  const updateObj = isFunction(update) ? update(expressionBuilder()) : update;
  return Object.entries(updateObj).filter(([_3, value]) => value !== void 0).map(([key, value]) => {
    return ColumnUpdateNode.create(ColumnNode.create(key), parseValueExpression(value));
  });
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/on-duplicate-key-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var OnDuplicateKeyNode = freeze({
  is(node) {
    return node.kind === "OnDuplicateKeyNode";
  },
  create(updates) {
    return freeze({
      kind: "OnDuplicateKeyNode",
      updates
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/insert-result.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var InsertResult = class {
  /**
   * The auto incrementing primary key of the inserted row.
   *
   * This property can be undefined when the query contains an `on conflict`
   * clause that makes the query succeed even when nothing gets inserted.
   *
   * This property is always undefined on dialects like PostgreSQL that
   * don't return the inserted id by default. On those dialects you need
   * to use the {@link ReturningInterface.returning | returning} method.
   */
  insertId;
  /**
   * Affected rows count.
   */
  numInsertedOrUpdatedRows;
  constructor(insertId, numInsertedOrUpdatedRows) {
    this.insertId = insertId;
    this.numInsertedOrUpdatedRows = numInsertedOrUpdatedRows;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/no-result-error.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var NoResultError = class extends Error {
  /**
   * The operation node tree of the query that was executed.
   */
  node;
  constructor(node) {
    super("no result");
    this.node = node;
  }
};
function isNoResultErrorConstructor(fn) {
  return Object.prototype.hasOwnProperty.call(fn, "prototype");
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/on-conflict-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/on-conflict-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var OnConflictNode = freeze({
  is(node) {
    return node.kind === "OnConflictNode";
  },
  create() {
    return freeze({
      kind: "OnConflictNode"
    });
  },
  cloneWith(node, props) {
    return freeze({
      ...node,
      ...props
    });
  },
  cloneWithIndexWhere(node, operation) {
    return freeze({
      ...node,
      indexWhere: node.indexWhere ? WhereNode.cloneWithOperation(node.indexWhere, "And", operation) : WhereNode.create(operation)
    });
  },
  cloneWithIndexOrWhere(node, operation) {
    return freeze({
      ...node,
      indexWhere: node.indexWhere ? WhereNode.cloneWithOperation(node.indexWhere, "Or", operation) : WhereNode.create(operation)
    });
  },
  cloneWithUpdateWhere(node, operation) {
    return freeze({
      ...node,
      updateWhere: node.updateWhere ? WhereNode.cloneWithOperation(node.updateWhere, "And", operation) : WhereNode.create(operation)
    });
  },
  cloneWithUpdateOrWhere(node, operation) {
    return freeze({
      ...node,
      updateWhere: node.updateWhere ? WhereNode.cloneWithOperation(node.updateWhere, "Or", operation) : WhereNode.create(operation)
    });
  },
  cloneWithoutIndexWhere(node) {
    return freeze({
      ...node,
      indexWhere: void 0
    });
  },
  cloneWithoutUpdateWhere(node) {
    return freeze({
      ...node,
      updateWhere: void 0
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/on-conflict-builder.js
var OnConflictBuilder = class _OnConflictBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  /**
   * Specify a single column as the conflict target.
   *
   * Also see the {@link columns}, {@link constraint} and {@link expression}
   * methods for alternative ways to specify the conflict target.
   */
  column(column) {
    const columnNode = ColumnNode.create(column);
    return new _OnConflictBuilder({
      ...this.#props,
      onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, {
        columns: this.#props.onConflictNode.columns ? freeze([...this.#props.onConflictNode.columns, columnNode]) : freeze([columnNode])
      })
    });
  }
  /**
   * Specify a list of columns as the conflict target.
   *
   * Also see the {@link column}, {@link constraint} and {@link expression}
   * methods for alternative ways to specify the conflict target.
   */
  columns(columns) {
    const columnNodes = columns.map(ColumnNode.create);
    return new _OnConflictBuilder({
      ...this.#props,
      onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, {
        columns: this.#props.onConflictNode.columns ? freeze([...this.#props.onConflictNode.columns, ...columnNodes]) : freeze(columnNodes)
      })
    });
  }
  /**
   * Specify a specific constraint by name as the conflict target.
   *
   * Also see the {@link column}, {@link columns} and {@link expression}
   * methods for alternative ways to specify the conflict target.
   */
  constraint(constraintName) {
    return new _OnConflictBuilder({
      ...this.#props,
      onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, {
        constraint: IdentifierNode.create(constraintName)
      })
    });
  }
  /**
   * Specify an expression as the conflict target.
   *
   * This can be used if the unique index is an expression index.
   *
   * Also see the {@link column}, {@link columns} and {@link constraint}
   * methods for alternative ways to specify the conflict target.
   */
  expression(expression) {
    return new _OnConflictBuilder({
      ...this.#props,
      onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, {
        indexExpression: expression.toOperationNode()
      })
    });
  }
  where(...args) {
    return new _OnConflictBuilder({
      ...this.#props,
      onConflictNode: OnConflictNode.cloneWithIndexWhere(this.#props.onConflictNode, parseValueBinaryOperationOrExpression(args))
    });
  }
  whereRef(lhs, op, rhs) {
    return new _OnConflictBuilder({
      ...this.#props,
      onConflictNode: OnConflictNode.cloneWithIndexWhere(this.#props.onConflictNode, parseReferentialBinaryOperation(lhs, op, rhs))
    });
  }
  clearWhere() {
    return new _OnConflictBuilder({
      ...this.#props,
      onConflictNode: OnConflictNode.cloneWithoutIndexWhere(this.#props.onConflictNode)
    });
  }
  /**
   * Adds the "do nothing" conflict action.
   *
   * ### Examples
   *
   * ```ts
   * const id = 1
   * const first_name = 'John'
   *
   * await db
   *   .insertInto('person')
   *   .values({ first_name, id })
   *   .onConflict((oc) => oc
   *     .column('id')
   *     .doNothing()
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * insert into "person" ("first_name", "id")
   * values ($1, $2)
   * on conflict ("id") do nothing
   * ```
   */
  doNothing() {
    return new OnConflictDoNothingBuilder({
      ...this.#props,
      onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, {
        doNothing: true
      })
    });
  }
  /**
   * Adds the "do update set" conflict action.
   *
   * ### Examples
   *
   * ```ts
   * const id = 1
   * const first_name = 'John'
   *
   * await db
   *   .insertInto('person')
   *   .values({ first_name, id })
   *   .onConflict((oc) => oc
   *     .column('id')
   *     .doUpdateSet({ first_name })
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * insert into "person" ("first_name", "id")
   * values ($1, $2)
   * on conflict ("id")
   * do update set "first_name" = $3
   * ```
   *
   * In the next example we use the `ref` method to reference
   * columns of the virtual table `excluded` in a type-safe way
   * to create an upsert operation:
   *
   * ```ts
   * import type { NewPerson } from 'type-editor' // imaginary module
   *
   * async function upsertPerson(person: NewPerson): Promise<void> {
   *   await db.insertInto('person')
   *     .values(person)
   *     .onConflict((oc) => oc
   *       .column('id')
   *       .doUpdateSet((eb) => ({
   *         first_name: eb.ref('excluded.first_name'),
   *         last_name: eb.ref('excluded.last_name')
   *       })
   *     )
   *   )
   *   .execute()
   * }
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * insert into "person" ("first_name", "last_name")
   * values ($1, $2)
   * on conflict ("id")
   * do update set
   *  "first_name" = excluded."first_name",
   *  "last_name" = excluded."last_name"
   * ```
   */
  doUpdateSet(update) {
    return new OnConflictUpdateBuilder({
      ...this.#props,
      onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, {
        updates: parseUpdateObjectExpression(update)
      })
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
};
var OnConflictDoNothingBuilder = class {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  toOperationNode() {
    return this.#props.onConflictNode;
  }
};
var OnConflictUpdateBuilder = class _OnConflictUpdateBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  where(...args) {
    return new _OnConflictUpdateBuilder({
      ...this.#props,
      onConflictNode: OnConflictNode.cloneWithUpdateWhere(this.#props.onConflictNode, parseValueBinaryOperationOrExpression(args))
    });
  }
  /**
   * Specify a where condition for the update operation.
   *
   * See {@link WhereInterface.whereRef} for more info.
   */
  whereRef(lhs, op, rhs) {
    return new _OnConflictUpdateBuilder({
      ...this.#props,
      onConflictNode: OnConflictNode.cloneWithUpdateWhere(this.#props.onConflictNode, parseReferentialBinaryOperation(lhs, op, rhs))
    });
  }
  clearWhere() {
    return new _OnConflictUpdateBuilder({
      ...this.#props,
      onConflictNode: OnConflictNode.cloneWithoutUpdateWhere(this.#props.onConflictNode)
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#props.onConflictNode;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/top-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/top-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var TopNode = freeze({
  is(node) {
    return node.kind === "TopNode";
  },
  create(expression, modifiers) {
    return freeze({
      kind: "TopNode",
      expression,
      modifiers
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/top-parser.js
function parseTop(expression, modifiers) {
  if (!isNumber(expression) && !isBigInt(expression)) {
    throw new Error(`Invalid top expression: ${expression}`);
  }
  if (!isUndefined(modifiers) && !isTopModifiers(modifiers)) {
    throw new Error(`Invalid top modifiers: ${modifiers}`);
  }
  return TopNode.create(expression, modifiers);
}
function isTopModifiers(modifiers) {
  return modifiers === "percent" || modifiers === "with ties" || modifiers === "percent with ties";
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/or-action-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var OrActionNode = freeze({
  is(node) {
    return node.kind === "OrActionNode";
  },
  create(action) {
    return freeze({
      kind: "OrActionNode",
      action
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/insert-query-builder.js
var InsertQueryBuilder = class _InsertQueryBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  /**
   * Sets the values to insert for an {@link Kysely.insertInto | insert} query.
   *
   * This method takes an object whose keys are column names and values are
   * values to insert. In addition to the column's type, the values can be
   * raw {@link sql} snippets or select queries.
   *
   * You must provide all fields you haven't explicitly marked as nullable
   * or optional using {@link Generated} or {@link ColumnType}.
   *
   * The return value of an `insert` query is an instance of {@link InsertResult}. The
   * {@link InsertResult.insertId | insertId} field holds the auto incremented primary
   * key if the database returned one.
   *
   * On PostgreSQL and some other dialects, you need to call `returning` to get
   * something out of the query.
   *
   * Also see the {@link expression} method for inserting the result of a select
   * query or any other expression.
   *
   * ### Examples
   *
   * <!-- siteExample("insert", "Single row", 10) -->
   *
   * Insert a single row:
   *
   * ```ts
   * const result = await db
   *   .insertInto('person')
   *   .values({
   *     first_name: 'Jennifer',
   *     last_name: 'Aniston',
   *     age: 40
   *   })
   *   .executeTakeFirst()
   *
   * // `insertId` is only available on dialects that
   * // automatically return the id of the inserted row
   * // such as MySQL and SQLite. On PostgreSQL, for example,
   * // you need to add a `returning` clause to the query to
   * // get anything out. See the "returning data" example.
   * console.log(result.insertId)
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * insert into `person` (`first_name`, `last_name`, `age`) values (?, ?, ?)
   * ```
   *
   * <!-- siteExample("insert", "Multiple rows", 20) -->
   *
   * On dialects that support it (for example PostgreSQL) you can insert multiple
   * rows by providing an array. Note that the return value is once again very
   * dialect-specific. Some databases may only return the id of the *last* inserted
   * row and some return nothing at all unless you call `returning`.
   *
   * ```ts
   * await db
   *   .insertInto('person')
   *   .values([{
   *     first_name: 'Jennifer',
   *     last_name: 'Aniston',
   *     age: 40,
   *   }, {
   *     first_name: 'Arnold',
   *     last_name: 'Schwarzenegger',
   *     age: 70,
   *   }])
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * insert into "person" ("first_name", "last_name", "age") values (($1, $2, $3), ($4, $5, $6))
   * ```
   *
   * <!-- siteExample("insert", "Returning data", 30) -->
   *
   * On supported dialects like PostgreSQL you need to chain `returning` to the query to get
   * the inserted row's columns (or any other expression) as the return value. `returning`
   * works just like `select`. Refer to `select` method's examples and documentation for
   * more info.
   *
   * ```ts
   * const result = await db
   *   .insertInto('person')
   *   .values({
   *     first_name: 'Jennifer',
   *     last_name: 'Aniston',
   *     age: 40,
   *   })
   *   .returning(['id', 'first_name as name'])
   *   .executeTakeFirstOrThrow()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * insert into "person" ("first_name", "last_name", "age") values ($1, $2, $3) returning "id", "first_name" as "name"
   * ```
   *
   * <!-- siteExample("insert", "Complex values", 40) -->
   *
   * In addition to primitives, the values can also be arbitrary expressions.
   * You can build the expressions by using a callback and calling the methods
   * on the expression builder passed to it:
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * const ani = "Ani"
   * const ston = "ston"
   *
   * const result = await db
   *   .insertInto('person')
   *   .values(({ ref, selectFrom, fn }) => ({
   *     first_name: 'Jennifer',
   *     last_name: sql<string>`concat(${ani}, ${ston})`,
   *     middle_name: ref('first_name'),
   *     age: selectFrom('person')
   *       .select(fn.avg<number>('age').as('avg_age')),
   *   }))
   *   .executeTakeFirst()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * insert into "person" (
   *   "first_name",
   *   "last_name",
   *   "middle_name",
   *   "age"
   * )
   * values (
   *   $1,
   *   concat($2, $3),
   *   "first_name",
   *   (select avg("age") as "avg_age" from "person")
   * )
   * ```
   *
   * You can also use the callback version of subqueries or raw expressions:
   *
   * ```ts
   * await db.with('jennifer', (db) => db
   *   .selectFrom('person')
   *   .where('first_name', '=', 'Jennifer')
   *   .select(['id', 'first_name', 'gender'])
   *   .limit(1)
   * ).insertInto('pet').values((eb) => ({
   *   owner_id: eb.selectFrom('jennifer').select('id'),
   *   name: eb.selectFrom('jennifer').select('first_name'),
   *   species: 'cat',
   * }))
   * .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * with "jennifer" as (
   *   select "id", "first_name", "gender"
   *   from "person"
   *   where "first_name" = $1
   *   limit $2
   * )
   * insert into "pet" ("owner_id", "name", "species")
   * values (
   *  (select "id" from "jennifer"),
   *  (select "first_name" from "jennifer"),
   *  $3
   * )
   * ```
   */
  values(insert) {
    const [columns, values] = parseInsertExpression(insert);
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {
        columns,
        values
      })
    });
  }
  /**
   * Sets the columns to insert.
   *
   * The {@link values} method sets both the columns and the values and this method
   * is not needed. But if you are using the {@link expression} method, you can use
   * this method to set the columns to insert.
   *
   * ### Examples
   *
   * ```ts
   * await db.insertInto('person')
   *   .columns(['first_name'])
   *   .expression((eb) => eb.selectFrom('pet').select('pet.name'))
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * insert into "person" ("first_name")
   * select "pet"."name" from "pet"
   * ```
   */
  columns(columns) {
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {
        columns: freeze(columns.map(ColumnNode.create))
      })
    });
  }
  /**
   * Insert an arbitrary expression. For example the result of a select query.
   *
   * ### Examples
   *
   * <!-- siteExample("insert", "Insert subquery", 50) -->
   *
   * You can create an `INSERT INTO SELECT FROM` query using the `expression` method.
   * This API doesn't follow our WYSIWYG principles and might be a bit difficult to
   * remember. The reasons for this design stem from implementation difficulties.
   *
   * ```ts
   * const result = await db.insertInto('person')
   *   .columns(['first_name', 'last_name', 'age'])
   *   .expression((eb) => eb
   *     .selectFrom('pet')
   *     .select((eb) => [
   *       'pet.name',
   *       eb.val('Petson').as('last_name'),
   *       eb.lit(7).as('age'),
   *     ])
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * insert into "person" ("first_name", "last_name", "age")
   * select "pet"."name", $1 as "last_name", 7 as "age from "pet"
   * ```
   */
  expression(expression) {
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {
        values: parseExpression(expression)
      })
    });
  }
  /**
   * Creates an `insert into "person" default values` query.
   *
   * ### Examples
   *
   * ```ts
   * await db.insertInto('person')
   *   .defaultValues()
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * insert into "person" default values
   * ```
   */
  defaultValues() {
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {
        defaultValues: true
      })
    });
  }
  /**
   * This can be used to add any additional SQL to the end of the query.
   *
   * ### Examples
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db.insertInto('person')
   *   .values({
   *     first_name: 'John',
   *     last_name: 'Doe',
   *     gender: 'male',
   *   })
   *   .modifyEnd(sql`-- This is a comment`)
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * insert into `person` ("first_name", "last_name", "gender")
   * values (?, ?, ?) -- This is a comment
   * ```
   */
  modifyEnd(modifier) {
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode())
    });
  }
  /**
   * Changes an `insert into` query to an `insert ignore into` query.
   *
   * This is only supported by some dialects like MySQL.
   *
   * To avoid a footgun, when invoked with the SQLite dialect, this method will
   * be handled like {@link orIgnore}. See also, {@link orAbort}, {@link orFail},
   * {@link orReplace}, and {@link orRollback}.
   *
   * If you use the ignore modifier, ignorable errors that occur while executing the
   * insert statement are ignored. For example, without ignore, a row that duplicates
   * an existing unique index or primary key value in the table causes a duplicate-key
   * error and the statement is aborted. With ignore, the row is discarded and no error
   * occurs.
   *
   * ### Examples
   *
   * ```ts
   * await db.insertInto('person')
   *   .ignore()
   *   .values({
   *     first_name: 'John',
   *     last_name: 'Doe',
   *     gender: 'female',
   *   })
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * insert ignore into `person` (`first_name`, `last_name`, `gender`) values (?, ?, ?)
   * ```
   *
   * The generated SQL (SQLite):
   *
   * ```sql
   * insert or ignore into "person" ("first_name", "last_name", "gender") values (?, ?, ?)
   * ```
   */
  ignore() {
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {
        orAction: OrActionNode.create("ignore")
      })
    });
  }
  /**
   * Changes an `insert into` query to an `insert or ignore into` query.
   *
   * This is only supported by some dialects like SQLite.
   *
   * To avoid a footgun, when invoked with the MySQL dialect, this method will
   * be handled like {@link ignore}.
   *
   * See also, {@link orAbort}, {@link orFail}, {@link orReplace}, and {@link orRollback}.
   *
   * ### Examples
   *
   * ```ts
   * await db.insertInto('person')
   *   .orIgnore()
   *   .values({
   *     first_name: 'John',
   *     last_name: 'Doe',
   *     gender: 'female',
   *   })
   *   .execute()
   * ```
   *
   * The generated SQL (SQLite):
   *
   * ```sql
   * insert or ignore into "person" ("first_name", "last_name", "gender") values (?, ?, ?)
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * insert ignore into `person` (`first_name`, `last_name`, `gender`) values (?, ?, ?)
   * ```
   */
  orIgnore() {
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {
        orAction: OrActionNode.create("ignore")
      })
    });
  }
  /**
   * Changes an `insert into` query to an `insert or abort into` query.
   *
   * This is only supported by some dialects like SQLite.
   *
   * See also, {@link orIgnore}, {@link orFail}, {@link orReplace}, and {@link orRollback}.
   *
   * ### Examples
   *
   * ```ts
   * await db.insertInto('person')
   *   .orAbort()
   *   .values({
   *     first_name: 'John',
   *     last_name: 'Doe',
   *     gender: 'female',
   *   })
   *   .execute()
   * ```
   *
   * The generated SQL (SQLite):
   *
   * ```sql
   * insert or abort into "person" ("first_name", "last_name", "gender") values (?, ?, ?)
   * ```
   */
  orAbort() {
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {
        orAction: OrActionNode.create("abort")
      })
    });
  }
  /**
   * Changes an `insert into` query to an `insert or fail into` query.
   *
   * This is only supported by some dialects like SQLite.
   *
   * See also, {@link orIgnore}, {@link orAbort}, {@link orReplace}, and {@link orRollback}.
   *
   * ### Examples
   *
   * ```ts
   * await db.insertInto('person')
   *   .orFail()
   *   .values({
   *     first_name: 'John',
   *     last_name: 'Doe',
   *     gender: 'female',
   *   })
   *   .execute()
   * ```
   *
   * The generated SQL (SQLite):
   *
   * ```sql
   * insert or fail into "person" ("first_name", "last_name", "gender") values (?, ?, ?)
   * ```
   */
  orFail() {
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {
        orAction: OrActionNode.create("fail")
      })
    });
  }
  /**
   * Changes an `insert into` query to an `insert or replace into` query.
   *
   * This is only supported by some dialects like SQLite.
   *
   * You can also use {@link Kysely.replaceInto} to achieve the same result.
   *
   * See also, {@link orIgnore}, {@link orAbort}, {@link orFail}, and {@link orRollback}.
   *
   * ### Examples
   *
   * ```ts
   * await db.insertInto('person')
   *   .orReplace()
   *   .values({
   *     first_name: 'John',
   *     last_name: 'Doe',
   *     gender: 'female',
   *   })
   *   .execute()
   * ```
   *
   * The generated SQL (SQLite):
   *
   * ```sql
   * insert or replace into "person" ("first_name", "last_name", "gender") values (?, ?, ?)
   * ```
   */
  orReplace() {
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {
        orAction: OrActionNode.create("replace")
      })
    });
  }
  /**
   * Changes an `insert into` query to an `insert or rollback into` query.
   *
   * This is only supported by some dialects like SQLite.
   *
   * See also, {@link orIgnore}, {@link orAbort}, {@link orFail}, and {@link orReplace}.
   *
   * ### Examples
   *
   * ```ts
   * await db.insertInto('person')
   *   .orRollback()
   *   .values({
   *     first_name: 'John',
   *     last_name: 'Doe',
   *     gender: 'female',
   *   })
   *   .execute()
   * ```
   *
   * The generated SQL (SQLite):
   *
   * ```sql
   * insert or rollback into "person" ("first_name", "last_name", "gender") values (?, ?, ?)
   * ```
   */
  orRollback() {
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {
        orAction: OrActionNode.create("rollback")
      })
    });
  }
  /**
   * Changes an `insert into` query to an `insert top into` query.
   *
   * `top` clause is only supported by some dialects like MS SQL Server.
   *
   * ### Examples
   *
   * Insert the first 5 rows:
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db.insertInto('person')
   *   .top(5)
   *   .columns(['first_name', 'gender'])
   *   .expression(
   *     (eb) => eb.selectFrom('pet').select(['name', sql.lit('other').as('gender')])
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (MS SQL Server):
   *
   * ```sql
   * insert top(5) into "person" ("first_name", "gender") select "name", 'other' as "gender" from "pet"
   * ```
   *
   * Insert the first 50 percent of rows:
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db.insertInto('person')
   *   .top(50, 'percent')
   *   .columns(['first_name', 'gender'])
   *   .expression(
   *     (eb) => eb.selectFrom('pet').select(['name', sql.lit('other').as('gender')])
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (MS SQL Server):
   *
   * ```sql
   * insert top(50) percent into "person" ("first_name", "gender") select "name", 'other' as "gender" from "pet"
   * ```
   */
  top(expression, modifiers) {
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers))
    });
  }
  /**
   * Adds an `on conflict` clause to the query.
   *
   * `on conflict` is only supported by some dialects like PostgreSQL and SQLite. On MySQL
   * you can use {@link ignore} and {@link onDuplicateKeyUpdate} to achieve similar results.
   *
   * ### Examples
   *
   * ```ts
   * await db
   *   .insertInto('pet')
   *   .values({
   *     name: 'Catto',
   *     species: 'cat',
   *     owner_id: 3,
   *   })
   *   .onConflict((oc) => oc
   *     .column('name')
   *     .doUpdateSet({ species: 'hamster' })
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * insert into "pet" ("name", "species", "owner_id")
   * values ($1, $2, $3)
   * on conflict ("name")
   * do update set "species" = $4
   * ```
   *
   * You can provide the name of the constraint instead of a column name:
   *
   * ```ts
   * await db
   *   .insertInto('pet')
   *   .values({
   *     name: 'Catto',
   *     species: 'cat',
   *     owner_id: 3,
   *   })
   *   .onConflict((oc) => oc
   *     .constraint('pet_name_key')
   *     .doUpdateSet({ species: 'hamster' })
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * insert into "pet" ("name", "species", "owner_id")
   * values ($1, $2, $3)
   * on conflict on constraint "pet_name_key"
   * do update set "species" = $4
   * ```
   *
   * You can also specify an expression as the conflict target in case
   * the unique index is an expression index:
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db
   *   .insertInto('pet')
   *   .values({
   *     name: 'Catto',
   *     species: 'cat',
   *     owner_id: 3,
   *   })
   *   .onConflict((oc) => oc
   *     .expression(sql<string>`lower(name)`)
   *     .doUpdateSet({ species: 'hamster' })
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * insert into "pet" ("name", "species", "owner_id")
   * values ($1, $2, $3)
   * on conflict (lower(name))
   * do update set "species" = $4
   * ```
   *
   * You can add a filter for the update statement like this:
   *
   * ```ts
   * await db
   *   .insertInto('pet')
   *   .values({
   *     name: 'Catto',
   *     species: 'cat',
   *     owner_id: 3,
   *   })
   *   .onConflict((oc) => oc
   *     .column('name')
   *     .doUpdateSet({ species: 'hamster' })
   *     .where('excluded.name', '!=', 'Catto')
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * insert into "pet" ("name", "species", "owner_id")
   * values ($1, $2, $3)
   * on conflict ("name")
   * do update set "species" = $4
   * where "excluded"."name" != $5
   * ```
   *
   * You can create an `on conflict do nothing` clauses like this:
   *
   * ```ts
   * await db
   *   .insertInto('pet')
   *   .values({
   *     name: 'Catto',
   *     species: 'cat',
   *     owner_id: 3,
   *   })
   *   .onConflict((oc) => oc
   *     .column('name')
   *     .doNothing()
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * insert into "pet" ("name", "species", "owner_id")
   * values ($1, $2, $3)
   * on conflict ("name") do nothing
   * ```
   *
   * You can refer to the columns of the virtual `excluded` table
   * in a type-safe way using a callback and the `ref` method of
   * `ExpressionBuilder`:
   *
   * ```ts
   * await db.insertInto('person')
   *   .values({
   *     id: 1,
   *     first_name: 'John',
   *     last_name: 'Doe',
   *     gender: 'male',
   *   })
   *   .onConflict(oc => oc
   *     .column('id')
   *     .doUpdateSet({
   *       first_name: (eb) => eb.ref('excluded.first_name'),
   *       last_name: (eb) => eb.ref('excluded.last_name')
   *     })
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * insert into "person" ("id", "first_name", "last_name", "gender")
   * values ($1, $2, $3, $4)
   * on conflict ("id")
   * do update set
   *  "first_name" = "excluded"."first_name",
   *  "last_name" = "excluded"."last_name"
   * ```
   */
  onConflict(callback) {
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {
        onConflict: callback(new OnConflictBuilder({
          onConflictNode: OnConflictNode.create()
        })).toOperationNode()
      })
    });
  }
  /**
   * Adds `on duplicate key update` to the query.
   *
   * If you specify `on duplicate key update`, and a row is inserted that would cause
   * a duplicate value in a unique index or primary key, an update of the old row occurs.
   *
   * This is only implemented by some dialects like MySQL. On most dialects you should
   * use {@link onConflict} instead.
   *
   * ### Examples
   *
   * ```ts
   * await db
   *   .insertInto('person')
   *   .values({
   *     id: 1,
   *     first_name: 'John',
   *     last_name: 'Doe',
   *     gender: 'male',
   *   })
   *   .onDuplicateKeyUpdate({ updated_at: new Date().toISOString() })
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * insert into `person` (`id`, `first_name`, `last_name`, `gender`)
   * values (?, ?, ?, ?)
   * on duplicate key update `updated_at` = ?
   * ```
   */
  onDuplicateKeyUpdate(update) {
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {
        onDuplicateKey: OnDuplicateKeyNode.create(parseUpdateObjectExpression(update))
      })
    });
  }
  returning(selection) {
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(selection))
    });
  }
  returningAll() {
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll())
    });
  }
  output(args) {
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args))
    });
  }
  outputAll(table) {
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table))
    });
  }
  /**
   * Clears all `returning` clauses from the query.
   *
   * ### Examples
   *
   * ```ts
   * await db.insertInto('person')
   *   .values({ first_name: 'James', last_name: 'Smith', gender: 'male' })
   *   .returning(['first_name'])
   *   .clearReturning()
   *   .execute()
   * ```
   *
   * The generated SQL(PostgreSQL):
   *
   * ```sql
   * insert into "person" ("first_name", "last_name", "gender") values ($1, $2, $3)
   * ```
   */
  clearReturning() {
    return new _InsertQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithoutReturning(this.#props.queryNode)
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   *
   * If you want to conditionally call a method on `this`, see
   * the {@link $if} method.
   *
   * ### Examples
   *
   * The next example uses a helper function `log` to log a query:
   *
   * ```ts
   * import type { Compilable } from 'kysely'
   *
   * function log<T extends Compilable>(qb: T): T {
   *   console.log(qb.compile())
   *   return qb
   * }
   *
   * await db.insertInto('person')
   *   .values({ first_name: 'John', last_name: 'Doe', gender: 'male' })
   *   .$call(log)
   *   .execute()
   * ```
   */
  $call(func) {
    return func(this);
  }
  /**
   * Call `func(this)` if `condition` is true.
   *
   * This method is especially handy with optional selects. Any `returning` or `returningAll`
   * method calls add columns as optional fields to the output type when called inside
   * the `func` callback. This is because we can't know if those selections were actually
   * made before running the code.
   *
   * You can also call any other methods inside the callback.
   *
   * ### Examples
   *
   * ```ts
   * import type { NewPerson } from 'type-editor' // imaginary module
   *
   * async function insertPerson(values: NewPerson, returnLastName: boolean) {
   *   return await db
   *     .insertInto('person')
   *     .values(values)
   *     .returning(['id', 'first_name'])
   *     .$if(returnLastName, (qb) => qb.returning('last_name'))
   *     .executeTakeFirstOrThrow()
   * }
   * ```
   *
   * Any selections added inside the `if` callback will be added as optional fields to the
   * output type since we can't know if the selections were actually made before running
   * the code. In the example above the return type of the `insertPerson` function is:
   *
   * ```ts
   * Promise<{
   *   id: number
   *   first_name: string
   *   last_name?: string
   * }>
   * ```
   */
  $if(condition, func) {
    if (condition) {
      return func(this);
    }
    return new _InsertQueryBuilder({
      ...this.#props
    });
  }
  /**
   * Change the output type of the query.
   *
   * This method call doesn't change the SQL in any way. This methods simply
   * returns a copy of this `InsertQueryBuilder` with a new output type.
   */
  $castTo() {
    return new _InsertQueryBuilder(this.#props);
  }
  /**
   * Narrows (parts of) the output type of the query.
   *
   * Kysely tries to be as type-safe as possible, but in some cases we have to make
   * compromises for better maintainability and compilation performance. At present,
   * Kysely doesn't narrow the output type of the query based on {@link values} input
   * when using {@link returning} or {@link returningAll}.
   *
   * This utility method is very useful for these situations, as it removes unncessary
   * runtime assertion/guard code. Its input type is limited to the output type
   * of the query, so you can't add a column that doesn't exist, or change a column's
   * type to something that doesn't exist in its union type.
   *
   * ### Examples
   *
   * Turn this code:
   *
   * ```ts
   * import type { Person } from 'type-editor' // imaginary module
   *
   * const person = await db.insertInto('person')
   *   .values({
   *     first_name: 'John',
   *     last_name: 'Doe',
   *     gender: 'male',
   *     nullable_column: 'hell yeah!'
   *   })
   *   .returningAll()
   *   .executeTakeFirstOrThrow()
   *
   * if (isWithNoNullValue(person)) {
   *   functionThatExpectsPersonWithNonNullValue(person)
   * }
   *
   * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } {
   *   return person.nullable_column != null
   * }
   * ```
   *
   * Into this:
   *
   * ```ts
   * import type { NotNull } from 'kysely'
   *
   * const person = await db.insertInto('person')
   *   .values({
   *     first_name: 'John',
   *     last_name: 'Doe',
   *     gender: 'male',
   *     nullable_column: 'hell yeah!'
   *   })
   *   .returningAll()
   *   .$narrowType<{ nullable_column: NotNull }>()
   *   .executeTakeFirstOrThrow()
   *
   * functionThatExpectsPersonWithNonNullValue(person)
   * ```
   */
  $narrowType() {
    return new _InsertQueryBuilder(this.#props);
  }
  /**
   * Asserts that query's output row type equals the given type `T`.
   *
   * This method can be used to simplify excessively complex types to make TypeScript happy
   * and much faster.
   *
   * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much
   * for TypeScript and you get errors like this:
   *
   * ```
   * error TS2589: Type instantiation is excessively deep and possibly infinite.
   * ```
   *
   * In these case you can often use this method to help TypeScript a little bit. When you use this
   * method to assert the output type of a query, Kysely can drop the complex output type that
   * consists of multiple nested helper types and replace it with the simple asserted type.
   *
   * Using this method doesn't reduce type safety at all. You have to pass in a type that is
   * structurally equal to the current type.
   *
   * ### Examples
   *
   * ```ts
   * import type { NewPerson, NewPet, Species } from 'type-editor' // imaginary module
   *
   * async function insertPersonAndPet(person: NewPerson, pet: Omit<NewPet, 'owner_id'>) {
   *   return await db
   *     .with('new_person', (qb) => qb
   *       .insertInto('person')
   *       .values(person)
   *       .returning('id')
   *       .$assertType<{ id: number }>()
   *     )
   *     .with('new_pet', (qb) => qb
   *       .insertInto('pet')
   *       .values((eb) => ({
   *         owner_id: eb.selectFrom('new_person').select('id'),
   *         ...pet
   *       }))
   *       .returning(['name as pet_name', 'species'])
   *       .$assertType<{ pet_name: string, species: Species }>()
   *     )
   *     .selectFrom(['new_person', 'new_pet'])
   *     .selectAll()
   *     .executeTakeFirstOrThrow()
   * }
   * ```
   */
  $assertType() {
    return new _InsertQueryBuilder(this.#props);
  }
  /**
   * Returns a copy of this InsertQueryBuilder instance with the given plugin installed.
   */
  withPlugin(plugin2) {
    return new _InsertQueryBuilder({
      ...this.#props,
      executor: this.#props.executor.withPlugin(plugin2)
    });
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  /**
   * Executes the query and returns an array of rows.
   *
   * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods.
   */
  async execute() {
    const compiledQuery = this.compile();
    const result = await this.#props.executor.executeQuery(compiledQuery);
    const { adapter } = this.#props.executor;
    const query = compiledQuery.query;
    if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) {
      return result.rows;
    }
    return [
      new InsertResult(result.insertId, result.numAffectedRows ?? BigInt(0))
    ];
  }
  /**
   * Executes the query and returns the first result or undefined if
   * the query returned no result.
   */
  async executeTakeFirst() {
    const [result] = await this.execute();
    return result;
  }
  /**
   * Executes the query and returns the first result or throws if
   * the query returned no result.
   *
   * By default an instance of {@link NoResultError} is thrown, but you can
   * provide a custom error class, or callback as the only argument to throw a different
   * error.
   */
  async executeTakeFirstOrThrow(errorConstructor = NoResultError) {
    const result = await this.executeTakeFirst();
    if (result === void 0) {
      const error = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode());
      throw error;
    }
    return result;
  }
  async *stream(chunkSize = 100) {
    const compiledQuery = this.compile();
    const stream = this.#props.executor.stream(compiledQuery, chunkSize);
    for await (const item of stream) {
      yield* item.rows;
    }
  }
  async explain(format, options) {
    const builder = new _InsertQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options)
    });
    return await builder.execute();
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/delete-query-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/delete-result.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DeleteResult = class {
  numDeletedRows;
  constructor(numDeletedRows) {
    this.numDeletedRows = numDeletedRows;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/limit-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var LimitNode = freeze({
  is(node) {
    return node.kind === "LimitNode";
  },
  create(limit) {
    return freeze({
      kind: "LimitNode",
      limit
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/delete-query-builder.js
var DeleteQueryBuilder = class _DeleteQueryBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  where(...args) {
    return new _DeleteQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args))
    });
  }
  whereRef(lhs, op, rhs) {
    return new _DeleteQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs))
    });
  }
  clearWhere() {
    return new _DeleteQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode)
    });
  }
  /**
   * Changes a `delete from` query into a `delete top from` query.
   *
   * `top` clause is only supported by some dialects like MS SQL Server.
   *
   * ### Examples
   *
   * Delete the first 5 rows:
   *
   * ```ts
   * await db
   *   .deleteFrom('person')
   *   .top(5)
   *   .where('age', '>', 18)
   *   .executeTakeFirstOrThrow()
   * ```
   *
   * The generated SQL (MS SQL Server):
   *
   * ```sql
   * delete top(5) from "person" where "age" > @1
   * ```
   *
   * Delete the first 50% of rows:
   *
   * ```ts
   * await db
   *   .deleteFrom('person')
   *   .top(50, 'percent')
   *   .where('age', '>', 18)
   *   .executeTakeFirstOrThrow()
   * ```
   *
   * The generated SQL (MS SQL Server):
   *
   * ```sql
   * delete top(50) percent from "person" where "age" > @1
   * ```
   */
  top(expression, modifiers) {
    return new _DeleteQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers))
    });
  }
  using(tables) {
    return new _DeleteQueryBuilder({
      ...this.#props,
      queryNode: DeleteQueryNode.cloneWithUsing(this.#props.queryNode, parseTableExpressionOrList(tables))
    });
  }
  innerJoin(...args) {
    return this.#join("InnerJoin", args);
  }
  leftJoin(...args) {
    return this.#join("LeftJoin", args);
  }
  rightJoin(...args) {
    return this.#join("RightJoin", args);
  }
  fullJoin(...args) {
    return this.#join("FullJoin", args);
  }
  #join(joinType, args) {
    return new _DeleteQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args))
    });
  }
  returning(selection) {
    return new _DeleteQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(selection))
    });
  }
  returningAll(table) {
    return new _DeleteQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table))
    });
  }
  output(args) {
    return new _DeleteQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args))
    });
  }
  outputAll(table) {
    return new _DeleteQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table))
    });
  }
  /**
   * Clears all `returning` clauses from the query.
   *
   * ### Examples
   *
   * ```ts
   * await db.deleteFrom('pet')
   *   .returningAll()
   *   .where('name', '=', 'Max')
   *   .clearReturning()
   *   .execute()
   * ```
   *
   * The generated SQL(PostgreSQL):
   *
   * ```sql
   * delete from "pet" where "name" = "Max"
   * ```
   */
  clearReturning() {
    return new _DeleteQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithoutReturning(this.#props.queryNode)
    });
  }
  /**
   * Clears the `limit` clause from the query.
   *
   * ### Examples
   *
   * ```ts
   * await db.deleteFrom('pet')
   *   .returningAll()
   *   .where('name', '=', 'Max')
   *   .limit(5)
   *   .clearLimit()
   *   .execute()
   * ```
   *
   * The generated SQL(PostgreSQL):
   *
   * ```sql
   * delete from "pet" where "name" = "Max" returning *
   * ```
   */
  clearLimit() {
    return new _DeleteQueryBuilder({
      ...this.#props,
      queryNode: DeleteQueryNode.cloneWithoutLimit(this.#props.queryNode)
    });
  }
  orderBy(...args) {
    return new _DeleteQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args))
    });
  }
  clearOrderBy() {
    return new _DeleteQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode)
    });
  }
  /**
   * Adds a limit clause to the query.
   *
   * A limit clause in a delete query is only supported by some dialects
   * like MySQL.
   *
   * ### Examples
   *
   * Delete 5 oldest items in a table:
   *
   * ```ts
   * await db
   *   .deleteFrom('pet')
   *   .orderBy('created_at')
   *   .limit(5)
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * delete from `pet` order by `created_at` limit ?
   * ```
   */
  limit(limit) {
    return new _DeleteQueryBuilder({
      ...this.#props,
      queryNode: DeleteQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit)))
    });
  }
  /**
   * This can be used to add any additional SQL to the end of the query.
   *
   * ### Examples
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db.deleteFrom('person')
   *   .where('first_name', '=', 'John')
   *   .modifyEnd(sql`-- This is a comment`)
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * delete from `person`
   * where `first_name` = "John" -- This is a comment
   * ```
   */
  modifyEnd(modifier) {
    return new _DeleteQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode())
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   *
   * If you want to conditionally call a method on `this`, see
   * the {@link $if} method.
   *
   * ### Examples
   *
   * The next example uses a helper function `log` to log a query:
   *
   * ```ts
   * import type { Compilable } from 'kysely'
   *
   * function log<T extends Compilable>(qb: T): T {
   *   console.log(qb.compile())
   *   return qb
   * }
   *
   * await db.deleteFrom('person')
   *   .$call(log)
   *   .execute()
   * ```
   */
  $call(func) {
    return func(this);
  }
  /**
   * Call `func(this)` if `condition` is true.
   *
   * This method is especially handy with optional selects. Any `returning` or `returningAll`
   * method calls add columns as optional fields to the output type when called inside
   * the `func` callback. This is because we can't know if those selections were actually
   * made before running the code.
   *
   * You can also call any other methods inside the callback.
   *
   * ### Examples
   *
   * ```ts
   * async function deletePerson(id: number, returnLastName: boolean) {
   *   return await db
   *     .deleteFrom('person')
   *     .where('id', '=', id)
   *     .returning(['id', 'first_name'])
   *     .$if(returnLastName, (qb) => qb.returning('last_name'))
   *     .executeTakeFirstOrThrow()
   * }
   * ```
   *
   * Any selections added inside the `if` callback will be added as optional fields to the
   * output type since we can't know if the selections were actually made before running
   * the code. In the example above the return type of the `deletePerson` function is:
   *
   * ```ts
   * Promise<{
   *   id: number
   *   first_name: string
   *   last_name?: string
   * }>
   * ```
   */
  $if(condition, func) {
    if (condition) {
      return func(this);
    }
    return new _DeleteQueryBuilder({
      ...this.#props
    });
  }
  /**
   * Change the output type of the query.
   *
   * This method call doesn't change the SQL in any way. This methods simply
   * returns a copy of this `DeleteQueryBuilder` with a new output type.
   */
  $castTo() {
    return new _DeleteQueryBuilder(this.#props);
  }
  /**
   * Narrows (parts of) the output type of the query.
   *
   * Kysely tries to be as type-safe as possible, but in some cases we have to make
   * compromises for better maintainability and compilation performance. At present,
   * Kysely doesn't narrow the output type of the query when using {@link where} and {@link returning} or {@link returningAll}.
   *
   * This utility method is very useful for these situations, as it removes unncessary
   * runtime assertion/guard code. Its input type is limited to the output type
   * of the query, so you can't add a column that doesn't exist, or change a column's
   * type to something that doesn't exist in its union type.
   *
   * ### Examples
   *
   * Turn this code:
   *
   * ```ts
   * import type { Person } from 'type-editor' // imaginary module
   *
   * const person = await db.deleteFrom('person')
   *   .where('id', '=', 3)
   *   .where('nullable_column', 'is not', null)
   *   .returningAll()
   *   .executeTakeFirstOrThrow()
   *
   * if (isWithNoNullValue(person)) {
   *   functionThatExpectsPersonWithNonNullValue(person)
   * }
   *
   * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } {
   *   return person.nullable_column != null
   * }
   * ```
   *
   * Into this:
   *
   * ```ts
   * import type { NotNull } from 'kysely'
   *
   * const person = await db.deleteFrom('person')
   *   .where('id', '=', 3)
   *   .where('nullable_column', 'is not', null)
   *   .returningAll()
   *   .$narrowType<{ nullable_column: NotNull }>()
   *   .executeTakeFirstOrThrow()
   *
   * functionThatExpectsPersonWithNonNullValue(person)
   * ```
   */
  $narrowType() {
    return new _DeleteQueryBuilder(this.#props);
  }
  /**
   * Asserts that query's output row type equals the given type `T`.
   *
   * This method can be used to simplify excessively complex types to make TypeScript happy
   * and much faster.
   *
   * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much
   * for TypeScript and you get errors like this:
   *
   * ```
   * error TS2589: Type instantiation is excessively deep and possibly infinite.
   * ```
   *
   * In these case you can often use this method to help TypeScript a little bit. When you use this
   * method to assert the output type of a query, Kysely can drop the complex output type that
   * consists of multiple nested helper types and replace it with the simple asserted type.
   *
   * Using this method doesn't reduce type safety at all. You have to pass in a type that is
   * structurally equal to the current type.
   *
   * ### Examples
   *
   * ```ts
   * import type { Species } from 'type-editor' // imaginary module
   *
   * async function deletePersonAndPets(personId: number) {
   *   return await db
   *     .with('deleted_person', (qb) => qb
   *        .deleteFrom('person')
   *        .where('id', '=', personId)
   *        .returning('first_name')
   *        .$assertType<{ first_name: string }>()
   *     )
   *     .with('deleted_pets', (qb) => qb
   *       .deleteFrom('pet')
   *       .where('owner_id', '=', personId)
   *       .returning(['name as pet_name', 'species'])
   *       .$assertType<{ pet_name: string, species: Species }>()
   *     )
   *     .selectFrom(['deleted_person', 'deleted_pets'])
   *     .selectAll()
   *     .execute()
   * }
   * ```
   */
  $assertType() {
    return new _DeleteQueryBuilder(this.#props);
  }
  /**
   * Returns a copy of this DeleteQueryBuilder instance with the given plugin installed.
   */
  withPlugin(plugin2) {
    return new _DeleteQueryBuilder({
      ...this.#props,
      executor: this.#props.executor.withPlugin(plugin2)
    });
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  /**
   * Executes the query and returns an array of rows.
   *
   * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods.
   */
  async execute() {
    const compiledQuery = this.compile();
    const result = await this.#props.executor.executeQuery(compiledQuery);
    const { adapter } = this.#props.executor;
    const query = compiledQuery.query;
    if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) {
      return result.rows;
    }
    return [new DeleteResult(result.numAffectedRows ?? BigInt(0))];
  }
  /**
   * Executes the query and returns the first result or undefined if
   * the query returned no result.
   */
  async executeTakeFirst() {
    const [result] = await this.execute();
    return result;
  }
  /**
   * Executes the query and returns the first result or throws if
   * the query returned no result.
   *
   * By default an instance of {@link NoResultError} is thrown, but you can
   * provide a custom error class, or callback as the only argument to throw a different
   * error.
   */
  async executeTakeFirstOrThrow(errorConstructor = NoResultError) {
    const result = await this.executeTakeFirst();
    if (result === void 0) {
      const error = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode());
      throw error;
    }
    return result;
  }
  async *stream(chunkSize = 100) {
    const compiledQuery = this.compile();
    const stream = this.#props.executor.stream(compiledQuery, chunkSize);
    for await (const item of stream) {
      yield* item.rows;
    }
  }
  async explain(format, options) {
    const builder = new _DeleteQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options)
    });
    return await builder.execute();
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/update-query-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/update-result.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var UpdateResult = class {
  /**
   * The number of rows the update query updated (even if not changed).
   */
  numUpdatedRows;
  /**
   * The number of rows the update query changed.
   *
   * This is **optional** and only supported in dialects such as MySQL.
   * You would probably use {@link numUpdatedRows} in most cases.
   */
  numChangedRows;
  constructor(numUpdatedRows, numChangedRows) {
    this.numUpdatedRows = numUpdatedRows;
    this.numChangedRows = numChangedRows;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/update-query-builder.js
var UpdateQueryBuilder = class _UpdateQueryBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  where(...args) {
    return new _UpdateQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args))
    });
  }
  whereRef(lhs, op, rhs) {
    return new _UpdateQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs))
    });
  }
  clearWhere() {
    return new _UpdateQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode)
    });
  }
  /**
   * Changes an `update` query into a `update top` query.
   *
   * `top` clause is only supported by some dialects like MS SQL Server.
   *
   * ### Examples
   *
   * Update the first row:
   *
   * ```ts
   * await db.updateTable('person')
   *   .top(1)
   *   .set({ first_name: 'Foo' })
   *   .where('age', '>', 18)
   *   .executeTakeFirstOrThrow()
   * ```
   *
   * The generated SQL (MS SQL Server):
   *
   * ```sql
   * update top(1) "person" set "first_name" = @1 where "age" > @2
   * ```
   *
   * Update the 50% first rows:
   *
   * ```ts
   * await db.updateTable('person')
   *   .top(50, 'percent')
   *   .set({ first_name: 'Foo' })
   *   .where('age', '>', 18)
   *   .executeTakeFirstOrThrow()
   * ```
   *
   * The generated SQL (MS SQL Server):
   *
   * ```sql
   * update top(50) percent "person" set "first_name" = @1 where "age" > @2
   * ```
   */
  top(expression, modifiers) {
    return new _UpdateQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers))
    });
  }
  from(from) {
    return new _UpdateQueryBuilder({
      ...this.#props,
      queryNode: UpdateQueryNode.cloneWithFromItems(this.#props.queryNode, parseTableExpressionOrList(from))
    });
  }
  innerJoin(...args) {
    return this.#join("InnerJoin", args);
  }
  leftJoin(...args) {
    return this.#join("LeftJoin", args);
  }
  rightJoin(...args) {
    return this.#join("RightJoin", args);
  }
  fullJoin(...args) {
    return this.#join("FullJoin", args);
  }
  #join(joinType, args) {
    return new _UpdateQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args))
    });
  }
  orderBy(...args) {
    return new _UpdateQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args))
    });
  }
  clearOrderBy() {
    return new _UpdateQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode)
    });
  }
  /**
   * Adds a limit clause to the update query for supported databases, such as MySQL.
   *
   * ### Examples
   *
   * Update the first 2 rows in the 'person' table:
   *
   * ```ts
   * await db
   *   .updateTable('person')
   *   .set({ first_name: 'Foo' })
   *   .limit(2)
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * update `person` set `first_name` = ? limit ?
   * ```
   */
  limit(limit) {
    return new _UpdateQueryBuilder({
      ...this.#props,
      queryNode: UpdateQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit)))
    });
  }
  set(...args) {
    return new _UpdateQueryBuilder({
      ...this.#props,
      queryNode: UpdateQueryNode.cloneWithUpdates(this.#props.queryNode, parseUpdate(...args))
    });
  }
  returning(selection) {
    return new _UpdateQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(selection))
    });
  }
  returningAll(table) {
    return new _UpdateQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table))
    });
  }
  output(args) {
    return new _UpdateQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args))
    });
  }
  outputAll(table) {
    return new _UpdateQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table))
    });
  }
  /**
   * This can be used to add any additional SQL to the end of the query.
   *
   * ### Examples
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db.updateTable('person')
   *   .set({ age: 39 })
   *   .where('first_name', '=', 'John')
   *   .modifyEnd(sql.raw('-- This is a comment'))
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * update `person`
   * set `age` = 39
   * where `first_name` = "John" -- This is a comment
   * ```
   */
  modifyEnd(modifier) {
    return new _UpdateQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode())
    });
  }
  /**
   * Clears all `returning` clauses from the query.
   *
   * ### Examples
   *
   * ```ts
   * db.updateTable('person')
   *   .returningAll()
   *   .set({ age: 39 })
   *   .where('first_name', '=', 'John')
   *   .clearReturning()
   * ```
   *
   * The generated SQL(PostgreSQL):
   *
   * ```sql
   * update "person" set "age" = 39 where "first_name" = "John"
   * ```
   */
  clearReturning() {
    return new _UpdateQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithoutReturning(this.#props.queryNode)
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   *
   * If you want to conditionally call a method on `this`, see
   * the {@link $if} method.
   *
   * ### Examples
   *
   * The next example uses a helper function `log` to log a query:
   *
   * ```ts
   * import type { Compilable } from 'kysely'
   * import type { PersonUpdate } from 'type-editor' // imaginary module
   *
   * function log<T extends Compilable>(qb: T): T {
   *   console.log(qb.compile())
   *   return qb
   * }
   *
   * const values = {
   *   first_name: 'John',
   * } satisfies PersonUpdate
   *
   * db.updateTable('person')
   *   .set(values)
   *   .$call(log)
   *   .execute()
   * ```
   */
  $call(func) {
    return func(this);
  }
  /**
   * Call `func(this)` if `condition` is true.
   *
   * This method is especially handy with optional selects. Any `returning` or `returningAll`
   * method calls add columns as optional fields to the output type when called inside
   * the `func` callback. This is because we can't know if those selections were actually
   * made before running the code.
   *
   * You can also call any other methods inside the callback.
   *
   * ### Examples
   *
   * ```ts
   * import type { PersonUpdate } from 'type-editor' // imaginary module
   *
   * async function updatePerson(id: number, updates: PersonUpdate, returnLastName: boolean) {
   *   return await db
   *     .updateTable('person')
   *     .set(updates)
   *     .where('id', '=', id)
   *     .returning(['id', 'first_name'])
   *     .$if(returnLastName, (qb) => qb.returning('last_name'))
   *     .executeTakeFirstOrThrow()
   * }
   * ```
   *
   * Any selections added inside the `if` callback will be added as optional fields to the
   * output type since we can't know if the selections were actually made before running
   * the code. In the example above the return type of the `updatePerson` function is:
   *
   * ```ts
   * Promise<{
   *   id: number
   *   first_name: string
   *   last_name?: string
   * }>
   * ```
   */
  $if(condition, func) {
    if (condition) {
      return func(this);
    }
    return new _UpdateQueryBuilder({
      ...this.#props
    });
  }
  /**
   * Change the output type of the query.
   *
   * This method call doesn't change the SQL in any way. This methods simply
   * returns a copy of this `UpdateQueryBuilder` with a new output type.
   */
  $castTo() {
    return new _UpdateQueryBuilder(this.#props);
  }
  /**
   * Narrows (parts of) the output type of the query.
   *
   * Kysely tries to be as type-safe as possible, but in some cases we have to make
   * compromises for better maintainability and compilation performance. At present,
   * Kysely doesn't narrow the output type of the query based on {@link set} input
   * when using {@link where} and/or {@link returning} or {@link returningAll}.
   *
   * This utility method is very useful for these situations, as it removes unncessary
   * runtime assertion/guard code. Its input type is limited to the output type
   * of the query, so you can't add a column that doesn't exist, or change a column's
   * type to something that doesn't exist in its union type.
   *
   * ### Examples
   *
   * Turn this code:
   *
   * ```ts
   * import type { Person } from 'type-editor' // imaginary module
   *
   * const id = 1
   * const now = new Date().toISOString()
   *
   * const person = await db.updateTable('person')
   *   .set({ deleted_at: now })
   *   .where('id', '=', id)
   *   .where('nullable_column', 'is not', null)
   *   .returningAll()
   *   .executeTakeFirstOrThrow()
   *
   * if (isWithNoNullValue(person)) {
   *   functionThatExpectsPersonWithNonNullValue(person)
   * }
   *
   * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } {
   *   return person.nullable_column != null
   * }
   * ```
   *
   * Into this:
   *
   * ```ts
   * import type { NotNull } from 'kysely'
   *
   * const id = 1
   * const now = new Date().toISOString()
   *
   * const person = await db.updateTable('person')
   *   .set({ deleted_at: now })
   *   .where('id', '=', id)
   *   .where('nullable_column', 'is not', null)
   *   .returningAll()
   *   .$narrowType<{ deleted_at: Date; nullable_column: NotNull }>()
   *   .executeTakeFirstOrThrow()
   *
   * functionThatExpectsPersonWithNonNullValue(person)
   * ```
   */
  $narrowType() {
    return new _UpdateQueryBuilder(this.#props);
  }
  /**
   * Asserts that query's output row type equals the given type `T`.
   *
   * This method can be used to simplify excessively complex types to make TypeScript happy
   * and much faster.
   *
   * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much
   * for TypeScript and you get errors like this:
   *
   * ```
   * error TS2589: Type instantiation is excessively deep and possibly infinite.
   * ```
   *
   * In these case you can often use this method to help TypeScript a little bit. When you use this
   * method to assert the output type of a query, Kysely can drop the complex output type that
   * consists of multiple nested helper types and replace it with the simple asserted type.
   *
   * Using this method doesn't reduce type safety at all. You have to pass in a type that is
   * structurally equal to the current type.
   *
   * ### Examples
   *
   * ```ts
   * import type { PersonUpdate, PetUpdate, Species } from 'type-editor' // imaginary module
   *
   * const person = {
   *   id: 1,
   *   gender: 'other',
   * } satisfies PersonUpdate
   *
   * const pet = {
   *   name: 'Fluffy',
   * } satisfies PetUpdate
   *
   * const result = await db
   *   .with('updated_person', (qb) => qb
   *     .updateTable('person')
   *     .set(person)
   *     .where('id', '=', person.id)
   *     .returning('first_name')
   *     .$assertType<{ first_name: string }>()
   *   )
   *   .with('updated_pet', (qb) => qb
   *     .updateTable('pet')
   *     .set(pet)
   *     .where('owner_id', '=', person.id)
   *     .returning(['name as pet_name', 'species'])
   *     .$assertType<{ pet_name: string, species: Species }>()
   *   )
   *   .selectFrom(['updated_person', 'updated_pet'])
   *   .selectAll()
   *   .executeTakeFirstOrThrow()
   * ```
   */
  $assertType() {
    return new _UpdateQueryBuilder(this.#props);
  }
  /**
   * Returns a copy of this UpdateQueryBuilder instance with the given plugin installed.
   */
  withPlugin(plugin2) {
    return new _UpdateQueryBuilder({
      ...this.#props,
      executor: this.#props.executor.withPlugin(plugin2)
    });
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  /**
   * Executes the query and returns an array of rows.
   *
   * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods.
   */
  async execute() {
    const compiledQuery = this.compile();
    const result = await this.#props.executor.executeQuery(compiledQuery);
    const { adapter } = this.#props.executor;
    const query = compiledQuery.query;
    if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) {
      return result.rows;
    }
    return [
      new UpdateResult(result.numAffectedRows ?? BigInt(0), result.numChangedRows)
    ];
  }
  /**
   * Executes the query and returns the first result or undefined if
   * the query returned no result.
   */
  async executeTakeFirst() {
    const [result] = await this.execute();
    return result;
  }
  /**
   * Executes the query and returns the first result or throws if
   * the query returned no result.
   *
   * By default an instance of {@link NoResultError} is thrown, but you can
   * provide a custom error class, or callback as the only argument to throw a different
   * error.
   */
  async executeTakeFirstOrThrow(errorConstructor = NoResultError) {
    const result = await this.executeTakeFirst();
    if (result === void 0) {
      const error = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode());
      throw error;
    }
    return result;
  }
  async *stream(chunkSize = 100) {
    const compiledQuery = this.compile();
    const stream = this.#props.executor.stream(compiledQuery, chunkSize);
    for await (const item of stream) {
      yield* item.rows;
    }
  }
  async explain(format, options) {
    const builder = new _UpdateQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options)
    });
    return await builder.execute();
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/with-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/common-table-expression-name-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var CommonTableExpressionNameNode = freeze({
  is(node) {
    return node.kind === "CommonTableExpressionNameNode";
  },
  create(tableName, columnNames) {
    return freeze({
      kind: "CommonTableExpressionNameNode",
      table: TableNode.create(tableName),
      columns: columnNames ? freeze(columnNames.map(ColumnNode.create)) : void 0
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/cte-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/common-table-expression-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var CommonTableExpressionNode = freeze({
  is(node) {
    return node.kind === "CommonTableExpressionNode";
  },
  create(name, expression) {
    return freeze({
      kind: "CommonTableExpressionNode",
      name,
      expression
    });
  },
  cloneWith(node, props) {
    return freeze({
      ...node,
      ...props
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/cte-builder.js
var CTEBuilder = class _CTEBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  /**
   * Makes the common table expression materialized.
   */
  materialized() {
    return new _CTEBuilder({
      ...this.#props,
      node: CommonTableExpressionNode.cloneWith(this.#props.node, {
        materialized: true
      })
    });
  }
  /**
   * Makes the common table expression not materialized.
   */
  notMaterialized() {
    return new _CTEBuilder({
      ...this.#props,
      node: CommonTableExpressionNode.cloneWith(this.#props.node, {
        materialized: false
      })
    });
  }
  toOperationNode() {
    return this.#props.node;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/with-parser.js
function parseCommonTableExpression(nameOrBuilderCallback, expression) {
  const expressionNode = expression(createQueryCreator()).toOperationNode();
  if (isFunction(nameOrBuilderCallback)) {
    return nameOrBuilderCallback(cteBuilderFactory(expressionNode)).toOperationNode();
  }
  return CommonTableExpressionNode.create(parseCommonTableExpressionName(nameOrBuilderCallback), expressionNode);
}
function cteBuilderFactory(expressionNode) {
  return (name) => {
    return new CTEBuilder({
      node: CommonTableExpressionNode.create(parseCommonTableExpressionName(name), expressionNode)
    });
  };
}
function parseCommonTableExpressionName(name) {
  if (name.includes("(")) {
    const parts = name.split(/[\(\)]/);
    const table = parts[0];
    const columns = parts[1].split(",").map((it) => it.trim());
    return CommonTableExpressionNameNode.create(table, columns);
  } else {
    return CommonTableExpressionNameNode.create(name);
  }
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/with-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var WithNode = freeze({
  is(node) {
    return node.kind === "WithNode";
  },
  create(expression, params) {
    return freeze({
      kind: "WithNode",
      expressions: freeze([expression]),
      ...params
    });
  },
  cloneWithExpression(withNode, expression) {
    return freeze({
      ...withNode,
      expressions: freeze([...withNode.expressions, expression])
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/util/query-id.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/util/random-string.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var CHARS = [
  "A",
  "B",
  "C",
  "D",
  "E",
  "F",
  "G",
  "H",
  "I",
  "J",
  "K",
  "L",
  "M",
  "N",
  "O",
  "P",
  "Q",
  "R",
  "S",
  "T",
  "U",
  "V",
  "W",
  "X",
  "Y",
  "Z",
  "a",
  "b",
  "c",
  "d",
  "e",
  "f",
  "g",
  "h",
  "i",
  "j",
  "k",
  "l",
  "m",
  "n",
  "o",
  "p",
  "q",
  "r",
  "s",
  "t",
  "u",
  "v",
  "w",
  "x",
  "y",
  "z",
  "0",
  "1",
  "2",
  "3",
  "4",
  "5",
  "6",
  "7",
  "8",
  "9"
];
function randomString(length) {
  let chars = "";
  for (let i2 = 0; i2 < length; ++i2) {
    chars += randomChar();
  }
  return chars;
}
function randomChar() {
  return CHARS[~~(Math.random() * CHARS.length)];
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/util/query-id.js
function createQueryId() {
  return new LazyQueryId();
}
var LazyQueryId = class {
  #queryId;
  get queryId() {
    if (this.#queryId === void 0) {
      this.#queryId = randomString(8);
    }
    return this.#queryId;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-plugin.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-transformer.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/operation-node-transformer.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/util/require-all-props.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function requireAllProps(obj) {
  return obj;
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/operation-node-transformer.js
var OperationNodeTransformer = class {
  nodeStack = [];
  #transformers = freeze({
    AliasNode: this.transformAlias.bind(this),
    ColumnNode: this.transformColumn.bind(this),
    IdentifierNode: this.transformIdentifier.bind(this),
    SchemableIdentifierNode: this.transformSchemableIdentifier.bind(this),
    RawNode: this.transformRaw.bind(this),
    ReferenceNode: this.transformReference.bind(this),
    SelectQueryNode: this.transformSelectQuery.bind(this),
    SelectionNode: this.transformSelection.bind(this),
    TableNode: this.transformTable.bind(this),
    FromNode: this.transformFrom.bind(this),
    SelectAllNode: this.transformSelectAll.bind(this),
    AndNode: this.transformAnd.bind(this),
    OrNode: this.transformOr.bind(this),
    ValueNode: this.transformValue.bind(this),
    ValueListNode: this.transformValueList.bind(this),
    PrimitiveValueListNode: this.transformPrimitiveValueList.bind(this),
    ParensNode: this.transformParens.bind(this),
    JoinNode: this.transformJoin.bind(this),
    OperatorNode: this.transformOperator.bind(this),
    WhereNode: this.transformWhere.bind(this),
    InsertQueryNode: this.transformInsertQuery.bind(this),
    DeleteQueryNode: this.transformDeleteQuery.bind(this),
    ReturningNode: this.transformReturning.bind(this),
    CreateTableNode: this.transformCreateTable.bind(this),
    AddColumnNode: this.transformAddColumn.bind(this),
    ColumnDefinitionNode: this.transformColumnDefinition.bind(this),
    DropTableNode: this.transformDropTable.bind(this),
    DataTypeNode: this.transformDataType.bind(this),
    OrderByNode: this.transformOrderBy.bind(this),
    OrderByItemNode: this.transformOrderByItem.bind(this),
    GroupByNode: this.transformGroupBy.bind(this),
    GroupByItemNode: this.transformGroupByItem.bind(this),
    UpdateQueryNode: this.transformUpdateQuery.bind(this),
    ColumnUpdateNode: this.transformColumnUpdate.bind(this),
    LimitNode: this.transformLimit.bind(this),
    OffsetNode: this.transformOffset.bind(this),
    OnConflictNode: this.transformOnConflict.bind(this),
    OnDuplicateKeyNode: this.transformOnDuplicateKey.bind(this),
    CreateIndexNode: this.transformCreateIndex.bind(this),
    DropIndexNode: this.transformDropIndex.bind(this),
    ListNode: this.transformList.bind(this),
    PrimaryKeyConstraintNode: this.transformPrimaryKeyConstraint.bind(this),
    UniqueConstraintNode: this.transformUniqueConstraint.bind(this),
    ReferencesNode: this.transformReferences.bind(this),
    CheckConstraintNode: this.transformCheckConstraint.bind(this),
    WithNode: this.transformWith.bind(this),
    CommonTableExpressionNode: this.transformCommonTableExpression.bind(this),
    CommonTableExpressionNameNode: this.transformCommonTableExpressionName.bind(this),
    HavingNode: this.transformHaving.bind(this),
    CreateSchemaNode: this.transformCreateSchema.bind(this),
    DropSchemaNode: this.transformDropSchema.bind(this),
    AlterTableNode: this.transformAlterTable.bind(this),
    DropColumnNode: this.transformDropColumn.bind(this),
    RenameColumnNode: this.transformRenameColumn.bind(this),
    AlterColumnNode: this.transformAlterColumn.bind(this),
    ModifyColumnNode: this.transformModifyColumn.bind(this),
    AddConstraintNode: this.transformAddConstraint.bind(this),
    DropConstraintNode: this.transformDropConstraint.bind(this),
    RenameConstraintNode: this.transformRenameConstraint.bind(this),
    ForeignKeyConstraintNode: this.transformForeignKeyConstraint.bind(this),
    CreateViewNode: this.transformCreateView.bind(this),
    RefreshMaterializedViewNode: this.transformRefreshMaterializedView.bind(this),
    DropViewNode: this.transformDropView.bind(this),
    GeneratedNode: this.transformGenerated.bind(this),
    DefaultValueNode: this.transformDefaultValue.bind(this),
    OnNode: this.transformOn.bind(this),
    ValuesNode: this.transformValues.bind(this),
    SelectModifierNode: this.transformSelectModifier.bind(this),
    CreateTypeNode: this.transformCreateType.bind(this),
    DropTypeNode: this.transformDropType.bind(this),
    ExplainNode: this.transformExplain.bind(this),
    DefaultInsertValueNode: this.transformDefaultInsertValue.bind(this),
    AggregateFunctionNode: this.transformAggregateFunction.bind(this),
    OverNode: this.transformOver.bind(this),
    PartitionByNode: this.transformPartitionBy.bind(this),
    PartitionByItemNode: this.transformPartitionByItem.bind(this),
    SetOperationNode: this.transformSetOperation.bind(this),
    BinaryOperationNode: this.transformBinaryOperation.bind(this),
    UnaryOperationNode: this.transformUnaryOperation.bind(this),
    UsingNode: this.transformUsing.bind(this),
    FunctionNode: this.transformFunction.bind(this),
    CaseNode: this.transformCase.bind(this),
    WhenNode: this.transformWhen.bind(this),
    JSONReferenceNode: this.transformJSONReference.bind(this),
    JSONPathNode: this.transformJSONPath.bind(this),
    JSONPathLegNode: this.transformJSONPathLeg.bind(this),
    JSONOperatorChainNode: this.transformJSONOperatorChain.bind(this),
    TupleNode: this.transformTuple.bind(this),
    MergeQueryNode: this.transformMergeQuery.bind(this),
    MatchedNode: this.transformMatched.bind(this),
    AddIndexNode: this.transformAddIndex.bind(this),
    CastNode: this.transformCast.bind(this),
    FetchNode: this.transformFetch.bind(this),
    TopNode: this.transformTop.bind(this),
    OutputNode: this.transformOutput.bind(this),
    OrActionNode: this.transformOrAction.bind(this),
    CollateNode: this.transformCollate.bind(this)
  });
  transformNode(node, queryId) {
    if (!node) {
      return node;
    }
    this.nodeStack.push(node);
    const out = this.transformNodeImpl(node, queryId);
    this.nodeStack.pop();
    return freeze(out);
  }
  transformNodeImpl(node, queryId) {
    return this.#transformers[node.kind](node, queryId);
  }
  transformNodeList(list, queryId) {
    if (!list) {
      return list;
    }
    return freeze(list.map((node) => this.transformNode(node, queryId)));
  }
  transformSelectQuery(node, queryId) {
    return requireAllProps({
      kind: "SelectQueryNode",
      from: this.transformNode(node.from, queryId),
      selections: this.transformNodeList(node.selections, queryId),
      distinctOn: this.transformNodeList(node.distinctOn, queryId),
      joins: this.transformNodeList(node.joins, queryId),
      groupBy: this.transformNode(node.groupBy, queryId),
      orderBy: this.transformNode(node.orderBy, queryId),
      where: this.transformNode(node.where, queryId),
      frontModifiers: this.transformNodeList(node.frontModifiers, queryId),
      endModifiers: this.transformNodeList(node.endModifiers, queryId),
      limit: this.transformNode(node.limit, queryId),
      offset: this.transformNode(node.offset, queryId),
      with: this.transformNode(node.with, queryId),
      having: this.transformNode(node.having, queryId),
      explain: this.transformNode(node.explain, queryId),
      setOperations: this.transformNodeList(node.setOperations, queryId),
      fetch: this.transformNode(node.fetch, queryId),
      top: this.transformNode(node.top, queryId)
    });
  }
  transformSelection(node, queryId) {
    return requireAllProps({
      kind: "SelectionNode",
      selection: this.transformNode(node.selection, queryId)
    });
  }
  transformColumn(node, queryId) {
    return requireAllProps({
      kind: "ColumnNode",
      column: this.transformNode(node.column, queryId)
    });
  }
  transformAlias(node, queryId) {
    return requireAllProps({
      kind: "AliasNode",
      node: this.transformNode(node.node, queryId),
      alias: this.transformNode(node.alias, queryId)
    });
  }
  transformTable(node, queryId) {
    return requireAllProps({
      kind: "TableNode",
      table: this.transformNode(node.table, queryId)
    });
  }
  transformFrom(node, queryId) {
    return requireAllProps({
      kind: "FromNode",
      froms: this.transformNodeList(node.froms, queryId)
    });
  }
  transformReference(node, queryId) {
    return requireAllProps({
      kind: "ReferenceNode",
      column: this.transformNode(node.column, queryId),
      table: this.transformNode(node.table, queryId)
    });
  }
  transformAnd(node, queryId) {
    return requireAllProps({
      kind: "AndNode",
      left: this.transformNode(node.left, queryId),
      right: this.transformNode(node.right, queryId)
    });
  }
  transformOr(node, queryId) {
    return requireAllProps({
      kind: "OrNode",
      left: this.transformNode(node.left, queryId),
      right: this.transformNode(node.right, queryId)
    });
  }
  transformValueList(node, queryId) {
    return requireAllProps({
      kind: "ValueListNode",
      values: this.transformNodeList(node.values, queryId)
    });
  }
  transformParens(node, queryId) {
    return requireAllProps({
      kind: "ParensNode",
      node: this.transformNode(node.node, queryId)
    });
  }
  transformJoin(node, queryId) {
    return requireAllProps({
      kind: "JoinNode",
      joinType: node.joinType,
      table: this.transformNode(node.table, queryId),
      on: this.transformNode(node.on, queryId)
    });
  }
  transformRaw(node, queryId) {
    return requireAllProps({
      kind: "RawNode",
      sqlFragments: freeze([...node.sqlFragments]),
      parameters: this.transformNodeList(node.parameters, queryId)
    });
  }
  transformWhere(node, queryId) {
    return requireAllProps({
      kind: "WhereNode",
      where: this.transformNode(node.where, queryId)
    });
  }
  transformInsertQuery(node, queryId) {
    return requireAllProps({
      kind: "InsertQueryNode",
      into: this.transformNode(node.into, queryId),
      columns: this.transformNodeList(node.columns, queryId),
      values: this.transformNode(node.values, queryId),
      returning: this.transformNode(node.returning, queryId),
      onConflict: this.transformNode(node.onConflict, queryId),
      onDuplicateKey: this.transformNode(node.onDuplicateKey, queryId),
      endModifiers: this.transformNodeList(node.endModifiers, queryId),
      with: this.transformNode(node.with, queryId),
      ignore: node.ignore,
      orAction: this.transformNode(node.orAction, queryId),
      replace: node.replace,
      explain: this.transformNode(node.explain, queryId),
      defaultValues: node.defaultValues,
      top: this.transformNode(node.top, queryId),
      output: this.transformNode(node.output, queryId)
    });
  }
  transformValues(node, queryId) {
    return requireAllProps({
      kind: "ValuesNode",
      values: this.transformNodeList(node.values, queryId)
    });
  }
  transformDeleteQuery(node, queryId) {
    return requireAllProps({
      kind: "DeleteQueryNode",
      from: this.transformNode(node.from, queryId),
      using: this.transformNode(node.using, queryId),
      joins: this.transformNodeList(node.joins, queryId),
      where: this.transformNode(node.where, queryId),
      returning: this.transformNode(node.returning, queryId),
      endModifiers: this.transformNodeList(node.endModifiers, queryId),
      with: this.transformNode(node.with, queryId),
      orderBy: this.transformNode(node.orderBy, queryId),
      limit: this.transformNode(node.limit, queryId),
      explain: this.transformNode(node.explain, queryId),
      top: this.transformNode(node.top, queryId),
      output: this.transformNode(node.output, queryId)
    });
  }
  transformReturning(node, queryId) {
    return requireAllProps({
      kind: "ReturningNode",
      selections: this.transformNodeList(node.selections, queryId)
    });
  }
  transformCreateTable(node, queryId) {
    return requireAllProps({
      kind: "CreateTableNode",
      table: this.transformNode(node.table, queryId),
      columns: this.transformNodeList(node.columns, queryId),
      constraints: this.transformNodeList(node.constraints, queryId),
      temporary: node.temporary,
      ifNotExists: node.ifNotExists,
      onCommit: node.onCommit,
      frontModifiers: this.transformNodeList(node.frontModifiers, queryId),
      endModifiers: this.transformNodeList(node.endModifiers, queryId),
      selectQuery: this.transformNode(node.selectQuery, queryId)
    });
  }
  transformColumnDefinition(node, queryId) {
    return requireAllProps({
      kind: "ColumnDefinitionNode",
      column: this.transformNode(node.column, queryId),
      dataType: this.transformNode(node.dataType, queryId),
      references: this.transformNode(node.references, queryId),
      primaryKey: node.primaryKey,
      autoIncrement: node.autoIncrement,
      unique: node.unique,
      notNull: node.notNull,
      unsigned: node.unsigned,
      defaultTo: this.transformNode(node.defaultTo, queryId),
      check: this.transformNode(node.check, queryId),
      generated: this.transformNode(node.generated, queryId),
      frontModifiers: this.transformNodeList(node.frontModifiers, queryId),
      endModifiers: this.transformNodeList(node.endModifiers, queryId),
      nullsNotDistinct: node.nullsNotDistinct,
      identity: node.identity,
      ifNotExists: node.ifNotExists
    });
  }
  transformAddColumn(node, queryId) {
    return requireAllProps({
      kind: "AddColumnNode",
      column: this.transformNode(node.column, queryId)
    });
  }
  transformDropTable(node, queryId) {
    return requireAllProps({
      kind: "DropTableNode",
      table: this.transformNode(node.table, queryId),
      ifExists: node.ifExists,
      cascade: node.cascade
    });
  }
  transformOrderBy(node, queryId) {
    return requireAllProps({
      kind: "OrderByNode",
      items: this.transformNodeList(node.items, queryId)
    });
  }
  transformOrderByItem(node, queryId) {
    return requireAllProps({
      kind: "OrderByItemNode",
      orderBy: this.transformNode(node.orderBy, queryId),
      direction: this.transformNode(node.direction, queryId),
      collation: this.transformNode(node.collation, queryId),
      nulls: node.nulls
    });
  }
  transformGroupBy(node, queryId) {
    return requireAllProps({
      kind: "GroupByNode",
      items: this.transformNodeList(node.items, queryId)
    });
  }
  transformGroupByItem(node, queryId) {
    return requireAllProps({
      kind: "GroupByItemNode",
      groupBy: this.transformNode(node.groupBy, queryId)
    });
  }
  transformUpdateQuery(node, queryId) {
    return requireAllProps({
      kind: "UpdateQueryNode",
      table: this.transformNode(node.table, queryId),
      from: this.transformNode(node.from, queryId),
      joins: this.transformNodeList(node.joins, queryId),
      where: this.transformNode(node.where, queryId),
      updates: this.transformNodeList(node.updates, queryId),
      returning: this.transformNode(node.returning, queryId),
      endModifiers: this.transformNodeList(node.endModifiers, queryId),
      with: this.transformNode(node.with, queryId),
      explain: this.transformNode(node.explain, queryId),
      limit: this.transformNode(node.limit, queryId),
      top: this.transformNode(node.top, queryId),
      output: this.transformNode(node.output, queryId),
      orderBy: this.transformNode(node.orderBy, queryId)
    });
  }
  transformColumnUpdate(node, queryId) {
    return requireAllProps({
      kind: "ColumnUpdateNode",
      column: this.transformNode(node.column, queryId),
      value: this.transformNode(node.value, queryId)
    });
  }
  transformLimit(node, queryId) {
    return requireAllProps({
      kind: "LimitNode",
      limit: this.transformNode(node.limit, queryId)
    });
  }
  transformOffset(node, queryId) {
    return requireAllProps({
      kind: "OffsetNode",
      offset: this.transformNode(node.offset, queryId)
    });
  }
  transformOnConflict(node, queryId) {
    return requireAllProps({
      kind: "OnConflictNode",
      columns: this.transformNodeList(node.columns, queryId),
      constraint: this.transformNode(node.constraint, queryId),
      indexExpression: this.transformNode(node.indexExpression, queryId),
      indexWhere: this.transformNode(node.indexWhere, queryId),
      updates: this.transformNodeList(node.updates, queryId),
      updateWhere: this.transformNode(node.updateWhere, queryId),
      doNothing: node.doNothing
    });
  }
  transformOnDuplicateKey(node, queryId) {
    return requireAllProps({
      kind: "OnDuplicateKeyNode",
      updates: this.transformNodeList(node.updates, queryId)
    });
  }
  transformCreateIndex(node, queryId) {
    return requireAllProps({
      kind: "CreateIndexNode",
      name: this.transformNode(node.name, queryId),
      table: this.transformNode(node.table, queryId),
      columns: this.transformNodeList(node.columns, queryId),
      unique: node.unique,
      using: this.transformNode(node.using, queryId),
      ifNotExists: node.ifNotExists,
      where: this.transformNode(node.where, queryId),
      nullsNotDistinct: node.nullsNotDistinct
    });
  }
  transformList(node, queryId) {
    return requireAllProps({
      kind: "ListNode",
      items: this.transformNodeList(node.items, queryId)
    });
  }
  transformDropIndex(node, queryId) {
    return requireAllProps({
      kind: "DropIndexNode",
      name: this.transformNode(node.name, queryId),
      table: this.transformNode(node.table, queryId),
      ifExists: node.ifExists,
      cascade: node.cascade
    });
  }
  transformPrimaryKeyConstraint(node, queryId) {
    return requireAllProps({
      kind: "PrimaryKeyConstraintNode",
      columns: this.transformNodeList(node.columns, queryId),
      name: this.transformNode(node.name, queryId),
      deferrable: node.deferrable,
      initiallyDeferred: node.initiallyDeferred
    });
  }
  transformUniqueConstraint(node, queryId) {
    return requireAllProps({
      kind: "UniqueConstraintNode",
      columns: this.transformNodeList(node.columns, queryId),
      name: this.transformNode(node.name, queryId),
      nullsNotDistinct: node.nullsNotDistinct,
      deferrable: node.deferrable,
      initiallyDeferred: node.initiallyDeferred
    });
  }
  transformForeignKeyConstraint(node, queryId) {
    return requireAllProps({
      kind: "ForeignKeyConstraintNode",
      columns: this.transformNodeList(node.columns, queryId),
      references: this.transformNode(node.references, queryId),
      name: this.transformNode(node.name, queryId),
      onDelete: node.onDelete,
      onUpdate: node.onUpdate,
      deferrable: node.deferrable,
      initiallyDeferred: node.initiallyDeferred
    });
  }
  transformSetOperation(node, queryId) {
    return requireAllProps({
      kind: "SetOperationNode",
      operator: node.operator,
      expression: this.transformNode(node.expression, queryId),
      all: node.all
    });
  }
  transformReferences(node, queryId) {
    return requireAllProps({
      kind: "ReferencesNode",
      table: this.transformNode(node.table, queryId),
      columns: this.transformNodeList(node.columns, queryId),
      onDelete: node.onDelete,
      onUpdate: node.onUpdate
    });
  }
  transformCheckConstraint(node, queryId) {
    return requireAllProps({
      kind: "CheckConstraintNode",
      expression: this.transformNode(node.expression, queryId),
      name: this.transformNode(node.name, queryId)
    });
  }
  transformWith(node, queryId) {
    return requireAllProps({
      kind: "WithNode",
      expressions: this.transformNodeList(node.expressions, queryId),
      recursive: node.recursive
    });
  }
  transformCommonTableExpression(node, queryId) {
    return requireAllProps({
      kind: "CommonTableExpressionNode",
      name: this.transformNode(node.name, queryId),
      materialized: node.materialized,
      expression: this.transformNode(node.expression, queryId)
    });
  }
  transformCommonTableExpressionName(node, queryId) {
    return requireAllProps({
      kind: "CommonTableExpressionNameNode",
      table: this.transformNode(node.table, queryId),
      columns: this.transformNodeList(node.columns, queryId)
    });
  }
  transformHaving(node, queryId) {
    return requireAllProps({
      kind: "HavingNode",
      having: this.transformNode(node.having, queryId)
    });
  }
  transformCreateSchema(node, queryId) {
    return requireAllProps({
      kind: "CreateSchemaNode",
      schema: this.transformNode(node.schema, queryId),
      ifNotExists: node.ifNotExists
    });
  }
  transformDropSchema(node, queryId) {
    return requireAllProps({
      kind: "DropSchemaNode",
      schema: this.transformNode(node.schema, queryId),
      ifExists: node.ifExists,
      cascade: node.cascade
    });
  }
  transformAlterTable(node, queryId) {
    return requireAllProps({
      kind: "AlterTableNode",
      table: this.transformNode(node.table, queryId),
      renameTo: this.transformNode(node.renameTo, queryId),
      setSchema: this.transformNode(node.setSchema, queryId),
      columnAlterations: this.transformNodeList(node.columnAlterations, queryId),
      addConstraint: this.transformNode(node.addConstraint, queryId),
      dropConstraint: this.transformNode(node.dropConstraint, queryId),
      renameConstraint: this.transformNode(node.renameConstraint, queryId),
      addIndex: this.transformNode(node.addIndex, queryId),
      dropIndex: this.transformNode(node.dropIndex, queryId)
    });
  }
  transformDropColumn(node, queryId) {
    return requireAllProps({
      kind: "DropColumnNode",
      column: this.transformNode(node.column, queryId)
    });
  }
  transformRenameColumn(node, queryId) {
    return requireAllProps({
      kind: "RenameColumnNode",
      column: this.transformNode(node.column, queryId),
      renameTo: this.transformNode(node.renameTo, queryId)
    });
  }
  transformAlterColumn(node, queryId) {
    return requireAllProps({
      kind: "AlterColumnNode",
      column: this.transformNode(node.column, queryId),
      dataType: this.transformNode(node.dataType, queryId),
      dataTypeExpression: this.transformNode(node.dataTypeExpression, queryId),
      setDefault: this.transformNode(node.setDefault, queryId),
      dropDefault: node.dropDefault,
      setNotNull: node.setNotNull,
      dropNotNull: node.dropNotNull
    });
  }
  transformModifyColumn(node, queryId) {
    return requireAllProps({
      kind: "ModifyColumnNode",
      column: this.transformNode(node.column, queryId)
    });
  }
  transformAddConstraint(node, queryId) {
    return requireAllProps({
      kind: "AddConstraintNode",
      constraint: this.transformNode(node.constraint, queryId)
    });
  }
  transformDropConstraint(node, queryId) {
    return requireAllProps({
      kind: "DropConstraintNode",
      constraintName: this.transformNode(node.constraintName, queryId),
      ifExists: node.ifExists,
      modifier: node.modifier
    });
  }
  transformRenameConstraint(node, queryId) {
    return requireAllProps({
      kind: "RenameConstraintNode",
      oldName: this.transformNode(node.oldName, queryId),
      newName: this.transformNode(node.newName, queryId)
    });
  }
  transformCreateView(node, queryId) {
    return requireAllProps({
      kind: "CreateViewNode",
      name: this.transformNode(node.name, queryId),
      temporary: node.temporary,
      orReplace: node.orReplace,
      ifNotExists: node.ifNotExists,
      materialized: node.materialized,
      columns: this.transformNodeList(node.columns, queryId),
      as: this.transformNode(node.as, queryId)
    });
  }
  transformRefreshMaterializedView(node, queryId) {
    return requireAllProps({
      kind: "RefreshMaterializedViewNode",
      name: this.transformNode(node.name, queryId),
      concurrently: node.concurrently,
      withNoData: node.withNoData
    });
  }
  transformDropView(node, queryId) {
    return requireAllProps({
      kind: "DropViewNode",
      name: this.transformNode(node.name, queryId),
      ifExists: node.ifExists,
      materialized: node.materialized,
      cascade: node.cascade
    });
  }
  transformGenerated(node, queryId) {
    return requireAllProps({
      kind: "GeneratedNode",
      byDefault: node.byDefault,
      always: node.always,
      identity: node.identity,
      stored: node.stored,
      expression: this.transformNode(node.expression, queryId)
    });
  }
  transformDefaultValue(node, queryId) {
    return requireAllProps({
      kind: "DefaultValueNode",
      defaultValue: this.transformNode(node.defaultValue, queryId)
    });
  }
  transformOn(node, queryId) {
    return requireAllProps({
      kind: "OnNode",
      on: this.transformNode(node.on, queryId)
    });
  }
  transformSelectModifier(node, queryId) {
    return requireAllProps({
      kind: "SelectModifierNode",
      modifier: node.modifier,
      rawModifier: this.transformNode(node.rawModifier, queryId),
      of: this.transformNodeList(node.of, queryId)
    });
  }
  transformCreateType(node, queryId) {
    return requireAllProps({
      kind: "CreateTypeNode",
      name: this.transformNode(node.name, queryId),
      enum: this.transformNode(node.enum, queryId)
    });
  }
  transformDropType(node, queryId) {
    return requireAllProps({
      kind: "DropTypeNode",
      name: this.transformNode(node.name, queryId),
      ifExists: node.ifExists
    });
  }
  transformExplain(node, queryId) {
    return requireAllProps({
      kind: "ExplainNode",
      format: node.format,
      options: this.transformNode(node.options, queryId)
    });
  }
  transformSchemableIdentifier(node, queryId) {
    return requireAllProps({
      kind: "SchemableIdentifierNode",
      schema: this.transformNode(node.schema, queryId),
      identifier: this.transformNode(node.identifier, queryId)
    });
  }
  transformAggregateFunction(node, queryId) {
    return requireAllProps({
      kind: "AggregateFunctionNode",
      func: node.func,
      aggregated: this.transformNodeList(node.aggregated, queryId),
      distinct: node.distinct,
      orderBy: this.transformNode(node.orderBy, queryId),
      withinGroup: this.transformNode(node.withinGroup, queryId),
      filter: this.transformNode(node.filter, queryId),
      over: this.transformNode(node.over, queryId)
    });
  }
  transformOver(node, queryId) {
    return requireAllProps({
      kind: "OverNode",
      orderBy: this.transformNode(node.orderBy, queryId),
      partitionBy: this.transformNode(node.partitionBy, queryId)
    });
  }
  transformPartitionBy(node, queryId) {
    return requireAllProps({
      kind: "PartitionByNode",
      items: this.transformNodeList(node.items, queryId)
    });
  }
  transformPartitionByItem(node, queryId) {
    return requireAllProps({
      kind: "PartitionByItemNode",
      partitionBy: this.transformNode(node.partitionBy, queryId)
    });
  }
  transformBinaryOperation(node, queryId) {
    return requireAllProps({
      kind: "BinaryOperationNode",
      leftOperand: this.transformNode(node.leftOperand, queryId),
      operator: this.transformNode(node.operator, queryId),
      rightOperand: this.transformNode(node.rightOperand, queryId)
    });
  }
  transformUnaryOperation(node, queryId) {
    return requireAllProps({
      kind: "UnaryOperationNode",
      operator: this.transformNode(node.operator, queryId),
      operand: this.transformNode(node.operand, queryId)
    });
  }
  transformUsing(node, queryId) {
    return requireAllProps({
      kind: "UsingNode",
      tables: this.transformNodeList(node.tables, queryId)
    });
  }
  transformFunction(node, queryId) {
    return requireAllProps({
      kind: "FunctionNode",
      func: node.func,
      arguments: this.transformNodeList(node.arguments, queryId)
    });
  }
  transformCase(node, queryId) {
    return requireAllProps({
      kind: "CaseNode",
      value: this.transformNode(node.value, queryId),
      when: this.transformNodeList(node.when, queryId),
      else: this.transformNode(node.else, queryId),
      isStatement: node.isStatement
    });
  }
  transformWhen(node, queryId) {
    return requireAllProps({
      kind: "WhenNode",
      condition: this.transformNode(node.condition, queryId),
      result: this.transformNode(node.result, queryId)
    });
  }
  transformJSONReference(node, queryId) {
    return requireAllProps({
      kind: "JSONReferenceNode",
      reference: this.transformNode(node.reference, queryId),
      traversal: this.transformNode(node.traversal, queryId)
    });
  }
  transformJSONPath(node, queryId) {
    return requireAllProps({
      kind: "JSONPathNode",
      inOperator: this.transformNode(node.inOperator, queryId),
      pathLegs: this.transformNodeList(node.pathLegs, queryId)
    });
  }
  transformJSONPathLeg(node, _queryId) {
    return requireAllProps({
      kind: "JSONPathLegNode",
      type: node.type,
      value: node.value
    });
  }
  transformJSONOperatorChain(node, queryId) {
    return requireAllProps({
      kind: "JSONOperatorChainNode",
      operator: this.transformNode(node.operator, queryId),
      values: this.transformNodeList(node.values, queryId)
    });
  }
  transformTuple(node, queryId) {
    return requireAllProps({
      kind: "TupleNode",
      values: this.transformNodeList(node.values, queryId)
    });
  }
  transformMergeQuery(node, queryId) {
    return requireAllProps({
      kind: "MergeQueryNode",
      into: this.transformNode(node.into, queryId),
      using: this.transformNode(node.using, queryId),
      whens: this.transformNodeList(node.whens, queryId),
      with: this.transformNode(node.with, queryId),
      top: this.transformNode(node.top, queryId),
      endModifiers: this.transformNodeList(node.endModifiers, queryId),
      output: this.transformNode(node.output, queryId),
      returning: this.transformNode(node.returning, queryId)
    });
  }
  transformMatched(node, _queryId) {
    return requireAllProps({
      kind: "MatchedNode",
      not: node.not,
      bySource: node.bySource
    });
  }
  transformAddIndex(node, queryId) {
    return requireAllProps({
      kind: "AddIndexNode",
      name: this.transformNode(node.name, queryId),
      columns: this.transformNodeList(node.columns, queryId),
      unique: node.unique,
      using: this.transformNode(node.using, queryId),
      ifNotExists: node.ifNotExists
    });
  }
  transformCast(node, queryId) {
    return requireAllProps({
      kind: "CastNode",
      expression: this.transformNode(node.expression, queryId),
      dataType: this.transformNode(node.dataType, queryId)
    });
  }
  transformFetch(node, queryId) {
    return requireAllProps({
      kind: "FetchNode",
      rowCount: this.transformNode(node.rowCount, queryId),
      modifier: node.modifier
    });
  }
  transformTop(node, _queryId) {
    return requireAllProps({
      kind: "TopNode",
      expression: node.expression,
      modifiers: node.modifiers
    });
  }
  transformOutput(node, queryId) {
    return requireAllProps({
      kind: "OutputNode",
      selections: this.transformNodeList(node.selections, queryId)
    });
  }
  transformDataType(node, _queryId) {
    return node;
  }
  transformSelectAll(node, _queryId) {
    return node;
  }
  transformIdentifier(node, _queryId) {
    return node;
  }
  transformValue(node, _queryId) {
    return node;
  }
  transformPrimitiveValueList(node, _queryId) {
    return node;
  }
  transformOperator(node, _queryId) {
    return node;
  }
  transformDefaultInsertValue(node, _queryId) {
    return node;
  }
  transformOrAction(node, _queryId) {
    return node;
  }
  transformCollate(node, _queryId) {
    return node;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-transformer.js
var ROOT_OPERATION_NODES = freeze({
  AlterTableNode: true,
  CreateIndexNode: true,
  CreateSchemaNode: true,
  CreateTableNode: true,
  CreateTypeNode: true,
  CreateViewNode: true,
  RefreshMaterializedViewNode: true,
  DeleteQueryNode: true,
  DropIndexNode: true,
  DropSchemaNode: true,
  DropTableNode: true,
  DropTypeNode: true,
  DropViewNode: true,
  InsertQueryNode: true,
  RawNode: true,
  SelectQueryNode: true,
  UpdateQueryNode: true,
  MergeQueryNode: true
});
var SCHEMALESS_FUNCTIONS = {
  json_agg: true,
  to_json: true
};
var WithSchemaTransformer = class extends OperationNodeTransformer {
  #schema;
  #schemableIds = /* @__PURE__ */ new Set();
  #ctes = /* @__PURE__ */ new Set();
  constructor(schema) {
    super();
    this.#schema = schema;
  }
  transformNodeImpl(node, queryId) {
    if (!this.#isRootOperationNode(node)) {
      return super.transformNodeImpl(node, queryId);
    }
    const ctes = this.#collectCTEs(node);
    for (const cte of ctes) {
      this.#ctes.add(cte);
    }
    const tables = this.#collectSchemableIds(node);
    for (const table of tables) {
      this.#schemableIds.add(table);
    }
    const transformed = super.transformNodeImpl(node, queryId);
    for (const table of tables) {
      this.#schemableIds.delete(table);
    }
    for (const cte of ctes) {
      this.#ctes.delete(cte);
    }
    return transformed;
  }
  transformSchemableIdentifier(node, queryId) {
    const transformed = super.transformSchemableIdentifier(node, queryId);
    if (transformed.schema || !this.#schemableIds.has(node.identifier.name)) {
      return transformed;
    }
    return {
      ...transformed,
      schema: IdentifierNode.create(this.#schema)
    };
  }
  transformReferences(node, queryId) {
    const transformed = super.transformReferences(node, queryId);
    if (transformed.table.table.schema) {
      return transformed;
    }
    return {
      ...transformed,
      table: TableNode.createWithSchema(this.#schema, transformed.table.table.identifier.name)
    };
  }
  transformAggregateFunction(node, queryId) {
    return {
      ...super.transformAggregateFunction({ ...node, aggregated: [] }, queryId),
      aggregated: this.#transformTableArgsWithoutSchemas(node, queryId, "aggregated")
    };
  }
  transformFunction(node, queryId) {
    return {
      ...super.transformFunction({ ...node, arguments: [] }, queryId),
      arguments: this.#transformTableArgsWithoutSchemas(node, queryId, "arguments")
    };
  }
  transformSelectModifier(node, queryId) {
    var _a8;
    return {
      ...super.transformSelectModifier({ ...node, of: void 0 }, queryId),
      of: (_a8 = node.of) == null ? void 0 : _a8.map((item) => TableNode.is(item) && !item.table.schema ? {
        ...item,
        table: this.transformIdentifier(item.table.identifier, queryId)
      } : this.transformNode(item, queryId))
    };
  }
  #transformTableArgsWithoutSchemas(node, queryId, argsKey) {
    return SCHEMALESS_FUNCTIONS[node.func] ? node[argsKey].map((arg) => !TableNode.is(arg) || arg.table.schema ? this.transformNode(arg, queryId) : {
      ...arg,
      table: this.transformIdentifier(arg.table.identifier, queryId)
    }) : this.transformNodeList(node[argsKey], queryId);
  }
  #isRootOperationNode(node) {
    return node.kind in ROOT_OPERATION_NODES;
  }
  #collectSchemableIds(node) {
    const schemableIds = /* @__PURE__ */ new Set();
    if ("name" in node && node.name && SchemableIdentifierNode.is(node.name)) {
      this.#collectSchemableId(node.name, schemableIds);
    }
    if ("from" in node && node.from) {
      for (const from of node.from.froms) {
        this.#collectSchemableIdsFromTableExpr(from, schemableIds);
      }
    }
    if ("into" in node && node.into) {
      this.#collectSchemableIdsFromTableExpr(node.into, schemableIds);
    }
    if ("table" in node && node.table) {
      this.#collectSchemableIdsFromTableExpr(node.table, schemableIds);
    }
    if ("joins" in node && node.joins) {
      for (const join of node.joins) {
        this.#collectSchemableIdsFromTableExpr(join.table, schemableIds);
      }
    }
    if ("using" in node && node.using) {
      if (JoinNode.is(node.using)) {
        this.#collectSchemableIdsFromTableExpr(node.using.table, schemableIds);
      } else {
        this.#collectSchemableIdsFromTableExpr(node.using, schemableIds);
      }
    }
    return schemableIds;
  }
  #collectCTEs(node) {
    const ctes = /* @__PURE__ */ new Set();
    if ("with" in node && node.with) {
      this.#collectCTEIds(node.with, ctes);
    }
    return ctes;
  }
  #collectSchemableIdsFromTableExpr(node, schemableIds) {
    if (TableNode.is(node)) {
      return this.#collectSchemableId(node.table, schemableIds);
    }
    if (AliasNode.is(node) && TableNode.is(node.node)) {
      return this.#collectSchemableId(node.node.table, schemableIds);
    }
    if (ListNode.is(node)) {
      for (const table of node.items) {
        this.#collectSchemableIdsFromTableExpr(table, schemableIds);
      }
      return;
    }
    if (UsingNode.is(node)) {
      for (const table of node.tables) {
        this.#collectSchemableIdsFromTableExpr(table, schemableIds);
      }
      return;
    }
  }
  #collectSchemableId(node, schemableIds) {
    const id = node.identifier.name;
    if (!this.#schemableIds.has(id) && !this.#ctes.has(id)) {
      schemableIds.add(id);
    }
  }
  #collectCTEIds(node, ctes) {
    for (const expr of node.expressions) {
      const cteId = expr.name.table.table.identifier.name;
      if (!this.#ctes.has(cteId)) {
        ctes.add(cteId);
      }
    }
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-plugin.js
var WithSchemaPlugin = class {
  #transformer;
  constructor(schema) {
    this.#transformer = new WithSchemaTransformer(schema);
  }
  transformQuery(args) {
    return this.#transformer.transformNode(args.node, args.queryId);
  }
  async transformResult(args) {
    return args.result;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/merge-query-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/merge-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/matched-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var MatchedNode = freeze({
  is(node) {
    return node.kind === "MatchedNode";
  },
  create(not, bySource = false) {
    return freeze({
      kind: "MatchedNode",
      not,
      bySource
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/merge-parser.js
function parseMergeWhen(type, args, refRight) {
  return WhenNode.create(parseFilterList([
    MatchedNode.create(!type.isMatched, type.bySource),
    ...args && args.length > 0 ? [
      args.length === 3 && refRight ? parseReferentialBinaryOperation(args[0], args[1], args[2]) : parseValueBinaryOperationOrExpression(args)
    ] : []
  ], "and", false));
}
function parseMergeThen(result) {
  if (isString(result)) {
    return RawNode.create([result], []);
  }
  if (isOperationNodeSource(result)) {
    return result.toOperationNode();
  }
  return result;
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-executor/noop-query-executor.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-executor/query-executor-base.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/util/provide-controlled-connection.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/util/deferred.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var Deferred = class {
  #promise;
  #resolve;
  #reject;
  constructor() {
    this.#promise = new Promise((resolve2, reject) => {
      this.#reject = reject;
      this.#resolve = resolve2;
    });
  }
  get promise() {
    return this.#promise;
  }
  resolve = (value) => {
    if (this.#resolve) {
      this.#resolve(value);
    }
  };
  reject = (reason) => {
    if (this.#reject) {
      this.#reject(reason);
    }
  };
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/util/provide-controlled-connection.js
async function provideControlledConnection(connectionProvider) {
  const connectionDefer = new Deferred();
  const connectionReleaseDefer = new Deferred();
  connectionProvider.provideConnection(async (connection) => {
    connectionDefer.resolve(connection);
    return await connectionReleaseDefer.promise;
  }).catch((ex) => connectionDefer.reject(ex));
  return freeze({
    connection: await connectionDefer.promise,
    release: connectionReleaseDefer.resolve
  });
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-executor/query-executor-base.js
var NO_PLUGINS = freeze([]);
var QueryExecutorBase = class {
  #plugins;
  constructor(plugins = NO_PLUGINS) {
    this.#plugins = plugins;
  }
  get plugins() {
    return this.#plugins;
  }
  transformQuery(node, queryId) {
    for (const plugin2 of this.#plugins) {
      const transformedNode = plugin2.transformQuery({ node, queryId });
      if (transformedNode.kind === node.kind) {
        node = transformedNode;
      } else {
        throw new Error([
          `KyselyPlugin.transformQuery must return a node`,
          `of the same kind that was given to it.`,
          `The plugin was given a ${node.kind}`,
          `but it returned a ${transformedNode.kind}`
        ].join(" "));
      }
    }
    return node;
  }
  async executeQuery(compiledQuery) {
    return await this.provideConnection(async (connection) => {
      const result = await connection.executeQuery(compiledQuery);
      if ("numUpdatedOrDeletedRows" in result) {
        logOnce("kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`.");
      }
      return await this.#transformResult(result, compiledQuery.queryId);
    });
  }
  async *stream(compiledQuery, chunkSize) {
    const { connection, release } = await provideControlledConnection(this);
    try {
      for await (const result of connection.streamQuery(compiledQuery, chunkSize)) {
        yield await this.#transformResult(result, compiledQuery.queryId);
      }
    } finally {
      release();
    }
  }
  async #transformResult(result, queryId) {
    for (const plugin2 of this.#plugins) {
      result = await plugin2.transformResult({ result, queryId });
    }
    return result;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-executor/noop-query-executor.js
var NoopQueryExecutor = class _NoopQueryExecutor extends QueryExecutorBase {
  get adapter() {
    throw new Error("this query cannot be compiled to SQL");
  }
  compileQuery() {
    throw new Error("this query cannot be compiled to SQL");
  }
  provideConnection() {
    throw new Error("this query cannot be executed");
  }
  withConnectionProvider() {
    throw new Error("this query cannot have a connection provider");
  }
  withPlugin(plugin2) {
    return new _NoopQueryExecutor([...this.plugins, plugin2]);
  }
  withPlugins(plugins) {
    return new _NoopQueryExecutor([...this.plugins, ...plugins]);
  }
  withPluginAtFront(plugin2) {
    return new _NoopQueryExecutor([plugin2, ...this.plugins]);
  }
  withoutPlugins() {
    return new _NoopQueryExecutor([]);
  }
};
var NOOP_QUERY_EXECUTOR = new NoopQueryExecutor();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/merge-result.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var MergeResult = class {
  numChangedRows;
  constructor(numChangedRows) {
    this.numChangedRows = numChangedRows;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/merge-query-builder.js
var MergeQueryBuilder = class _MergeQueryBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  /**
   * This can be used to add any additional SQL to the end of the query.
   *
   * ### Examples
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db
   *   .mergeInto('person')
   *   .using('pet', 'pet.owner_id', 'person.id')
   *   .whenMatched()
   *   .thenDelete()
   *   .modifyEnd(sql.raw('-- this is a comment'))
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * merge into "person" using "pet" on "pet"."owner_id" = "person"."id" when matched then delete -- this is a comment
   * ```
   */
  modifyEnd(modifier) {
    return new _MergeQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode())
    });
  }
  /**
   * Changes a `merge into` query to an `merge top into` query.
   *
   * `top` clause is only supported by some dialects like MS SQL Server.
   *
   * ### Examples
   *
   * Affect 5 matched rows at most:
   *
   * ```ts
   * await db.mergeInto('person')
   *   .top(5)
   *   .using('pet', 'person.id', 'pet.owner_id')
   *   .whenMatched()
   *   .thenDelete()
   *   .execute()
   * ```
   *
   * The generated SQL (MS SQL Server):
   *
   * ```sql
   * merge top(5) into "person"
   * using "pet" on "person"."id" = "pet"."owner_id"
   * when matched then
   *   delete
   * ```
   *
   * Affect 50% of matched rows:
   *
   * ```ts
   * await db.mergeInto('person')
   *   .top(50, 'percent')
   *   .using('pet', 'person.id', 'pet.owner_id')
   *   .whenMatched()
   *   .thenDelete()
   *   .execute()
   * ```
   *
   * The generated SQL (MS SQL Server):
   *
   * ```sql
   * merge top(50) percent into "person"
   * using "pet" on "person"."id" = "pet"."owner_id"
   * when matched then
   *   delete
   * ```
   */
  top(expression, modifiers) {
    return new _MergeQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers))
    });
  }
  using(...args) {
    return new WheneableMergeQueryBuilder({
      ...this.#props,
      queryNode: MergeQueryNode.cloneWithUsing(this.#props.queryNode, parseJoin("Using", args))
    });
  }
  returning(args) {
    return new _MergeQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(args))
    });
  }
  returningAll(table) {
    return new _MergeQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table))
    });
  }
  output(args) {
    return new _MergeQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args))
    });
  }
  outputAll(table) {
    return new _MergeQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table))
    });
  }
};
var WheneableMergeQueryBuilder = class _WheneableMergeQueryBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  /**
   * This can be used to add any additional SQL to the end of the query.
   *
   * ### Examples
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db
   *   .mergeInto('person')
   *   .using('pet', 'pet.owner_id', 'person.id')
   *   .whenMatched()
   *   .thenDelete()
   *   .modifyEnd(sql.raw('-- this is a comment'))
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * merge into "person" using "pet" on "pet"."owner_id" = "person"."id" when matched then delete -- this is a comment
   * ```
   */
  modifyEnd(modifier) {
    return new _WheneableMergeQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode())
    });
  }
  /**
   * See {@link MergeQueryBuilder.top}.
   */
  top(expression, modifiers) {
    return new _WheneableMergeQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers))
    });
  }
  /**
   * Adds a simple `when matched` clause to the query.
   *
   * For a `when matched` clause with an `and` condition, see {@link whenMatchedAnd}.
   *
   * For a simple `when not matched` clause, see {@link whenNotMatched}.
   *
   * For a `when not matched` clause with an `and` condition, see {@link whenNotMatchedAnd}.
   *
   * ### Examples
   *
   * ```ts
   * const result = await db.mergeInto('person')
   *   .using('pet', 'person.id', 'pet.owner_id')
   *   .whenMatched()
   *   .thenDelete()
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * merge into "person"
   * using "pet" on "person"."id" = "pet"."owner_id"
   * when matched then
   *   delete
   * ```
   */
  whenMatched() {
    return this.#whenMatched([]);
  }
  whenMatchedAnd(...args) {
    return this.#whenMatched(args);
  }
  /**
   * Adds the `when matched` clause to the query with an `and` condition. But unlike
   * {@link whenMatchedAnd}, this method accepts a column reference as the 3rd argument.
   *
   * This method is similar to {@link SelectQueryBuilder.whereRef}, so see the documentation
   * for that method for more examples.
   */
  whenMatchedAndRef(lhs, op, rhs) {
    return this.#whenMatched([lhs, op, rhs], true);
  }
  #whenMatched(args, refRight) {
    return new MatchedThenableMergeQueryBuilder({
      ...this.#props,
      queryNode: MergeQueryNode.cloneWithWhen(this.#props.queryNode, parseMergeWhen({ isMatched: true }, args, refRight))
    });
  }
  /**
   * Adds a simple `when not matched` clause to the query.
   *
   * For a `when not matched` clause with an `and` condition, see {@link whenNotMatchedAnd}.
   *
   * For a simple `when matched` clause, see {@link whenMatched}.
   *
   * For a `when matched` clause with an `and` condition, see {@link whenMatchedAnd}.
   *
   * ### Examples
   *
   * ```ts
   * const result = await db.mergeInto('person')
   *   .using('pet', 'person.id', 'pet.owner_id')
   *   .whenNotMatched()
   *   .thenInsertValues({
   *     first_name: 'John',
   *     last_name: 'Doe',
   *   })
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * merge into "person"
   * using "pet" on "person"."id" = "pet"."owner_id"
   * when not matched then
   *   insert ("first_name", "last_name") values ($1, $2)
   * ```
   */
  whenNotMatched() {
    return this.#whenNotMatched([]);
  }
  whenNotMatchedAnd(...args) {
    return this.#whenNotMatched(args);
  }
  /**
   * Adds the `when not matched` clause to the query with an `and` condition. But unlike
   * {@link whenNotMatchedAnd}, this method accepts a column reference as the 3rd argument.
   *
   * Unlike {@link whenMatchedAndRef}, you cannot reference columns from the target table.
   *
   * This method is similar to {@link SelectQueryBuilder.whereRef}, so see the documentation
   * for that method for more examples.
   */
  whenNotMatchedAndRef(lhs, op, rhs) {
    return this.#whenNotMatched([lhs, op, rhs], true);
  }
  /**
   * Adds a simple `when not matched by source` clause to the query.
   *
   * Supported in MS SQL Server.
   *
   * Similar to {@link whenNotMatched}, but returns a {@link MatchedThenableMergeQueryBuilder}.
   */
  whenNotMatchedBySource() {
    return this.#whenNotMatched([], false, true);
  }
  whenNotMatchedBySourceAnd(...args) {
    return this.#whenNotMatched(args, false, true);
  }
  /**
   * Adds the `when not matched by source` clause to the query with an `and` condition.
   *
   * Similar to {@link whenNotMatchedAndRef}, but you can reference columns from
   * the target table, and not from source table and returns a {@link MatchedThenableMergeQueryBuilder}.
   */
  whenNotMatchedBySourceAndRef(lhs, op, rhs) {
    return this.#whenNotMatched([lhs, op, rhs], true, true);
  }
  returning(args) {
    return new _WheneableMergeQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(args))
    });
  }
  returningAll(table) {
    return new _WheneableMergeQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table))
    });
  }
  output(args) {
    return new _WheneableMergeQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args))
    });
  }
  outputAll(table) {
    return new _WheneableMergeQueryBuilder({
      ...this.#props,
      queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table))
    });
  }
  #whenNotMatched(args, refRight = false, bySource = false) {
    const props = {
      ...this.#props,
      queryNode: MergeQueryNode.cloneWithWhen(this.#props.queryNode, parseMergeWhen({ isMatched: false, bySource }, args, refRight))
    };
    const Builder = bySource ? MatchedThenableMergeQueryBuilder : NotMatchedThenableMergeQueryBuilder;
    return new Builder(props);
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   *
   * If you want to conditionally call a method on `this`, see
   * the {@link $if} method.
   *
   * ### Examples
   *
   * The next example uses a helper function `log` to log a query:
   *
   * ```ts
   * import type { Compilable } from 'kysely'
   *
   * function log<T extends Compilable>(qb: T): T {
   *   console.log(qb.compile())
   *   return qb
   * }
   *
   * await db.updateTable('person')
   *   .set({ first_name: 'John' })
   *   .$call(log)
   *   .execute()
   * ```
   */
  $call(func) {
    return func(this);
  }
  /**
   * Call `func(this)` if `condition` is true.
   *
   * This method is especially handy with optional selects. Any `returning` or `returningAll`
   * method calls add columns as optional fields to the output type when called inside
   * the `func` callback. This is because we can't know if those selections were actually
   * made before running the code.
   *
   * You can also call any other methods inside the callback.
   *
   * ### Examples
   *
   * ```ts
   * import type { PersonUpdate } from 'type-editor' // imaginary module
   *
   * async function updatePerson(id: number, updates: PersonUpdate, returnLastName: boolean) {
   *   return await db
   *     .updateTable('person')
   *     .set(updates)
   *     .where('id', '=', id)
   *     .returning(['id', 'first_name'])
   *     .$if(returnLastName, (qb) => qb.returning('last_name'))
   *     .executeTakeFirstOrThrow()
   * }
   * ```
   *
   * Any selections added inside the `if` callback will be added as optional fields to the
   * output type since we can't know if the selections were actually made before running
   * the code. In the example above the return type of the `updatePerson` function is:
   *
   * ```ts
   * Promise<{
   *   id: number
   *   first_name: string
   *   last_name?: string
   * }>
   * ```
   */
  $if(condition, func) {
    if (condition) {
      return func(this);
    }
    return new _WheneableMergeQueryBuilder({
      ...this.#props
    });
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  /**
   * Executes the query and returns an array of rows.
   *
   * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods.
   */
  async execute() {
    const compiledQuery = this.compile();
    const result = await this.#props.executor.executeQuery(compiledQuery);
    const { adapter } = this.#props.executor;
    const query = compiledQuery.query;
    if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) {
      return result.rows;
    }
    return [new MergeResult(result.numAffectedRows)];
  }
  /**
   * Executes the query and returns the first result or undefined if
   * the query returned no result.
   */
  async executeTakeFirst() {
    const [result] = await this.execute();
    return result;
  }
  /**
   * Executes the query and returns the first result or throws if
   * the query returned no result.
   *
   * By default an instance of {@link NoResultError} is thrown, but you can
   * provide a custom error class, or callback as the only argument to throw a different
   * error.
   */
  async executeTakeFirstOrThrow(errorConstructor = NoResultError) {
    const result = await this.executeTakeFirst();
    if (result === void 0) {
      const error = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode());
      throw error;
    }
    return result;
  }
};
var MatchedThenableMergeQueryBuilder = class {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  /**
   * Performs the `delete` action.
   *
   * To perform the `do nothing` action, see {@link thenDoNothing}.
   *
   * To perform the `update` action, see {@link thenUpdate} or {@link thenUpdateSet}.
   *
   * ### Examples
   *
   * ```ts
   * const result = await db.mergeInto('person')
   *   .using('pet', 'person.id', 'pet.owner_id')
   *   .whenMatched()
   *   .thenDelete()
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * merge into "person"
   * using "pet" on "person"."id" = "pet"."owner_id"
   * when matched then
   *   delete
   * ```
   */
  thenDelete() {
    return new WheneableMergeQueryBuilder({
      ...this.#props,
      queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen("delete"))
    });
  }
  /**
   * Performs the `do nothing` action.
   *
   * This is supported in PostgreSQL.
   *
   * To perform the `delete` action, see {@link thenDelete}.
   *
   * To perform the `update` action, see {@link thenUpdate} or {@link thenUpdateSet}.
   *
   * ### Examples
   *
   * ```ts
   * const result = await db.mergeInto('person')
   *   .using('pet', 'person.id', 'pet.owner_id')
   *   .whenMatched()
   *   .thenDoNothing()
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * merge into "person"
   * using "pet" on "person"."id" = "pet"."owner_id"
   * when matched then
   *   do nothing
   * ```
   */
  thenDoNothing() {
    return new WheneableMergeQueryBuilder({
      ...this.#props,
      queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen("do nothing"))
    });
  }
  /**
   * Perform an `update` operation with a full-fledged {@link UpdateQueryBuilder}.
   * This is handy when multiple `set` invocations are needed.
   *
   * For a shorthand version of this method, see {@link thenUpdateSet}.
   *
   * To perform the `delete` action, see {@link thenDelete}.
   *
   * To perform the `do nothing` action, see {@link thenDoNothing}.
   *
   * ### Examples
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * const result = await db.mergeInto('person')
   *   .using('pet', 'person.id', 'pet.owner_id')
   *   .whenMatched()
   *   .thenUpdate((ub) => ub
   *     .set(sql`metadata['has_pets']`, 'Y')
   *     .set({
   *       updated_at: new Date().toISOString(),
   *     })
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * merge into "person"
   * using "pet" on "person"."id" = "pet"."owner_id"
   * when matched then
   *   update set metadata['has_pets'] = $1, "updated_at" = $2
   * ```
   */
  thenUpdate(set) {
    return new WheneableMergeQueryBuilder({
      ...this.#props,
      queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen(set(new UpdateQueryBuilder({
        queryId: this.#props.queryId,
        executor: NOOP_QUERY_EXECUTOR,
        queryNode: UpdateQueryNode.createWithoutTable()
      }))))
    });
  }
  thenUpdateSet(...args) {
    return this.thenUpdate((ub) => ub.set(...args));
  }
};
var NotMatchedThenableMergeQueryBuilder = class {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  /**
   * Performs the `do nothing` action.
   *
   * This is supported in PostgreSQL.
   *
   * To perform the `insert` action, see {@link thenInsertValues}.
   *
   * ### Examples
   *
   * ```ts
   * const result = await db.mergeInto('person')
   *   .using('pet', 'person.id', 'pet.owner_id')
   *   .whenNotMatched()
   *   .thenDoNothing()
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * merge into "person"
   * using "pet" on "person"."id" = "pet"."owner_id"
   * when not matched then
   *   do nothing
   * ```
   */
  thenDoNothing() {
    return new WheneableMergeQueryBuilder({
      ...this.#props,
      queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen("do nothing"))
    });
  }
  thenInsertValues(insert) {
    const [columns, values] = parseInsertExpression(insert);
    return new WheneableMergeQueryBuilder({
      ...this.#props,
      queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen(InsertQueryNode.cloneWith(InsertQueryNode.createWithoutInto(), {
        columns,
        values
      })))
    });
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-creator.js
var QueryCreator = class _QueryCreator {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  /**
   * Creates a `select` query builder for the given table or tables.
   *
   * The tables passed to this method are built as the query's `from` clause.
   *
   * ### Examples
   *
   * Create a select query for one table:
   *
   * ```ts
   * db.selectFrom('person').selectAll()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * select * from "person"
   * ```
   *
   * Create a select query for one table with an alias:
   *
   * ```ts
   * const persons = await db.selectFrom('person as p')
   *   .select(['p.id', 'first_name'])
   *   .execute()
   *
   * console.log(persons[0].id)
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * select "p"."id", "first_name" from "person" as "p"
   * ```
   *
   * Create a select query from a subquery:
   *
   * ```ts
   * const persons = await db.selectFrom(
   *     (eb) => eb.selectFrom('person').select('person.id as identifier').as('p')
   *   )
   *   .select('p.identifier')
   *   .execute()
   *
   * console.log(persons[0].identifier)
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * select "p"."identifier",
   * from (
   *   select "person"."id" as "identifier" from "person"
   * ) as p
   * ```
   *
   * Create a select query from raw sql:
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * const items = await db
   *   .selectFrom(sql<{ one: number }>`(select 1 as one)`.as('q'))
   *   .select('q.one')
   *   .execute()
   *
   * console.log(items[0].one)
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * select "q"."one",
   * from (
   *   select 1 as one
   * ) as q
   * ```
   *
   * When you use the `sql` tag you need to also provide the result type of the
   * raw snippet / query so that Kysely can figure out what columns are
   * available for the rest of the query.
   *
   * The `selectFrom` method also accepts an array for multiple tables. All
   * the above examples can also be used in an array.
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * const items = await db.selectFrom([
   *     'person as p',
   *     db.selectFrom('pet').select('pet.species').as('a'),
   *     sql<{ one: number }>`(select 1 as one)`.as('q')
   *   ])
   *   .select(['p.id', 'a.species', 'q.one'])
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * select "p".id, "a"."species", "q"."one"
   * from
   *   "person" as "p",
   *   (select "pet"."species" from "pet") as a,
   *   (select 1 as one) as "q"
   * ```
   */
  selectFrom(from) {
    return createSelectQueryBuilder({
      queryId: createQueryId(),
      executor: this.#props.executor,
      queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(from), this.#props.withNode)
    });
  }
  selectNoFrom(selection) {
    return createSelectQueryBuilder({
      queryId: createQueryId(),
      executor: this.#props.executor,
      queryNode: SelectQueryNode.cloneWithSelections(SelectQueryNode.create(this.#props.withNode), parseSelectArg(selection))
    });
  }
  /**
   * Creates an insert query.
   *
   * The return value of this query is an instance of {@link InsertResult}. {@link InsertResult}
   * has the {@link InsertResult.insertId | insertId} field that holds the auto incremented id of
   * the inserted row if the db returned one.
   *
   * See the {@link InsertQueryBuilder.values | values} method for more info and examples. Also see
   * the {@link ReturningInterface.returning | returning} method for a way to return columns
   * on supported databases like PostgreSQL.
   *
   * ### Examples
   *
   * ```ts
   * const result = await db
   *   .insertInto('person')
   *   .values({
   *     first_name: 'Jennifer',
   *     last_name: 'Aniston'
   *   })
   *   .executeTakeFirst()
   *
   * console.log(result.insertId)
   * ```
   *
   * Some databases like PostgreSQL support the `returning` method:
   *
   * ```ts
   * const { id } = await db
   *   .insertInto('person')
   *   .values({
   *     first_name: 'Jennifer',
   *     last_name: 'Aniston'
   *   })
   *   .returning('id')
   *   .executeTakeFirstOrThrow()
   * ```
   */
  insertInto(table) {
    return new InsertQueryBuilder({
      queryId: createQueryId(),
      executor: this.#props.executor,
      queryNode: InsertQueryNode.create(parseTable(table), this.#props.withNode)
    });
  }
  /**
   * Creates a "replace into" query.
   *
   * This is only supported by some dialects like MySQL or SQLite.
   *
   * Similar to MySQL's {@link InsertQueryBuilder.onDuplicateKeyUpdate} that deletes
   * and inserts values on collision instead of updating existing rows.
   *
   * An alias of SQLite's {@link InsertQueryBuilder.orReplace}.
   *
   * The return value of this query is an instance of {@link InsertResult}. {@link InsertResult}
   * has the {@link InsertResult.insertId | insertId} field that holds the auto incremented id of
   * the inserted row if the db returned one.
   *
   * See the {@link InsertQueryBuilder.values | values} method for more info and examples.
   *
   * ### Examples
   *
   * ```ts
   * const result = await db
   *   .replaceInto('person')
   *   .values({
   *     first_name: 'Jennifer',
   *     last_name: 'Aniston'
   *   })
   *   .executeTakeFirstOrThrow()
   *
   * console.log(result.insertId)
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * replace into `person` (`first_name`, `last_name`) values (?, ?)
   * ```
   */
  replaceInto(table) {
    return new InsertQueryBuilder({
      queryId: createQueryId(),
      executor: this.#props.executor,
      queryNode: InsertQueryNode.create(parseTable(table), this.#props.withNode, true)
    });
  }
  /**
   * Creates a delete query.
   *
   * See the {@link DeleteQueryBuilder.where} method for examples on how to specify
   * a where clause for the delete operation.
   *
   * The return value of the query is an instance of {@link DeleteResult}.
   *
   * ### Examples
   *
   * <!-- siteExample("delete", "Single row", 10) -->
   *
   * Delete a single row:
   *
   * ```ts
   * const result = await db
   *   .deleteFrom('person')
   *   .where('person.id', '=', 1)
   *   .executeTakeFirst()
   *
   * console.log(result.numDeletedRows)
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * delete from "person" where "person"."id" = $1
   * ```
   *
   * Some databases such as MySQL support deleting from multiple tables:
   *
   * ```ts
   * const result = await db
   *   .deleteFrom(['person', 'pet'])
   *   .using('person')
   *   .innerJoin('pet', 'pet.owner_id', 'person.id')
   *   .where('person.id', '=', 1)
   *   .executeTakeFirst()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * delete from `person`, `pet`
   * using `person`
   * inner join `pet` on `pet`.`owner_id` = `person`.`id`
   * where `person`.`id` = ?
   * ```
   */
  deleteFrom(from) {
    return new DeleteQueryBuilder({
      queryId: createQueryId(),
      executor: this.#props.executor,
      queryNode: DeleteQueryNode.create(parseTableExpressionOrList(from), this.#props.withNode)
    });
  }
  /**
   * Creates an update query.
   *
   * See the {@link UpdateQueryBuilder.where} method for examples on how to specify
   * a where clause for the update operation.
   *
   * See the {@link UpdateQueryBuilder.set} method for examples on how to
   * specify the updates.
   *
   * The return value of the query is an {@link UpdateResult}.
   *
   * ### Examples
   *
   * ```ts
   * const result = await db
   *   .updateTable('person')
   *   .set({ first_name: 'Jennifer' })
   *   .where('person.id', '=', 1)
   *   .executeTakeFirst()
   *
   * console.log(result.numUpdatedRows)
   * ```
   */
  updateTable(tables) {
    return new UpdateQueryBuilder({
      queryId: createQueryId(),
      executor: this.#props.executor,
      queryNode: UpdateQueryNode.create(parseTableExpressionOrList(tables), this.#props.withNode)
    });
  }
  /**
   * Creates a merge query.
   *
   * The return value of the query is a {@link MergeResult}.
   *
   * See the {@link MergeQueryBuilder.using} method for examples on how to specify
   * the other table.
   *
   * ### Examples
   *
   * <!-- siteExample("merge", "Source row existence", 10) -->
   *
   * Update a target column based on the existence of a source row:
   *
   * ```ts
   * const result = await db
   *   .mergeInto('person as target')
   *   .using('pet as source', 'source.owner_id', 'target.id')
   *   .whenMatchedAnd('target.has_pets', '!=', 'Y')
   *   .thenUpdateSet({ has_pets: 'Y' })
   *   .whenNotMatchedBySourceAnd('target.has_pets', '=', 'Y')
   *   .thenUpdateSet({ has_pets: 'N' })
   *   .executeTakeFirstOrThrow()
   *
   * console.log(result.numChangedRows)
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * merge into "person"
   * using "pet"
   * on "pet"."owner_id" = "person"."id"
   * when matched and "has_pets" != $1
   * then update set "has_pets" = $2
   * when not matched by source and "has_pets" = $3
   * then update set "has_pets" = $4
   * ```
   *
   * <!-- siteExample("merge", "Temporary changes table", 20) -->
   *
   * Merge new entries from a temporary changes table:
   *
   * ```ts
   * const result = await db
   *   .mergeInto('wine as target')
   *   .using(
   *     'wine_stock_change as source',
   *     'source.wine_name',
   *     'target.name',
   *   )
   *   .whenNotMatchedAnd('source.stock_delta', '>', 0)
   *   .thenInsertValues(({ ref }) => ({
   *     name: ref('source.wine_name'),
   *     stock: ref('source.stock_delta'),
   *   }))
   *   .whenMatchedAnd(
   *     (eb) => eb('target.stock', '+', eb.ref('source.stock_delta')),
   *     '>',
   *     0,
   *   )
   *   .thenUpdateSet('stock', (eb) =>
   *     eb('target.stock', '+', eb.ref('source.stock_delta')),
   *   )
   *   .whenMatched()
   *   .thenDelete()
   *   .executeTakeFirstOrThrow()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * merge into "wine" as "target"
   * using "wine_stock_change" as "source"
   * on "source"."wine_name" = "target"."name"
   * when not matched and "source"."stock_delta" > $1
   * then insert ("name", "stock") values ("source"."wine_name", "source"."stock_delta")
   * when matched and "target"."stock" + "source"."stock_delta" > $2
   * then update set "stock" = "target"."stock" + "source"."stock_delta"
   * when matched
   * then delete
   * ```
   */
  mergeInto(targetTable) {
    return new MergeQueryBuilder({
      queryId: createQueryId(),
      executor: this.#props.executor,
      queryNode: MergeQueryNode.create(parseAliasedTable(targetTable), this.#props.withNode)
    });
  }
  /**
   * Creates a `with` query (Common Table Expression).
   *
   * ### Examples
   *
   * <!-- siteExample("cte", "Simple selects", 10) -->
   *
   * Common table expressions (CTE) are a great way to modularize complex queries.
   * Essentially they allow you to run multiple separate queries within a
   * single roundtrip to the DB.
   *
   * Since CTEs are a part of the main query, query optimizers inside DB
   * engines are able to optimize the overall query. For example, postgres
   * is able to inline the CTEs inside the using queries if it decides it's
   * faster.
   *
   * ```ts
   * const result = await db
   *   // Create a CTE called `jennifers` that selects all
   *   // persons named 'Jennifer'.
   *   .with('jennifers', (db) => db
   *     .selectFrom('person')
   *     .where('first_name', '=', 'Jennifer')
   *     .select(['id', 'age'])
   *   )
   *   // Select all rows from the `jennifers` CTE and
   *   // further filter it.
   *   .with('adult_jennifers', (db) => db
   *     .selectFrom('jennifers')
   *     .where('age', '>', 18)
   *     .select(['id', 'age'])
   *   )
   *   // Finally select all adult jennifers that are
   *   // also younger than 60.
   *   .selectFrom('adult_jennifers')
   *   .where('age', '<', 60)
   *   .selectAll()
   *   .execute()
   * ```
   *
   * <!-- siteExample("cte", "Inserts, updates and deletions", 20) -->
   *
   * Some databases like postgres also allow you to run other queries than selects
   * in CTEs. On these databases CTEs are extremely powerful:
   *
   * ```ts
   * const result = await db
   *   .with('new_person', (db) => db
   *     .insertInto('person')
   *     .values({
   *       first_name: 'Jennifer',
   *       age: 35,
   *     })
   *     .returning('id')
   *   )
   *   .with('new_pet', (db) => db
   *     .insertInto('pet')
   *     .values({
   *       name: 'Doggo',
   *       species: 'dog',
   *       is_favorite: true,
   *       // Use the id of the person we just inserted.
   *       owner_id: db
   *         .selectFrom('new_person')
   *         .select('id')
   *     })
   *     .returning('id')
   *   )
   *   .selectFrom(['new_person', 'new_pet'])
   *   .select([
   *     'new_person.id as person_id',
   *     'new_pet.id as pet_id'
   *   ])
   *   .execute()
   * ```
   *
   * The CTE name can optionally specify column names in addition to
   * a name. In that case Kysely requires the expression to retun
   * rows with the same columns.
   *
   * ```ts
   * await db
   *   .with('jennifers(id, age)', (db) => db
   *     .selectFrom('person')
   *     .where('first_name', '=', 'Jennifer')
   *     // This is ok since we return columns with the same
   *     // names as specified by `jennifers(id, age)`.
   *     .select(['id', 'age'])
   *   )
   *   .selectFrom('jennifers')
   *   .selectAll()
   *   .execute()
   * ```
   *
   * The first argument can also be a callback. The callback is passed
   * a `CTEBuilder` instance that can be used to configure the CTE:
   *
   * ```ts
   * await db
   *   .with(
   *     (cte) => cte('jennifers').materialized(),
   *     (db) => db
   *       .selectFrom('person')
   *       .where('first_name', '=', 'Jennifer')
   *       .select(['id', 'age'])
   *   )
   *   .selectFrom('jennifers')
   *   .selectAll()
   *   .execute()
   * ```
   */
  with(nameOrBuilder, expression) {
    const cte = parseCommonTableExpression(nameOrBuilder, expression);
    return new _QueryCreator({
      ...this.#props,
      withNode: this.#props.withNode ? WithNode.cloneWithExpression(this.#props.withNode, cte) : WithNode.create(cte)
    });
  }
  /**
   * Creates a recursive `with` query (Common Table Expression).
   *
   * Note that recursiveness is a property of the whole `with` statement.
   * You cannot have recursive and non-recursive CTEs in a same `with` statement.
   * Therefore the recursiveness is determined by the **first** `with` or
   * `withRecusive` call you make.
   *
   * See the {@link with} method for examples and more documentation.
   */
  withRecursive(nameOrBuilder, expression) {
    const cte = parseCommonTableExpression(nameOrBuilder, expression);
    return new _QueryCreator({
      ...this.#props,
      withNode: this.#props.withNode ? WithNode.cloneWithExpression(this.#props.withNode, cte) : WithNode.create(cte, { recursive: true })
    });
  }
  /**
   * Returns a copy of this query creator instance with the given plugin installed.
   */
  withPlugin(plugin2) {
    return new _QueryCreator({
      ...this.#props,
      executor: this.#props.executor.withPlugin(plugin2)
    });
  }
  /**
   * Returns a copy of this query creator instance without any plugins.
   */
  withoutPlugins() {
    return new _QueryCreator({
      ...this.#props,
      executor: this.#props.executor.withoutPlugins()
    });
  }
  /**
   * Sets the schema to be used for all table references that don't explicitly
   * specify a schema.
   *
   * This only affects the query created through the builder returned from
   * this method and doesn't modify the `db` instance.
   *
   * See [this recipe](https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/0007-schemas.md)
   * for a more detailed explanation.
   *
   * ### Examples
   *
   * ```
   * await db
   *   .withSchema('mammals')
   *   .selectFrom('pet')
   *   .selectAll()
   *   .innerJoin('public.person', 'public.person.id', 'pet.owner_id')
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * select * from "mammals"."pet"
   * inner join "public"."person"
   * on "public"."person"."id" = "mammals"."pet"."owner_id"
   * ```
   *
   * `withSchema` is smart enough to not add schema for aliases,
   * common table expressions or other places where the schema
   * doesn't belong to:
   *
   * ```
   * await db
   *   .withSchema('mammals')
   *   .selectFrom('pet as p')
   *   .select('p.name')
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * select "p"."name" from "mammals"."pet" as "p"
   * ```
   */
  withSchema(schema) {
    return new _QueryCreator({
      ...this.#props,
      executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema))
    });
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/parse-utils.js
function createQueryCreator() {
  return new QueryCreator({
    executor: NOOP_QUERY_EXECUTOR
  });
}
function createJoinBuilder(joinType, table) {
  return new JoinBuilder({
    joinNode: JoinNode.create(joinType, parseTableExpression(table))
  });
}
function createOverBuilder() {
  return new OverBuilder({
    overNode: OverNode.create()
  });
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/join-parser.js
function parseJoin(joinType, args) {
  if (args.length === 3) {
    return parseSingleOnJoin(joinType, args[0], args[1], args[2]);
  } else if (args.length === 2) {
    return parseCallbackJoin(joinType, args[0], args[1]);
  } else if (args.length === 1) {
    return parseOnlessJoin(joinType, args[0]);
  } else {
    throw new Error("not implemented");
  }
}
function parseCallbackJoin(joinType, from, callback) {
  return callback(createJoinBuilder(joinType, from)).toOperationNode();
}
function parseSingleOnJoin(joinType, from, lhsColumn, rhsColumn) {
  return JoinNode.createWithOn(joinType, parseTableExpression(from), parseReferentialBinaryOperation(lhsColumn, "=", rhsColumn));
}
function parseOnlessJoin(joinType, from) {
  return JoinNode.create(joinType, parseTableExpression(from));
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/offset-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var OffsetNode = freeze({
  is(node) {
    return node.kind === "OffsetNode";
  },
  create(offset) {
    return freeze({
      kind: "OffsetNode",
      offset
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/group-by-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/group-by-item-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var GroupByItemNode = freeze({
  is(node) {
    return node.kind === "GroupByItemNode";
  },
  create(groupBy) {
    return freeze({
      kind: "GroupByItemNode",
      groupBy
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/group-by-parser.js
function parseGroupBy(groupBy) {
  groupBy = isFunction(groupBy) ? groupBy(expressionBuilder()) : groupBy;
  return parseReferenceExpressionOrList(groupBy).map(GroupByItemNode.create);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/set-operation-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/set-operation-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var SetOperationNode = freeze({
  is(node) {
    return node.kind === "SetOperationNode";
  },
  create(operator, expression, all) {
    return freeze({
      kind: "SetOperationNode",
      operator,
      expression,
      all
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/set-operation-parser.js
function parseSetOperations(operator, expression, all) {
  if (isFunction(expression)) {
    expression = expression(createExpressionBuilder());
  }
  if (!isReadonlyArray(expression)) {
    expression = [expression];
  }
  return expression.map((expr) => SetOperationNode.create(operator, parseExpression(expr), all));
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/expression/expression-wrapper.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ExpressionWrapper = class _ExpressionWrapper {
  #node;
  constructor(node) {
    this.#node = node;
  }
  /** @private */
  get expressionType() {
    return void 0;
  }
  as(alias) {
    return new AliasedExpressionWrapper(this, alias);
  }
  or(...args) {
    return new OrWrapper(OrNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));
  }
  and(...args) {
    return new AndWrapper(AndNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));
  }
  /**
   * Change the output type of the expression.
   *
   * This method call doesn't change the SQL in any way. This methods simply
   * returns a copy of this `ExpressionWrapper` with a new output type.
   */
  $castTo() {
    return new _ExpressionWrapper(this.#node);
  }
  /**
   * Omit null from the expression's type.
   *
   * This function can be useful in cases where you know an expression can't be
   * null, but Kysely is unable to infer it.
   *
   * This method call doesn't change the SQL in any way. This methods simply
   * returns a copy of `this` with a new output type.
   */
  $notNull() {
    return new _ExpressionWrapper(this.#node);
  }
  toOperationNode() {
    return this.#node;
  }
};
var AliasedExpressionWrapper = class {
  #expr;
  #alias;
  constructor(expr, alias) {
    this.#expr = expr;
    this.#alias = alias;
  }
  /** @private */
  get expression() {
    return this.#expr;
  }
  /** @private */
  get alias() {
    return this.#alias;
  }
  toOperationNode() {
    return AliasNode.create(this.#expr.toOperationNode(), isOperationNodeSource(this.#alias) ? this.#alias.toOperationNode() : IdentifierNode.create(this.#alias));
  }
};
var OrWrapper = class _OrWrapper {
  #node;
  constructor(node) {
    this.#node = node;
  }
  /** @private */
  get expressionType() {
    return void 0;
  }
  as(alias) {
    return new AliasedExpressionWrapper(this, alias);
  }
  or(...args) {
    return new _OrWrapper(OrNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));
  }
  /**
   * Change the output type of the expression.
   *
   * This method call doesn't change the SQL in any way. This methods simply
   * returns a copy of this `OrWrapper` with a new output type.
   */
  $castTo() {
    return new _OrWrapper(this.#node);
  }
  toOperationNode() {
    return ParensNode.create(this.#node);
  }
};
var AndWrapper = class _AndWrapper {
  #node;
  constructor(node) {
    this.#node = node;
  }
  /** @private */
  get expressionType() {
    return void 0;
  }
  as(alias) {
    return new AliasedExpressionWrapper(this, alias);
  }
  and(...args) {
    return new _AndWrapper(AndNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));
  }
  /**
   * Change the output type of the expression.
   *
   * This method call doesn't change the SQL in any way. This methods simply
   * returns a copy of this `AndWrapper` with a new output type.
   */
  $castTo() {
    return new _AndWrapper(this.#node);
  }
  toOperationNode() {
    return ParensNode.create(this.#node);
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/fetch-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/fetch-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var FetchNode = freeze({
  is(node) {
    return node.kind === "FetchNode";
  },
  create(rowCount, modifier) {
    return {
      kind: "FetchNode",
      rowCount: ValueNode.create(rowCount),
      modifier
    };
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/fetch-parser.js
function parseFetch(rowCount, modifier) {
  if (!isNumber(rowCount) && !isBigInt(rowCount)) {
    throw new Error(`Invalid fetch row count: ${rowCount}`);
  }
  if (!isFetchModifier(modifier)) {
    throw new Error(`Invalid fetch modifier: ${modifier}`);
  }
  return FetchNode.create(rowCount, modifier);
}
function isFetchModifier(value) {
  return value === "only" || value === "with ties";
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/select-query-builder.js
var SelectQueryBuilderImpl = class _SelectQueryBuilderImpl {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  get expressionType() {
    return void 0;
  }
  get isSelectQueryBuilder() {
    return true;
  }
  where(...args) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args))
    });
  }
  whereRef(lhs, op, rhs) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs))
    });
  }
  having(...args) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithHaving(this.#props.queryNode, parseValueBinaryOperationOrExpression(args))
    });
  }
  havingRef(lhs, op, rhs) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithHaving(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs))
    });
  }
  select(selection) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithSelections(this.#props.queryNode, parseSelectArg(selection))
    });
  }
  distinctOn(selection) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithDistinctOn(this.#props.queryNode, parseReferenceExpressionOrList(selection))
    });
  }
  modifyFront(modifier) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithFrontModifier(this.#props.queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode()))
    });
  }
  modifyEnd(modifier) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode()))
    });
  }
  distinct() {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithFrontModifier(this.#props.queryNode, SelectModifierNode.create("Distinct"))
    });
  }
  forUpdate(of) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("ForUpdate", of ? asArray(of).map(parseTable) : void 0))
    });
  }
  forShare(of) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("ForShare", of ? asArray(of).map(parseTable) : void 0))
    });
  }
  forKeyShare(of) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("ForKeyShare", of ? asArray(of).map(parseTable) : void 0))
    });
  }
  forNoKeyUpdate(of) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("ForNoKeyUpdate", of ? asArray(of).map(parseTable) : void 0))
    });
  }
  skipLocked() {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("SkipLocked"))
    });
  }
  noWait() {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("NoWait"))
    });
  }
  selectAll(table) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithSelections(this.#props.queryNode, parseSelectAll(table))
    });
  }
  innerJoin(...args) {
    return this.#join("InnerJoin", args);
  }
  leftJoin(...args) {
    return this.#join("LeftJoin", args);
  }
  rightJoin(...args) {
    return this.#join("RightJoin", args);
  }
  fullJoin(...args) {
    return this.#join("FullJoin", args);
  }
  crossJoin(...args) {
    return this.#join("CrossJoin", args);
  }
  innerJoinLateral(...args) {
    return this.#join("LateralInnerJoin", args);
  }
  leftJoinLateral(...args) {
    return this.#join("LateralLeftJoin", args);
  }
  crossJoinLateral(...args) {
    return this.#join("LateralCrossJoin", args);
  }
  crossApply(...args) {
    return this.#join("CrossApply", args);
  }
  outerApply(...args) {
    return this.#join("OuterApply", args);
  }
  #join(joinType, args) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args))
    });
  }
  orderBy(...args) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args))
    });
  }
  groupBy(groupBy) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithGroupByItems(this.#props.queryNode, parseGroupBy(groupBy))
    });
  }
  limit(limit) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit)))
    });
  }
  offset(offset) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithOffset(this.#props.queryNode, OffsetNode.create(parseValueExpression(offset)))
    });
  }
  fetch(rowCount, modifier = "only") {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithFetch(this.#props.queryNode, parseFetch(rowCount, modifier))
    });
  }
  top(expression, modifiers) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers))
    });
  }
  union(expression) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("union", expression, false))
    });
  }
  unionAll(expression) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("union", expression, true))
    });
  }
  intersect(expression) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("intersect", expression, false))
    });
  }
  intersectAll(expression) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("intersect", expression, true))
    });
  }
  except(expression) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("except", expression, false))
    });
  }
  exceptAll(expression) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("except", expression, true))
    });
  }
  as(alias) {
    return new AliasedSelectQueryBuilderImpl(this, alias);
  }
  clearSelect() {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithoutSelections(this.#props.queryNode)
    });
  }
  clearWhere() {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode)
    });
  }
  clearLimit() {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithoutLimit(this.#props.queryNode)
    });
  }
  clearOffset() {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithoutOffset(this.#props.queryNode)
    });
  }
  clearOrderBy() {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode)
    });
  }
  clearGroupBy() {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: SelectQueryNode.cloneWithoutGroupBy(this.#props.queryNode)
    });
  }
  $call(func) {
    return func(this);
  }
  $if(condition, func) {
    if (condition) {
      return func(this);
    }
    return new _SelectQueryBuilderImpl({
      ...this.#props
    });
  }
  $castTo() {
    return new _SelectQueryBuilderImpl(this.#props);
  }
  $narrowType() {
    return new _SelectQueryBuilderImpl(this.#props);
  }
  $assertType() {
    return new _SelectQueryBuilderImpl(this.#props);
  }
  $asTuple() {
    return new ExpressionWrapper(this.toOperationNode());
  }
  $asScalar() {
    return new ExpressionWrapper(this.toOperationNode());
  }
  withPlugin(plugin2) {
    return new _SelectQueryBuilderImpl({
      ...this.#props,
      executor: this.#props.executor.withPlugin(plugin2)
    });
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  async execute() {
    const compiledQuery = this.compile();
    const result = await this.#props.executor.executeQuery(compiledQuery);
    return result.rows;
  }
  async executeTakeFirst() {
    const [result] = await this.execute();
    return result;
  }
  async executeTakeFirstOrThrow(errorConstructor = NoResultError) {
    const result = await this.executeTakeFirst();
    if (result === void 0) {
      const error = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode());
      throw error;
    }
    return result;
  }
  async *stream(chunkSize = 100) {
    const compiledQuery = this.compile();
    const stream = this.#props.executor.stream(compiledQuery, chunkSize);
    for await (const item of stream) {
      yield* item.rows;
    }
  }
  async explain(format, options) {
    const builder = new _SelectQueryBuilderImpl({
      ...this.#props,
      queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options)
    });
    return await builder.execute();
  }
};
function createSelectQueryBuilder(props) {
  return new SelectQueryBuilderImpl(props);
}
var AliasedSelectQueryBuilderImpl = class {
  #queryBuilder;
  #alias;
  constructor(queryBuilder, alias) {
    this.#queryBuilder = queryBuilder;
    this.#alias = alias;
  }
  get expression() {
    return this.#queryBuilder;
  }
  get alias() {
    return this.#alias;
  }
  get isAliasedSelectQueryBuilder() {
    return true;
  }
  toOperationNode() {
    return AliasNode.create(this.#queryBuilder.toOperationNode(), IdentifierNode.create(this.#alias));
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/function-module.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/aggregate-function-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var AggregateFunctionNode = freeze({
  is(node) {
    return node.kind === "AggregateFunctionNode";
  },
  create(aggregateFunction, aggregated = []) {
    return freeze({
      kind: "AggregateFunctionNode",
      func: aggregateFunction,
      aggregated
    });
  },
  cloneWithDistinct(aggregateFunctionNode) {
    return freeze({
      ...aggregateFunctionNode,
      distinct: true
    });
  },
  cloneWithOrderBy(aggregateFunctionNode, orderItems, withinGroup = false) {
    const prop = withinGroup ? "withinGroup" : "orderBy";
    return freeze({
      ...aggregateFunctionNode,
      [prop]: aggregateFunctionNode[prop] ? OrderByNode.cloneWithItems(aggregateFunctionNode[prop], orderItems) : OrderByNode.create(orderItems)
    });
  },
  cloneWithFilter(aggregateFunctionNode, filter) {
    return freeze({
      ...aggregateFunctionNode,
      filter: aggregateFunctionNode.filter ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, "And", filter) : WhereNode.create(filter)
    });
  },
  cloneWithOrFilter(aggregateFunctionNode, filter) {
    return freeze({
      ...aggregateFunctionNode,
      filter: aggregateFunctionNode.filter ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, "Or", filter) : WhereNode.create(filter)
    });
  },
  cloneWithOver(aggregateFunctionNode, over) {
    return freeze({
      ...aggregateFunctionNode,
      over
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/function-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var FunctionNode = freeze({
  is(node) {
    return node.kind === "FunctionNode";
  },
  create(func, args) {
    return freeze({
      kind: "FunctionNode",
      func,
      arguments: args
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/aggregate-function-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var AggregateFunctionBuilder = class _AggregateFunctionBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  /** @private */
  get expressionType() {
    return void 0;
  }
  /**
   * Returns an aliased version of the function.
   *
   * In addition to slapping `as "the_alias"` to the end of the SQL,
   * this method also provides strict typing:
   *
   * ```ts
   * const result = await db
   *   .selectFrom('person')
   *   .select(
   *     (eb) => eb.fn.count<number>('id').as('person_count')
   *   )
   *   .executeTakeFirstOrThrow()
   *
   * // `person_count: number` field exists in the result type.
   * console.log(result.person_count)
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * select count("id") as "person_count"
   * from "person"
   * ```
   */
  as(alias) {
    return new AliasedAggregateFunctionBuilder(this, alias);
  }
  /**
   * Adds a `distinct` clause inside the function.
   *
   * ### Examples
   *
   * ```ts
   * const result = await db
   *   .selectFrom('person')
   *   .select((eb) =>
   *     eb.fn.count<number>('first_name').distinct().as('first_name_count')
   *   )
   *   .executeTakeFirstOrThrow()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * select count(distinct "first_name") as "first_name_count"
   * from "person"
   * ```
   */
  distinct() {
    return new _AggregateFunctionBuilder({
      ...this.#props,
      aggregateFunctionNode: AggregateFunctionNode.cloneWithDistinct(this.#props.aggregateFunctionNode)
    });
  }
  orderBy(...args) {
    return new _AggregateFunctionBuilder({
      ...this.#props,
      aggregateFunctionNode: QueryNode.cloneWithOrderByItems(this.#props.aggregateFunctionNode, parseOrderBy(args))
    });
  }
  clearOrderBy() {
    return new _AggregateFunctionBuilder({
      ...this.#props,
      aggregateFunctionNode: QueryNode.cloneWithoutOrderBy(this.#props.aggregateFunctionNode)
    });
  }
  withinGroupOrderBy(...args) {
    return new _AggregateFunctionBuilder({
      ...this.#props,
      aggregateFunctionNode: AggregateFunctionNode.cloneWithOrderBy(this.#props.aggregateFunctionNode, parseOrderBy(args), true)
    });
  }
  filterWhere(...args) {
    return new _AggregateFunctionBuilder({
      ...this.#props,
      aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(this.#props.aggregateFunctionNode, parseValueBinaryOperationOrExpression(args))
    });
  }
  /**
   * Adds a `filter` clause with a nested `where` clause after the function, where
   * both sides of the operator are references to columns.
   *
   * Similar to {@link WhereInterface}'s `whereRef` method.
   *
   * ### Examples
   *
   * Count people with same first and last names versus general public:
   *
   * ```ts
   * const result = await db
   *   .selectFrom('person')
   *   .select((eb) => [
   *     eb.fn
   *       .count<number>('id')
   *       .filterWhereRef('first_name', '=', 'last_name')
   *       .as('repeat_name_count'),
   *     eb.fn.count<number>('id').as('total_count'),
   *   ])
   *   .executeTakeFirstOrThrow()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * select
   *   count("id") filter(where "first_name" = "last_name") as "repeat_name_count",
   *   count("id") as "total_count"
   * from "person"
   * ```
   */
  filterWhereRef(lhs, op, rhs) {
    return new _AggregateFunctionBuilder({
      ...this.#props,
      aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(this.#props.aggregateFunctionNode, parseReferentialBinaryOperation(lhs, op, rhs))
    });
  }
  /**
   * Adds an `over` clause (window functions) after the function.
   *
   * ### Examples
   *
   * ```ts
   * const result = await db
   *   .selectFrom('person')
   *   .select(
   *     (eb) => eb.fn.avg<number>('age').over().as('average_age')
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * select avg("age") over() as "average_age"
   * from "person"
   * ```
   *
   * Also supports passing a callback that returns an over builder,
   * allowing to add partition by and sort by clauses inside over.
   *
   * ```ts
   * const result = await db
   *   .selectFrom('person')
   *   .select(
   *     (eb) => eb.fn.avg<number>('age').over(
   *       ob => ob.partitionBy('last_name').orderBy('first_name', 'asc')
   *     ).as('average_age')
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * select avg("age") over(partition by "last_name" order by "first_name" asc) as "average_age"
   * from "person"
   * ```
   */
  over(over) {
    const builder = createOverBuilder();
    return new _AggregateFunctionBuilder({
      ...this.#props,
      aggregateFunctionNode: AggregateFunctionNode.cloneWithOver(this.#props.aggregateFunctionNode, (over ? over(builder) : builder).toOperationNode())
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  /**
   * Casts the expression to the given type.
   *
   * This method call doesn't change the SQL in any way. This methods simply
   * returns a copy of this `AggregateFunctionBuilder` with a new output type.
   */
  $castTo() {
    return new _AggregateFunctionBuilder(this.#props);
  }
  /**
   * Omit null from the expression's type.
   *
   * This function can be useful in cases where you know an expression can't be
   * null, but Kysely is unable to infer it.
   *
   * This method call doesn't change the SQL in any way. This methods simply
   * returns a copy of `this` with a new output type.
   */
  $notNull() {
    return new _AggregateFunctionBuilder(this.#props);
  }
  toOperationNode() {
    return this.#props.aggregateFunctionNode;
  }
};
var AliasedAggregateFunctionBuilder = class {
  #aggregateFunctionBuilder;
  #alias;
  constructor(aggregateFunctionBuilder, alias) {
    this.#aggregateFunctionBuilder = aggregateFunctionBuilder;
    this.#alias = alias;
  }
  /** @private */
  get expression() {
    return this.#aggregateFunctionBuilder;
  }
  /** @private */
  get alias() {
    return this.#alias;
  }
  toOperationNode() {
    return AliasNode.create(this.#aggregateFunctionBuilder.toOperationNode(), IdentifierNode.create(this.#alias));
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/function-module.js
function createFunctionModule() {
  const fn = (name, args) => {
    return new ExpressionWrapper(FunctionNode.create(name, parseReferenceExpressionOrList(args ?? [])));
  };
  const agg = (name, args) => {
    return new AggregateFunctionBuilder({
      aggregateFunctionNode: AggregateFunctionNode.create(name, args ? parseReferenceExpressionOrList(args) : void 0)
    });
  };
  return Object.assign(fn, {
    agg,
    avg(column) {
      return agg("avg", [column]);
    },
    coalesce(...values) {
      return fn("coalesce", values);
    },
    count(column) {
      return agg("count", [column]);
    },
    countAll(table) {
      return new AggregateFunctionBuilder({
        aggregateFunctionNode: AggregateFunctionNode.create("count", parseSelectAll(table))
      });
    },
    max(column) {
      return agg("max", [column]);
    },
    min(column) {
      return agg("min", [column]);
    },
    sum(column) {
      return agg("sum", [column]);
    },
    any(column) {
      return fn("any", [column]);
    },
    jsonAgg(table) {
      return new AggregateFunctionBuilder({
        aggregateFunctionNode: AggregateFunctionNode.create("json_agg", [
          isString(table) ? parseTable(table) : table.toOperationNode()
        ])
      });
    },
    toJson(table) {
      return new ExpressionWrapper(FunctionNode.create("to_json", [
        isString(table) ? parseTable(table) : table.toOperationNode()
      ]));
    }
  });
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/unary-operation-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/unary-operation-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var UnaryOperationNode = freeze({
  is(node) {
    return node.kind === "UnaryOperationNode";
  },
  create(operator, operand) {
    return freeze({
      kind: "UnaryOperationNode",
      operator,
      operand
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/unary-operation-parser.js
function parseUnaryOperation(operator, operand) {
  return UnaryOperationNode.create(OperatorNode.create(operator), parseReferenceExpression(operand));
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/case-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/case-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var CaseNode = freeze({
  is(node) {
    return node.kind === "CaseNode";
  },
  create(value) {
    return freeze({
      kind: "CaseNode",
      value
    });
  },
  cloneWithWhen(caseNode, when) {
    return freeze({
      ...caseNode,
      when: freeze(caseNode.when ? [...caseNode.when, when] : [when])
    });
  },
  cloneWithThen(caseNode, then) {
    return freeze({
      ...caseNode,
      when: caseNode.when ? freeze([
        ...caseNode.when.slice(0, -1),
        WhenNode.cloneWithResult(caseNode.when[caseNode.when.length - 1], then)
      ]) : void 0
    });
  },
  cloneWith(caseNode, props) {
    return freeze({
      ...caseNode,
      ...props
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/case-builder.js
var CaseBuilder = class {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  when(...args) {
    return new CaseThenBuilder({
      ...this.#props,
      node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseValueBinaryOperationOrExpression(args)))
    });
  }
};
var CaseThenBuilder = class {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  then(valueExpression) {
    return new CaseWhenBuilder({
      ...this.#props,
      node: CaseNode.cloneWithThen(this.#props.node, isSafeImmediateValue(valueExpression) ? parseSafeImmediateValue(valueExpression) : parseValueExpression(valueExpression))
    });
  }
};
var CaseWhenBuilder = class {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  when(...args) {
    return new CaseThenBuilder({
      ...this.#props,
      node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseValueBinaryOperationOrExpression(args)))
    });
  }
  else(valueExpression) {
    return new CaseEndBuilder({
      ...this.#props,
      node: CaseNode.cloneWith(this.#props.node, {
        else: isSafeImmediateValue(valueExpression) ? parseSafeImmediateValue(valueExpression) : parseValueExpression(valueExpression)
      })
    });
  }
  end() {
    return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: false }));
  }
  endCase() {
    return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: true }));
  }
};
var CaseEndBuilder = class {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  end() {
    return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: false }));
  }
  endCase() {
    return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: true }));
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/json-path-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/json-path-leg-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var JSONPathLegNode = freeze({
  is(node) {
    return node.kind === "JSONPathLegNode";
  },
  create(type, value) {
    return freeze({
      kind: "JSONPathLegNode",
      type,
      value
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-builder/json-path-builder.js
var JSONPathBuilder = class {
  #node;
  constructor(node) {
    this.#node = node;
  }
  /**
   * Access an element of a JSON array in a specific location.
   *
   * Since there's no guarantee an element exists in the given array location, the
   * resulting type is always nullable. If you're sure the element exists, you
   * should use {@link SelectQueryBuilder.$assertType} to narrow the type safely.
   *
   * See also {@link key} to access properties of JSON objects.
   *
   * ### Examples
   *
   * ```ts
   * await db.selectFrom('person')
   *   .select(eb =>
   *     eb.ref('nicknames', '->').at(0).as('primary_nickname')
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * select "nicknames"->0 as "primary_nickname" from "person"
   *```
   *
   * Combined with {@link key}:
   *
   * ```ts
   * db.selectFrom('person').select(eb =>
   *   eb.ref('experience', '->').at(0).key('role').as('first_role')
   * )
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * select "experience"->0->'role' as "first_role" from "person"
   * ```
   *
   * You can use `'last'` to access the last element of the array in MySQL:
   *
   * ```ts
   * db.selectFrom('person').select(eb =>
   *   eb.ref('nicknames', '->$').at('last').as('last_nickname')
   * )
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * select `nicknames`->'$[last]' as `last_nickname` from `person`
   * ```
   *
   * Or `'#-1'` in SQLite:
   *
   * ```ts
   * db.selectFrom('person').select(eb =>
   *   eb.ref('nicknames', '->>$').at('#-1').as('last_nickname')
   * )
   * ```
   *
   * The generated SQL (SQLite):
   *
   * ```sql
   * select "nicknames"->>'$[#-1]' as `last_nickname` from `person`
   * ```
   */
  at(index) {
    return this.#createBuilderWithPathLeg("ArrayLocation", index);
  }
  /**
   * Access a property of a JSON object.
   *
   * If a field is optional, the resulting type will be nullable.
   *
   * See also {@link at} to access elements of JSON arrays.
   *
   * ### Examples
   *
   * ```ts
   * db.selectFrom('person').select(eb =>
   *   eb.ref('address', '->').key('city').as('city')
   * )
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * select "address"->'city' as "city" from "person"
   * ```
   *
   * Going deeper:
   *
   * ```ts
   * db.selectFrom('person').select(eb =>
   *   eb.ref('profile', '->$').key('website').key('url').as('website_url')
   * )
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * select `profile`->'$.website.url' as `website_url` from `person`
   * ```
   *
   * Combined with {@link at}:
   *
   * ```ts
   * db.selectFrom('person').select(eb =>
   *   eb.ref('profile', '->').key('addresses').at(0).key('city').as('city')
   * )
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * select "profile"->'addresses'->0->'city' as "city" from "person"
   * ```
   */
  key(key) {
    return this.#createBuilderWithPathLeg("Member", key);
  }
  #createBuilderWithPathLeg(legType, value) {
    if (JSONReferenceNode.is(this.#node)) {
      return new TraversedJSONPathBuilder(JSONReferenceNode.cloneWithTraversal(this.#node, JSONPathNode.is(this.#node.traversal) ? JSONPathNode.cloneWithLeg(this.#node.traversal, JSONPathLegNode.create(legType, value)) : JSONOperatorChainNode.cloneWithValue(this.#node.traversal, ValueNode.createImmediate(value))));
    }
    return new TraversedJSONPathBuilder(JSONPathNode.cloneWithLeg(this.#node, JSONPathLegNode.create(legType, value)));
  }
};
var TraversedJSONPathBuilder = class _TraversedJSONPathBuilder extends JSONPathBuilder {
  #node;
  constructor(node) {
    super(node);
    this.#node = node;
  }
  /** @private */
  get expressionType() {
    return void 0;
  }
  as(alias) {
    return new AliasedJSONPathBuilder(this, alias);
  }
  /**
   * Change the output type of the json path.
   *
   * This method call doesn't change the SQL in any way. This methods simply
   * returns a copy of this `JSONPathBuilder` with a new output type.
   */
  $castTo() {
    return new _TraversedJSONPathBuilder(this.#node);
  }
  $notNull() {
    return new _TraversedJSONPathBuilder(this.#node);
  }
  toOperationNode() {
    return this.#node;
  }
};
var AliasedJSONPathBuilder = class {
  #jsonPath;
  #alias;
  constructor(jsonPath, alias) {
    this.#jsonPath = jsonPath;
    this.#alias = alias;
  }
  /** @private */
  get expression() {
    return this.#jsonPath;
  }
  /** @private */
  get alias() {
    return this.#alias;
  }
  toOperationNode() {
    return AliasNode.create(this.#jsonPath.toOperationNode(), isOperationNodeSource(this.#alias) ? this.#alias.toOperationNode() : IdentifierNode.create(this.#alias));
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/tuple-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var TupleNode = freeze({
  is(node) {
    return node.kind === "TupleNode";
  },
  create(values) {
    return freeze({
      kind: "TupleNode",
      values: freeze(values)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/data-type-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/data-type-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var SIMPLE_COLUMN_DATA_TYPES = [
  "varchar",
  "char",
  "text",
  "integer",
  "int2",
  "int4",
  "int8",
  "smallint",
  "bigint",
  "boolean",
  "real",
  "double precision",
  "float4",
  "float8",
  "decimal",
  "numeric",
  "binary",
  "bytea",
  "date",
  "datetime",
  "time",
  "timetz",
  "timestamp",
  "timestamptz",
  "serial",
  "bigserial",
  "uuid",
  "json",
  "jsonb",
  "blob",
  "varbinary",
  "int4range",
  "int4multirange",
  "int8range",
  "int8multirange",
  "numrange",
  "nummultirange",
  "tsrange",
  "tsmultirange",
  "tstzrange",
  "tstzmultirange",
  "daterange",
  "datemultirange"
];
var COLUMN_DATA_TYPE_REGEX = [
  /^varchar\(\d+\)$/,
  /^char\(\d+\)$/,
  /^decimal\(\d+, \d+\)$/,
  /^numeric\(\d+, \d+\)$/,
  /^binary\(\d+\)$/,
  /^datetime\(\d+\)$/,
  /^time\(\d+\)$/,
  /^timetz\(\d+\)$/,
  /^timestamp\(\d+\)$/,
  /^timestamptz\(\d+\)$/,
  /^varbinary\(\d+\)$/
];
var DataTypeNode = freeze({
  is(node) {
    return node.kind === "DataTypeNode";
  },
  create(dataType) {
    return freeze({
      kind: "DataTypeNode",
      dataType
    });
  }
});
function isColumnDataType(dataType) {
  if (SIMPLE_COLUMN_DATA_TYPES.includes(dataType)) {
    return true;
  }
  if (COLUMN_DATA_TYPE_REGEX.some((r3) => r3.test(dataType))) {
    return true;
  }
  return false;
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/data-type-parser.js
function parseDataTypeExpression(dataType) {
  if (isOperationNodeSource(dataType)) {
    return dataType.toOperationNode();
  }
  if (isColumnDataType(dataType)) {
    return DataTypeNode.create(dataType);
  }
  throw new Error(`invalid column data type ${JSON.stringify(dataType)}`);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/cast-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var CastNode = freeze({
  is(node) {
    return node.kind === "CastNode";
  },
  create(expression, dataType) {
    return freeze({
      kind: "CastNode",
      expression,
      dataType
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/expression/expression-builder.js
function createExpressionBuilder(executor = NOOP_QUERY_EXECUTOR) {
  function binary(lhs, op, rhs) {
    return new ExpressionWrapper(parseValueBinaryOperation(lhs, op, rhs));
  }
  function unary(op, expr) {
    return new ExpressionWrapper(parseUnaryOperation(op, expr));
  }
  const eb = Object.assign(binary, {
    fn: void 0,
    eb: void 0,
    selectFrom(table) {
      return createSelectQueryBuilder({
        queryId: createQueryId(),
        executor,
        queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(table))
      });
    },
    case(reference) {
      return new CaseBuilder({
        node: CaseNode.create(isUndefined(reference) ? void 0 : parseReferenceExpression(reference))
      });
    },
    ref(reference, op) {
      if (isUndefined(op)) {
        return new ExpressionWrapper(parseStringReference(reference));
      }
      return new JSONPathBuilder(parseJSONReference(reference, op));
    },
    jsonPath() {
      return new JSONPathBuilder(JSONPathNode.create());
    },
    table(table) {
      return new ExpressionWrapper(parseTable(table));
    },
    val(value) {
      return new ExpressionWrapper(parseValueExpression(value));
    },
    refTuple(...values) {
      return new ExpressionWrapper(TupleNode.create(values.map(parseReferenceExpression)));
    },
    tuple(...values) {
      return new ExpressionWrapper(TupleNode.create(values.map(parseValueExpression)));
    },
    lit(value) {
      return new ExpressionWrapper(parseSafeImmediateValue(value));
    },
    unary,
    not(expr) {
      return unary("not", expr);
    },
    exists(expr) {
      return unary("exists", expr);
    },
    neg(expr) {
      return unary("-", expr);
    },
    between(expr, start, end) {
      return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create("between"), AndNode.create(parseValueExpression(start), parseValueExpression(end))));
    },
    betweenSymmetric(expr, start, end) {
      return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create("between symmetric"), AndNode.create(parseValueExpression(start), parseValueExpression(end))));
    },
    and(exprs) {
      if (isReadonlyArray(exprs)) {
        return new ExpressionWrapper(parseFilterList(exprs, "and"));
      }
      return new ExpressionWrapper(parseFilterObject(exprs, "and"));
    },
    or(exprs) {
      if (isReadonlyArray(exprs)) {
        return new ExpressionWrapper(parseFilterList(exprs, "or"));
      }
      return new ExpressionWrapper(parseFilterObject(exprs, "or"));
    },
    parens(...args) {
      const node = parseValueBinaryOperationOrExpression(args);
      if (ParensNode.is(node)) {
        return new ExpressionWrapper(node);
      } else {
        return new ExpressionWrapper(ParensNode.create(node));
      }
    },
    cast(expr, dataType) {
      return new ExpressionWrapper(CastNode.create(parseReferenceExpression(expr), parseDataTypeExpression(dataType)));
    },
    withSchema(schema) {
      return createExpressionBuilder(executor.withPluginAtFront(new WithSchemaPlugin(schema)));
    }
  });
  eb.fn = createFunctionModule();
  eb.eb = eb;
  return eb;
}
function expressionBuilder(_3) {
  return createExpressionBuilder();
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/expression-parser.js
function parseExpression(exp) {
  if (isOperationNodeSource(exp)) {
    return exp.toOperationNode();
  } else if (isFunction(exp)) {
    return exp(expressionBuilder()).toOperationNode();
  }
  throw new Error(`invalid expression: ${JSON.stringify(exp)}`);
}
function parseAliasedExpression(exp) {
  if (isOperationNodeSource(exp)) {
    return exp.toOperationNode();
  } else if (isFunction(exp)) {
    return exp(expressionBuilder()).toOperationNode();
  }
  throw new Error(`invalid aliased expression: ${JSON.stringify(exp)}`);
}
function isExpressionOrFactory(obj) {
  return isExpression(obj) || isAliasedExpression(obj) || isFunction(obj);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/dynamic/dynamic-table-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DynamicTableBuilder = class {
  #table;
  get table() {
    return this.#table;
  }
  constructor(table) {
    this.#table = table;
  }
  as(alias) {
    return new AliasedDynamicTableBuilder(this.#table, alias);
  }
};
var AliasedDynamicTableBuilder = class {
  #table;
  #alias;
  get table() {
    return this.#table;
  }
  get alias() {
    return this.#alias;
  }
  constructor(table, alias) {
    this.#table = table;
    this.#alias = alias;
  }
  toOperationNode() {
    return AliasNode.create(parseTable(this.#table), IdentifierNode.create(this.#alias));
  }
};
function isAliasedDynamicTableBuilder(obj) {
  return isObject(obj) && isOperationNodeSource(obj) && isString(obj.table) && isString(obj.alias);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/table-parser.js
function parseTableExpressionOrList(table) {
  if (isReadonlyArray(table)) {
    return table.map((it) => parseTableExpression(it));
  } else {
    return [parseTableExpression(table)];
  }
}
function parseTableExpression(table) {
  if (isString(table)) {
    return parseAliasedTable(table);
  } else if (isAliasedDynamicTableBuilder(table)) {
    return table.toOperationNode();
  } else {
    return parseAliasedExpression(table);
  }
}
function parseAliasedTable(from) {
  const ALIAS_SEPARATOR = " as ";
  if (from.includes(ALIAS_SEPARATOR)) {
    const [table, alias] = from.split(ALIAS_SEPARATOR).map(trim2);
    return AliasNode.create(parseTable(table), IdentifierNode.create(alias));
  } else {
    return parseTable(from);
  }
}
function parseTable(from) {
  const SCHEMA_SEPARATOR = ".";
  if (from.includes(SCHEMA_SEPARATOR)) {
    const [schema, table] = from.split(SCHEMA_SEPARATOR).map(trim2);
    return TableNode.createWithSchema(schema, table);
  } else {
    return TableNode.create(from);
  }
}
function trim2(str) {
  return str.trim();
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/alter-table-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/add-column-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var AddColumnNode = freeze({
  is(node) {
    return node.kind === "AddColumnNode";
  },
  create(column) {
    return freeze({
      kind: "AddColumnNode",
      column
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/column-definition-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ColumnDefinitionNode = freeze({
  is(node) {
    return node.kind === "ColumnDefinitionNode";
  },
  create(column, dataType) {
    return freeze({
      kind: "ColumnDefinitionNode",
      column: ColumnNode.create(column),
      dataType
    });
  },
  cloneWithFrontModifier(node, modifier) {
    return freeze({
      ...node,
      frontModifiers: node.frontModifiers ? freeze([...node.frontModifiers, modifier]) : [modifier]
    });
  },
  cloneWithEndModifier(node, modifier) {
    return freeze({
      ...node,
      endModifiers: node.endModifiers ? freeze([...node.endModifiers, modifier]) : [modifier]
    });
  },
  cloneWith(node, props) {
    return freeze({
      ...node,
      ...props
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/drop-column-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DropColumnNode = freeze({
  is(node) {
    return node.kind === "DropColumnNode";
  },
  create(column) {
    return freeze({
      kind: "DropColumnNode",
      column: ColumnNode.create(column)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/rename-column-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var RenameColumnNode = freeze({
  is(node) {
    return node.kind === "RenameColumnNode";
  },
  create(column, newColumn) {
    return freeze({
      kind: "RenameColumnNode",
      column: ColumnNode.create(column),
      renameTo: ColumnNode.create(newColumn)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/column-definition-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/check-constraint-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var CheckConstraintNode = freeze({
  is(node) {
    return node.kind === "CheckConstraintNode";
  },
  create(expression, constraintName) {
    return freeze({
      kind: "CheckConstraintNode",
      expression,
      name: constraintName ? IdentifierNode.create(constraintName) : void 0
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/references-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ON_MODIFY_FOREIGN_ACTIONS = [
  "no action",
  "restrict",
  "cascade",
  "set null",
  "set default"
];
var ReferencesNode = freeze({
  is(node) {
    return node.kind === "ReferencesNode";
  },
  create(table, columns) {
    return freeze({
      kind: "ReferencesNode",
      table,
      columns: freeze([...columns])
    });
  },
  cloneWithOnDelete(references, onDelete) {
    return freeze({
      ...references,
      onDelete
    });
  },
  cloneWithOnUpdate(references, onUpdate) {
    return freeze({
      ...references,
      onUpdate
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/default-value-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function parseDefaultValueExpression(value) {
  return isOperationNodeSource(value) ? value.toOperationNode() : ValueNode.createImmediate(value);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/generated-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var GeneratedNode = freeze({
  is(node) {
    return node.kind === "GeneratedNode";
  },
  create(params) {
    return freeze({
      kind: "GeneratedNode",
      ...params
    });
  },
  createWithExpression(expression) {
    return freeze({
      kind: "GeneratedNode",
      always: true,
      expression
    });
  },
  cloneWith(node, params) {
    return freeze({
      ...node,
      ...params
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/default-value-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DefaultValueNode = freeze({
  is(node) {
    return node.kind === "DefaultValueNode";
  },
  create(defaultValue) {
    return freeze({
      kind: "DefaultValueNode",
      defaultValue
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/on-modify-action-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function parseOnModifyForeignAction(action) {
  if (ON_MODIFY_FOREIGN_ACTIONS.includes(action)) {
    return action;
  }
  throw new Error(`invalid OnModifyForeignAction ${action}`);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/column-definition-builder.js
var ColumnDefinitionBuilder = class _ColumnDefinitionBuilder {
  #node;
  constructor(node) {
    this.#node = node;
  }
  /**
   * Adds `auto_increment` or `autoincrement` to the column definition
   * depending on the dialect.
   *
   * Some dialects like PostgreSQL don't support this. On PostgreSQL
   * you can use the `serial` or `bigserial` data type instead.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createTable('person')
   *   .addColumn('id', 'integer', col => col.autoIncrement().primaryKey())
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * create table `person` (
   *   `id` integer primary key auto_increment
   * )
   * ```
   */
  autoIncrement() {
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { autoIncrement: true }));
  }
  /**
   * Makes the column an identity column.
   *
   * This only works on some dialects like MS SQL Server (MSSQL).
   *
   * For PostgreSQL's `generated always as identity` use {@link generatedAlwaysAsIdentity}.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createTable('person')
   *   .addColumn('id', 'integer', col => col.identity().primaryKey())
   *   .execute()
   * ```
   *
   * The generated SQL (MSSQL):
   *
   * ```sql
   * create table "person" (
   *   "id" integer identity primary key
   * )
   * ```
   */
  identity() {
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { identity: true }));
  }
  /**
   * Makes the column the primary key.
   *
   * If you want to specify a composite primary key use the
   * {@link CreateTableBuilder.addPrimaryKeyConstraint} method.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createTable('person')
   *   .addColumn('id', 'integer', col => col.primaryKey())
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * create table `person` (
   *   `id` integer primary key
   * )
   */
  primaryKey() {
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { primaryKey: true }));
  }
  /**
   * Adds a foreign key constraint for the column.
   *
   * If your database engine doesn't support foreign key constraints in the
   * column definition (like MySQL 5) you need to call the table level
   * {@link CreateTableBuilder.addForeignKeyConstraint} method instead.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createTable('pet')
   *   .addColumn('owner_id', 'integer', (col) => col.references('person.id'))
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * create table "pet" (
   *   "owner_id" integer references "person" ("id")
   * )
   * ```
   */
  references(ref) {
    const references = parseStringReference(ref);
    if (!references.table || SelectAllNode.is(references.column)) {
      throw new Error(`invalid call references('${ref}'). The reference must have format table.column or schema.table.column`);
    }
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {
      references: ReferencesNode.create(references.table, [
        references.column
      ])
    }));
  }
  /**
   * Adds an `on delete` constraint for the foreign key column.
   *
   * If your database engine doesn't support foreign key constraints in the
   * column definition (like MySQL 5) you need to call the table level
   * {@link CreateTableBuilder.addForeignKeyConstraint} method instead.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createTable('pet')
   *   .addColumn(
   *     'owner_id',
   *     'integer',
   *     (col) => col.references('person.id').onDelete('cascade')
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * create table "pet" (
   *   "owner_id" integer references "person" ("id") on delete cascade
   * )
   * ```
   */
  onDelete(onDelete) {
    if (!this.#node.references) {
      throw new Error("on delete constraint can only be added for foreign keys");
    }
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {
      references: ReferencesNode.cloneWithOnDelete(this.#node.references, parseOnModifyForeignAction(onDelete))
    }));
  }
  /**
   * Adds an `on update` constraint for the foreign key column.
   *
   * If your database engine doesn't support foreign key constraints in the
   * column definition (like MySQL 5) you need to call the table level
   * {@link CreateTableBuilder.addForeignKeyConstraint} method instead.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createTable('pet')
   *   .addColumn(
   *     'owner_id',
   *     'integer',
   *     (col) => col.references('person.id').onUpdate('cascade')
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * create table "pet" (
   *   "owner_id" integer references "person" ("id") on update cascade
   * )
   * ```
   */
  onUpdate(onUpdate) {
    if (!this.#node.references) {
      throw new Error("on update constraint can only be added for foreign keys");
    }
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {
      references: ReferencesNode.cloneWithOnUpdate(this.#node.references, parseOnModifyForeignAction(onUpdate))
    }));
  }
  /**
   * Adds a unique constraint for the column.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createTable('person')
   *   .addColumn('email', 'varchar(255)', col => col.unique())
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * create table `person` (
   *   `email` varchar(255) unique
   * )
   * ```
   */
  unique() {
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { unique: true }));
  }
  /**
   * Adds a `not null` constraint for the column.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createTable('person')
   *   .addColumn('first_name', 'varchar(255)', col => col.notNull())
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * create table `person` (
   *   `first_name` varchar(255) not null
   * )
   * ```
   */
  notNull() {
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { notNull: true }));
  }
  /**
   * Adds a `unsigned` modifier for the column.
   *
   * This only works on some dialects like MySQL.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createTable('person')
   *   .addColumn('age', 'integer', col => col.unsigned())
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * create table `person` (
   *   `age` integer unsigned
   * )
   * ```
   */
  unsigned() {
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { unsigned: true }));
  }
  /**
   * Adds a default value constraint for the column.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createTable('pet')
   *   .addColumn('number_of_legs', 'integer', (col) => col.defaultTo(4))
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * create table `pet` (
   *   `number_of_legs` integer default 4
   * )
   * ```
   *
   * Values passed to `defaultTo` are interpreted as value literals by default. You can define
   * an arbitrary SQL expression using the {@link sql} template tag:
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db.schema
   *   .createTable('pet')
   *   .addColumn(
   *     'created_at',
   *     'timestamp',
   *     (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`)
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * create table `pet` (
   *   `created_at` timestamp default CURRENT_TIMESTAMP
   * )
   * ```
   */
  defaultTo(value) {
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {
      defaultTo: DefaultValueNode.create(parseDefaultValueExpression(value))
    }));
  }
  /**
   * Adds a check constraint for the column.
   *
   * ### Examples
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db.schema
   *   .createTable('pet')
   *   .addColumn('number_of_legs', 'integer', (col) =>
   *     col.check(sql`number_of_legs < 5`)
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * create table `pet` (
   *   `number_of_legs` integer check (number_of_legs < 5)
   * )
   * ```
   */
  check(expression) {
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {
      check: CheckConstraintNode.create(expression.toOperationNode())
    }));
  }
  /**
   * Makes the column a generated column using a `generated always as` statement.
   *
   * ### Examples
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db.schema
   *   .createTable('person')
   *   .addColumn('full_name', 'varchar(255)',
   *     (col) => col.generatedAlwaysAs(sql`concat(first_name, ' ', last_name)`)
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * create table `person` (
   *   `full_name` varchar(255) generated always as (concat(first_name, ' ', last_name))
   * )
   * ```
   */
  generatedAlwaysAs(expression) {
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {
      generated: GeneratedNode.createWithExpression(expression.toOperationNode())
    }));
  }
  /**
   * Adds the `generated always as identity` specifier.
   *
   * This only works on some dialects like PostgreSQL.
   *
   * For MS SQL Server (MSSQL)'s identity column use {@link identity}.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createTable('person')
   *   .addColumn('id', 'integer', col => col.generatedAlwaysAsIdentity().primaryKey())
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * create table "person" (
   *   "id" integer generated always as identity primary key
   * )
   * ```
   */
  generatedAlwaysAsIdentity() {
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {
      generated: GeneratedNode.create({ identity: true, always: true })
    }));
  }
  /**
   * Adds the `generated by default as identity` specifier on supported dialects.
   *
   * This only works on some dialects like PostgreSQL.
   *
   * For MS SQL Server (MSSQL)'s identity column use {@link identity}.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createTable('person')
   *   .addColumn('id', 'integer', col => col.generatedByDefaultAsIdentity().primaryKey())
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * create table "person" (
   *   "id" integer generated by default as identity primary key
   * )
   * ```
   */
  generatedByDefaultAsIdentity() {
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {
      generated: GeneratedNode.create({ identity: true, byDefault: true })
    }));
  }
  /**
   * Makes a generated column stored instead of virtual. This method can only
   * be used with {@link generatedAlwaysAs}
   *
   * ### Examples
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db.schema
   *   .createTable('person')
   *   .addColumn('full_name', 'varchar(255)', (col) => col
   *     .generatedAlwaysAs(sql`concat(first_name, ' ', last_name)`)
   *     .stored()
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * create table `person` (
   *   `full_name` varchar(255) generated always as (concat(first_name, ' ', last_name)) stored
   * )
   * ```
   */
  stored() {
    if (!this.#node.generated) {
      throw new Error("stored() can only be called after generatedAlwaysAs");
    }
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {
      generated: GeneratedNode.cloneWith(this.#node.generated, {
        stored: true
      })
    }));
  }
  /**
   * This can be used to add any additional SQL right after the column's data type.
   *
   * ### Examples
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db.schema
   *   .createTable('person')
   *   .addColumn('id', 'integer', col => col.primaryKey())
   *   .addColumn(
   *     'first_name',
   *     'varchar(36)',
   *     (col) => col.modifyFront(sql`collate utf8mb4_general_ci`).notNull()
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * create table `person` (
   *   `id` integer primary key,
   *   `first_name` varchar(36) collate utf8mb4_general_ci not null
   * )
   * ```
   */
  modifyFront(modifier) {
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWithFrontModifier(this.#node, modifier.toOperationNode()));
  }
  /**
   * Adds `nulls not distinct` specifier.
   * Should be used with `unique` constraint.
   *
   * This only works on some dialects like PostgreSQL.
   *
   * ### Examples
   *
   * ```ts
   * db.schema
   *   .createTable('person')
   *   .addColumn('id', 'integer', col => col.primaryKey())
   *   .addColumn('first_name', 'varchar(30)', col => col.unique().nullsNotDistinct())
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * create table "person" (
   *   "id" integer primary key,
   *   "first_name" varchar(30) unique nulls not distinct
   * )
   * ```
   */
  nullsNotDistinct() {
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { nullsNotDistinct: true }));
  }
  /**
   * Adds `if not exists` specifier. This only works for PostgreSQL.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .alterTable('person')
   *   .addColumn('email', 'varchar(255)', col => col.unique().ifNotExists())
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * alter table "person" add column if not exists "email" varchar(255) unique
   * ```
   */
  ifNotExists() {
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { ifNotExists: true }));
  }
  /**
   * This can be used to add any additional SQL to the end of the column definition.
   *
   * ### Examples
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db.schema
   *   .createTable('person')
   *   .addColumn('id', 'integer', col => col.primaryKey())
   *   .addColumn(
   *     'age',
   *     'integer',
   *     col => col.unsigned()
   *       .notNull()
   *       .modifyEnd(sql`comment ${sql.lit('it is not polite to ask a woman her age')}`)
   *   )
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * create table `person` (
   *   `id` integer primary key,
   *   `age` integer unsigned not null comment 'it is not polite to ask a woman her age'
   * )
   * ```
   */
  modifyEnd(modifier) {
    return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWithEndModifier(this.#node, modifier.toOperationNode()));
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#node;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/modify-column-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ModifyColumnNode = freeze({
  is(node) {
    return node.kind === "ModifyColumnNode";
  },
  create(column) {
    return freeze({
      kind: "ModifyColumnNode",
      column
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/foreign-key-constraint-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/foreign-key-constraint-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ForeignKeyConstraintNode = freeze({
  is(node) {
    return node.kind === "ForeignKeyConstraintNode";
  },
  create(sourceColumns, targetTable, targetColumns, constraintName) {
    return freeze({
      kind: "ForeignKeyConstraintNode",
      columns: sourceColumns,
      references: ReferencesNode.create(targetTable, targetColumns),
      name: constraintName ? IdentifierNode.create(constraintName) : void 0
    });
  },
  cloneWith(node, props) {
    return freeze({
      ...node,
      ...props
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/foreign-key-constraint-builder.js
var ForeignKeyConstraintBuilder = class _ForeignKeyConstraintBuilder {
  #node;
  constructor(node) {
    this.#node = node;
  }
  onDelete(onDelete) {
    return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, {
      onDelete: parseOnModifyForeignAction(onDelete)
    }));
  }
  onUpdate(onUpdate) {
    return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, {
      onUpdate: parseOnModifyForeignAction(onUpdate)
    }));
  }
  deferrable() {
    return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { deferrable: true }));
  }
  notDeferrable() {
    return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { deferrable: false }));
  }
  initiallyDeferred() {
    return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, {
      initiallyDeferred: true
    }));
  }
  initiallyImmediate() {
    return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, {
      initiallyDeferred: false
    }));
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#node;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/add-constraint-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var AddConstraintNode = freeze({
  is(node) {
    return node.kind === "AddConstraintNode";
  },
  create(constraint) {
    return freeze({
      kind: "AddConstraintNode",
      constraint
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/unique-constraint-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var UniqueConstraintNode = freeze({
  is(node) {
    return node.kind === "UniqueConstraintNode";
  },
  create(columns, constraintName, nullsNotDistinct) {
    return freeze({
      kind: "UniqueConstraintNode",
      columns: freeze(columns.map(ColumnNode.create)),
      name: constraintName ? IdentifierNode.create(constraintName) : void 0,
      nullsNotDistinct
    });
  },
  cloneWith(node, props) {
    return freeze({
      ...node,
      ...props
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/drop-constraint-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DropConstraintNode = freeze({
  is(node) {
    return node.kind === "DropConstraintNode";
  },
  create(constraintName) {
    return freeze({
      kind: "DropConstraintNode",
      constraintName: IdentifierNode.create(constraintName)
    });
  },
  cloneWith(dropConstraint, props) {
    return freeze({
      ...dropConstraint,
      ...props
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/alter-column-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/alter-column-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var AlterColumnNode = freeze({
  is(node) {
    return node.kind === "AlterColumnNode";
  },
  create(column, prop, value) {
    return freeze({
      kind: "AlterColumnNode",
      column: ColumnNode.create(column),
      [prop]: value
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/alter-column-builder.js
var AlterColumnBuilder = class {
  #column;
  constructor(column) {
    this.#column = column;
  }
  setDataType(dataType) {
    return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "dataType", parseDataTypeExpression(dataType)));
  }
  setDefault(value) {
    return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "setDefault", parseDefaultValueExpression(value)));
  }
  dropDefault() {
    return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "dropDefault", true));
  }
  setNotNull() {
    return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "setNotNull", true));
  }
  dropNotNull() {
    return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "dropNotNull", true));
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
};
var AlteredColumnBuilder = class {
  #alterColumnNode;
  constructor(alterColumnNode) {
    this.#alterColumnNode = alterColumnNode;
  }
  toOperationNode() {
    return this.#alterColumnNode;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/alter-table-executor.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var AlterTableExecutor = class {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  async execute() {
    await this.#props.executor.executeQuery(this.compile());
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/alter-table-add-foreign-key-constraint-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var AlterTableAddForeignKeyConstraintBuilder = class _AlterTableAddForeignKeyConstraintBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  onDelete(onDelete) {
    return new _AlterTableAddForeignKeyConstraintBuilder({
      ...this.#props,
      constraintBuilder: this.#props.constraintBuilder.onDelete(onDelete)
    });
  }
  onUpdate(onUpdate) {
    return new _AlterTableAddForeignKeyConstraintBuilder({
      ...this.#props,
      constraintBuilder: this.#props.constraintBuilder.onUpdate(onUpdate)
    });
  }
  deferrable() {
    return new _AlterTableAddForeignKeyConstraintBuilder({
      ...this.#props,
      constraintBuilder: this.#props.constraintBuilder.deferrable()
    });
  }
  notDeferrable() {
    return new _AlterTableAddForeignKeyConstraintBuilder({
      ...this.#props,
      constraintBuilder: this.#props.constraintBuilder.notDeferrable()
    });
  }
  initiallyDeferred() {
    return new _AlterTableAddForeignKeyConstraintBuilder({
      ...this.#props,
      constraintBuilder: this.#props.constraintBuilder.initiallyDeferred()
    });
  }
  initiallyImmediate() {
    return new _AlterTableAddForeignKeyConstraintBuilder({
      ...this.#props,
      constraintBuilder: this.#props.constraintBuilder.initiallyImmediate()
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(AlterTableNode.cloneWithTableProps(this.#props.node, {
      addConstraint: AddConstraintNode.create(this.#props.constraintBuilder.toOperationNode())
    }), this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  async execute() {
    await this.#props.executor.executeQuery(this.compile());
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/alter-table-drop-constraint-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var AlterTableDropConstraintBuilder = class _AlterTableDropConstraintBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  ifExists() {
    return new _AlterTableDropConstraintBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithTableProps(this.#props.node, {
        dropConstraint: DropConstraintNode.cloneWith(this.#props.node.dropConstraint, {
          ifExists: true
        })
      })
    });
  }
  cascade() {
    return new _AlterTableDropConstraintBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithTableProps(this.#props.node, {
        dropConstraint: DropConstraintNode.cloneWith(this.#props.node.dropConstraint, {
          modifier: "cascade"
        })
      })
    });
  }
  restrict() {
    return new _AlterTableDropConstraintBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithTableProps(this.#props.node, {
        dropConstraint: DropConstraintNode.cloneWith(this.#props.node.dropConstraint, {
          modifier: "restrict"
        })
      })
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  async execute() {
    await this.#props.executor.executeQuery(this.compile());
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/primary-key-constraint-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var PrimaryKeyConstraintNode = freeze({
  is(node) {
    return node.kind === "PrimaryKeyConstraintNode";
  },
  create(columns, constraintName) {
    return freeze({
      kind: "PrimaryKeyConstraintNode",
      columns: freeze(columns.map(ColumnNode.create)),
      name: constraintName ? IdentifierNode.create(constraintName) : void 0
    });
  },
  cloneWith(node, props) {
    return freeze({ ...node, ...props });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/add-index-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var AddIndexNode = freeze({
  is(node) {
    return node.kind === "AddIndexNode";
  },
  create(name) {
    return freeze({
      kind: "AddIndexNode",
      name: IdentifierNode.create(name)
    });
  },
  cloneWith(node, props) {
    return freeze({
      ...node,
      ...props
    });
  },
  cloneWithColumns(node, columns) {
    return freeze({
      ...node,
      columns: [...node.columns || [], ...columns]
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/alter-table-add-index-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var AlterTableAddIndexBuilder = class _AlterTableAddIndexBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  /**
   * Makes the index unique.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .alterTable('person')
   *   .addIndex('person_first_name_index')
   *   .unique()
   *   .column('email')
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * alter table `person` add unique index `person_first_name_index` (`email`)
   * ```
   */
  unique() {
    return new _AlterTableAddIndexBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithTableProps(this.#props.node, {
        addIndex: AddIndexNode.cloneWith(this.#props.node.addIndex, {
          unique: true
        })
      })
    });
  }
  /**
   * Adds a column to the index.
   *
   * Also see {@link columns} for adding multiple columns at once or {@link expression}
   * for specifying an arbitrary expression.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .alterTable('person')
   *   .addIndex('person_first_name_and_age_index')
   *   .column('first_name')
   *   .column('age desc')
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * alter table `person` add index `person_first_name_and_age_index` (`first_name`, `age` desc)
   * ```
   */
  column(column) {
    return new _AlterTableAddIndexBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithTableProps(this.#props.node, {
        addIndex: AddIndexNode.cloneWithColumns(this.#props.node.addIndex, [
          parseOrderedColumnName(column)
        ])
      })
    });
  }
  /**
   * Specifies a list of columns for the index.
   *
   * Also see {@link column} for adding a single column or {@link expression} for
   * specifying an arbitrary expression.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .alterTable('person')
   *   .addIndex('person_first_name_and_age_index')
   *   .columns(['first_name', 'age desc'])
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * alter table `person` add index `person_first_name_and_age_index` (`first_name`, `age` desc)
   * ```
   */
  columns(columns) {
    return new _AlterTableAddIndexBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithTableProps(this.#props.node, {
        addIndex: AddIndexNode.cloneWithColumns(this.#props.node.addIndex, columns.map(parseOrderedColumnName))
      })
    });
  }
  /**
   * Specifies an arbitrary expression for the index.
   *
   * ### Examples
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db.schema
   *   .alterTable('person')
   *   .addIndex('person_first_name_index')
   *   .expression(sql<boolean>`(first_name < 'Sami')`)
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * alter table `person` add index `person_first_name_index` ((first_name < 'Sami'))
   * ```
   */
  expression(expression) {
    return new _AlterTableAddIndexBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithTableProps(this.#props.node, {
        addIndex: AddIndexNode.cloneWithColumns(this.#props.node.addIndex, [
          expression.toOperationNode()
        ])
      })
    });
  }
  using(indexType) {
    return new _AlterTableAddIndexBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithTableProps(this.#props.node, {
        addIndex: AddIndexNode.cloneWith(this.#props.node.addIndex, {
          using: RawNode.createWithSql(indexType)
        })
      })
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  async execute() {
    await this.#props.executor.executeQuery(this.compile());
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/unique-constraint-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var UniqueConstraintNodeBuilder = class _UniqueConstraintNodeBuilder {
  #node;
  constructor(node) {
    this.#node = node;
  }
  /**
   * Adds `nulls not distinct` to the unique constraint definition
   *
   * Supported by PostgreSQL dialect only
   */
  nullsNotDistinct() {
    return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { nullsNotDistinct: true }));
  }
  deferrable() {
    return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { deferrable: true }));
  }
  notDeferrable() {
    return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { deferrable: false }));
  }
  initiallyDeferred() {
    return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, {
      initiallyDeferred: true
    }));
  }
  initiallyImmediate() {
    return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, {
      initiallyDeferred: false
    }));
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#node;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/primary-key-constraint-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var PrimaryKeyConstraintBuilder = class _PrimaryKeyConstraintBuilder {
  #node;
  constructor(node) {
    this.#node = node;
  }
  deferrable() {
    return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, { deferrable: true }));
  }
  notDeferrable() {
    return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, { deferrable: false }));
  }
  initiallyDeferred() {
    return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, {
      initiallyDeferred: true
    }));
  }
  initiallyImmediate() {
    return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, {
      initiallyDeferred: false
    }));
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#node;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/check-constraint-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var CheckConstraintBuilder = class {
  #node;
  constructor(node) {
    this.#node = node;
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#node;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/rename-constraint-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var RenameConstraintNode = freeze({
  is(node) {
    return node.kind === "RenameConstraintNode";
  },
  create(oldName, newName) {
    return freeze({
      kind: "RenameConstraintNode",
      oldName: IdentifierNode.create(oldName),
      newName: IdentifierNode.create(newName)
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/alter-table-builder.js
var AlterTableBuilder = class {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  renameTo(newTableName) {
    return new AlterTableExecutor({
      ...this.#props,
      node: AlterTableNode.cloneWithTableProps(this.#props.node, {
        renameTo: parseTable(newTableName)
      })
    });
  }
  setSchema(newSchema) {
    return new AlterTableExecutor({
      ...this.#props,
      node: AlterTableNode.cloneWithTableProps(this.#props.node, {
        setSchema: IdentifierNode.create(newSchema)
      })
    });
  }
  alterColumn(column, alteration) {
    const builder = alteration(new AlterColumnBuilder(column));
    return new AlterTableColumnAlteringBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, builder.toOperationNode())
    });
  }
  dropColumn(column) {
    return new AlterTableColumnAlteringBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, DropColumnNode.create(column))
    });
  }
  renameColumn(column, newColumn) {
    return new AlterTableColumnAlteringBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, RenameColumnNode.create(column, newColumn))
    });
  }
  addColumn(columnName, dataType, build2 = noop) {
    const builder = build2(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));
    return new AlterTableColumnAlteringBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, AddColumnNode.create(builder.toOperationNode()))
    });
  }
  modifyColumn(columnName, dataType, build2 = noop) {
    const builder = build2(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));
    return new AlterTableColumnAlteringBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, ModifyColumnNode.create(builder.toOperationNode()))
    });
  }
  /**
   * See {@link CreateTableBuilder.addUniqueConstraint}
   */
  addUniqueConstraint(constraintName, columns, build2 = noop) {
    const uniqueConstraintBuilder = build2(new UniqueConstraintNodeBuilder(UniqueConstraintNode.create(columns, constraintName)));
    return new AlterTableExecutor({
      ...this.#props,
      node: AlterTableNode.cloneWithTableProps(this.#props.node, {
        addConstraint: AddConstraintNode.create(uniqueConstraintBuilder.toOperationNode())
      })
    });
  }
  /**
   * See {@link CreateTableBuilder.addCheckConstraint}
   */
  addCheckConstraint(constraintName, checkExpression, build2 = noop) {
    const constraintBuilder = build2(new CheckConstraintBuilder(CheckConstraintNode.create(checkExpression.toOperationNode(), constraintName)));
    return new AlterTableExecutor({
      ...this.#props,
      node: AlterTableNode.cloneWithTableProps(this.#props.node, {
        addConstraint: AddConstraintNode.create(constraintBuilder.toOperationNode())
      })
    });
  }
  /**
   * See {@link CreateTableBuilder.addForeignKeyConstraint}
   *
   * Unlike {@link CreateTableBuilder.addForeignKeyConstraint} this method returns
   * the constraint builder and doesn't take a callback as the last argument. This
   * is because you can only add one column per `ALTER TABLE` query.
   */
  addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build2 = noop) {
    const constraintBuilder = build2(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(columns.map(ColumnNode.create), parseTable(targetTable), targetColumns.map(ColumnNode.create), constraintName)));
    return new AlterTableAddForeignKeyConstraintBuilder({
      ...this.#props,
      constraintBuilder
    });
  }
  /**
   * See {@link CreateTableBuilder.addPrimaryKeyConstraint}
   */
  addPrimaryKeyConstraint(constraintName, columns, build2 = noop) {
    const constraintBuilder = build2(new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.create(columns, constraintName)));
    return new AlterTableExecutor({
      ...this.#props,
      node: AlterTableNode.cloneWithTableProps(this.#props.node, {
        addConstraint: AddConstraintNode.create(constraintBuilder.toOperationNode())
      })
    });
  }
  dropConstraint(constraintName) {
    return new AlterTableDropConstraintBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithTableProps(this.#props.node, {
        dropConstraint: DropConstraintNode.create(constraintName)
      })
    });
  }
  renameConstraint(oldName, newName) {
    return new AlterTableDropConstraintBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithTableProps(this.#props.node, {
        renameConstraint: RenameConstraintNode.create(oldName, newName)
      })
    });
  }
  /**
   * This can be used to add index to table.
   *
   *  ### Examples
   *
   * ```ts
   * db.schema.alterTable('person')
   *   .addIndex('person_email_index')
   *   .column('email')
   *   .unique()
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * alter table `person` add unique index `person_email_index` (`email`)
   * ```
   */
  addIndex(indexName) {
    return new AlterTableAddIndexBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithTableProps(this.#props.node, {
        addIndex: AddIndexNode.create(indexName)
      })
    });
  }
  /**
   * This can be used to drop index from table.
   *
   * ### Examples
   *
   * ```ts
   * db.schema.alterTable('person')
   *   .dropIndex('person_email_index')
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * alter table `person` drop index `test_first_name_index`
   * ```
   */
  dropIndex(indexName) {
    return new AlterTableExecutor({
      ...this.#props,
      node: AlterTableNode.cloneWithTableProps(this.#props.node, {
        dropIndex: DropIndexNode.create(indexName)
      })
    });
  }
  /**
   * Calls the given function passing `this` as the only argument.
   *
   * See {@link CreateTableBuilder.$call}
   */
  $call(func) {
    return func(this);
  }
};
var AlterTableColumnAlteringBuilder = class _AlterTableColumnAlteringBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  alterColumn(column, alteration) {
    const builder = alteration(new AlterColumnBuilder(column));
    return new _AlterTableColumnAlteringBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, builder.toOperationNode())
    });
  }
  dropColumn(column) {
    return new _AlterTableColumnAlteringBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, DropColumnNode.create(column))
    });
  }
  renameColumn(column, newColumn) {
    return new _AlterTableColumnAlteringBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, RenameColumnNode.create(column, newColumn))
    });
  }
  addColumn(columnName, dataType, build2 = noop) {
    const builder = build2(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));
    return new _AlterTableColumnAlteringBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, AddColumnNode.create(builder.toOperationNode()))
    });
  }
  modifyColumn(columnName, dataType, build2 = noop) {
    const builder = build2(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));
    return new _AlterTableColumnAlteringBuilder({
      ...this.#props,
      node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, ModifyColumnNode.create(builder.toOperationNode()))
    });
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  async execute() {
    await this.#props.executor.executeQuery(this.compile());
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/create-index-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-transformer.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ImmediateValueTransformer = class extends OperationNodeTransformer {
  transformPrimitiveValueList(node) {
    return ValueListNode.create(node.values.map(ValueNode.createImmediate));
  }
  transformValue(node) {
    return ValueNode.createImmediate(node.value);
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/create-index-builder.js
var CreateIndexBuilder = class _CreateIndexBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  /**
   * Adds the "if not exists" modifier.
   *
   * If the index already exists, no error is thrown if this method has been called.
   */
  ifNotExists() {
    return new _CreateIndexBuilder({
      ...this.#props,
      node: CreateIndexNode.cloneWith(this.#props.node, {
        ifNotExists: true
      })
    });
  }
  /**
   * Makes the index unique.
   */
  unique() {
    return new _CreateIndexBuilder({
      ...this.#props,
      node: CreateIndexNode.cloneWith(this.#props.node, {
        unique: true
      })
    });
  }
  /**
   * Adds `nulls not distinct` specifier to index.
   * This only works on some dialects like PostgreSQL.
   *
   * ### Examples
   *
   * ```ts
   * db.schema.createIndex('person_first_name_index')
   *  .on('person')
   *  .column('first_name')
   *  .nullsNotDistinct()
   *  .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * create index "person_first_name_index"
   * on "test" ("first_name")
   * nulls not distinct;
   * ```
   */
  nullsNotDistinct() {
    return new _CreateIndexBuilder({
      ...this.#props,
      node: CreateIndexNode.cloneWith(this.#props.node, {
        nullsNotDistinct: true
      })
    });
  }
  /**
   * Specifies the table for the index.
   */
  on(table) {
    return new _CreateIndexBuilder({
      ...this.#props,
      node: CreateIndexNode.cloneWith(this.#props.node, {
        table: parseTable(table)
      })
    });
  }
  /**
   * Adds a column to the index.
   *
   * Also see {@link columns} for adding multiple columns at once or {@link expression}
   * for specifying an arbitrary expression.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *         .createIndex('person_first_name_and_age_index')
   *         .on('person')
   *         .column('first_name')
   *         .column('age desc')
   *         .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * create index "person_first_name_and_age_index" on "person" ("first_name", "age" desc)
   * ```
   */
  column(column) {
    return new _CreateIndexBuilder({
      ...this.#props,
      node: CreateIndexNode.cloneWithColumns(this.#props.node, [
        parseOrderedColumnName(column)
      ])
    });
  }
  /**
   * Specifies a list of columns for the index.
   *
   * Also see {@link column} for adding a single column or {@link expression} for
   * specifying an arbitrary expression.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *         .createIndex('person_first_name_and_age_index')
   *         .on('person')
   *         .columns(['first_name', 'age desc'])
   *         .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * create index "person_first_name_and_age_index" on "person" ("first_name", "age" desc)
   * ```
   */
  columns(columns) {
    return new _CreateIndexBuilder({
      ...this.#props,
      node: CreateIndexNode.cloneWithColumns(this.#props.node, columns.map(parseOrderedColumnName))
    });
  }
  /**
   * Specifies an arbitrary expression for the index.
   *
   * ### Examples
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db.schema
   *   .createIndex('person_first_name_index')
   *   .on('person')
   *   .expression(sql`first_name COLLATE "fi_FI"`)
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * create index "person_first_name_index" on "person" (first_name COLLATE "fi_FI")
   * ```
   */
  expression(expression) {
    return new _CreateIndexBuilder({
      ...this.#props,
      node: CreateIndexNode.cloneWithColumns(this.#props.node, [
        expression.toOperationNode()
      ])
    });
  }
  using(indexType) {
    return new _CreateIndexBuilder({
      ...this.#props,
      node: CreateIndexNode.cloneWith(this.#props.node, {
        using: RawNode.createWithSql(indexType)
      })
    });
  }
  where(...args) {
    const transformer = new ImmediateValueTransformer();
    return new _CreateIndexBuilder({
      ...this.#props,
      node: QueryNode.cloneWithWhere(this.#props.node, transformer.transformNode(parseValueBinaryOperationOrExpression(args), this.#props.queryId))
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  async execute() {
    await this.#props.executor.executeQuery(this.compile());
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/create-schema-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var CreateSchemaBuilder = class _CreateSchemaBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  ifNotExists() {
    return new _CreateSchemaBuilder({
      ...this.#props,
      node: CreateSchemaNode.cloneWith(this.#props.node, { ifNotExists: true })
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  async execute() {
    await this.#props.executor.executeQuery(this.compile());
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/create-table-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/on-commit-action-parse.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function parseOnCommitAction(action) {
  if (ON_COMMIT_ACTIONS.includes(action)) {
    return action;
  }
  throw new Error(`invalid OnCommitAction ${action}`);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/create-table-builder.js
var CreateTableBuilder = class _CreateTableBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  /**
   * Adds the "temporary" modifier.
   *
   * Use this to create a temporary table.
   */
  temporary() {
    return new _CreateTableBuilder({
      ...this.#props,
      node: CreateTableNode.cloneWith(this.#props.node, {
        temporary: true
      })
    });
  }
  /**
   * Adds an "on commit" statement.
   *
   * This can be used in conjunction with temporary tables on supported databases
   * like PostgreSQL.
   */
  onCommit(onCommit) {
    return new _CreateTableBuilder({
      ...this.#props,
      node: CreateTableNode.cloneWith(this.#props.node, {
        onCommit: parseOnCommitAction(onCommit)
      })
    });
  }
  /**
   * Adds the "if not exists" modifier.
   *
   * If the table already exists, no error is thrown if this method has been called.
   */
  ifNotExists() {
    return new _CreateTableBuilder({
      ...this.#props,
      node: CreateTableNode.cloneWith(this.#props.node, {
        ifNotExists: true
      })
    });
  }
  /**
   * Adds a column to the table.
   *
   * ### Examples
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db.schema
   *   .createTable('person')
   *   .addColumn('id', 'integer', (col) => col.autoIncrement().primaryKey())
   *   .addColumn('first_name', 'varchar(50)', (col) => col.notNull())
   *   .addColumn('last_name', 'varchar(255)')
   *   .addColumn('bank_balance', 'numeric(8, 2)')
   *   // You can specify any data type using the `sql` tag if the types
   *   // don't include it.
   *   .addColumn('data', sql`any_type_here`)
   *   .addColumn('parent_id', 'integer', (col) =>
   *     col.references('person.id').onDelete('cascade')
   *   )
   * ```
   *
   * With this method, it's once again good to remember that Kysely just builds the
   * query and doesn't provide the same API for all databases. For example, some
   * databases like older MySQL don't support the `references` statement in the
   * column definition. Instead foreign key constraints need to be defined in the
   * `create table` query. See the next example:
   *
   * ```ts
   * await db.schema
   *   .createTable('person')
   *   .addColumn('id', 'integer', (col) => col.primaryKey())
   *   .addColumn('parent_id', 'integer')
   *   .addForeignKeyConstraint(
   *     'person_parent_id_fk',
   *     ['parent_id'],
   *     'person',
   *     ['id'],
   *     (cb) => cb.onDelete('cascade')
   *   )
   *   .execute()
   * ```
   *
   * Another good example is that PostgreSQL doesn't support the `auto_increment`
   * keyword and you need to define an autoincrementing column for example using
   * `serial`:
   *
   * ```ts
   * await db.schema
   *   .createTable('person')
   *   .addColumn('id', 'serial', (col) => col.primaryKey())
   *   .execute()
   * ```
   */
  addColumn(columnName, dataType, build2 = noop) {
    const columnBuilder = build2(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));
    return new _CreateTableBuilder({
      ...this.#props,
      node: CreateTableNode.cloneWithColumn(this.#props.node, columnBuilder.toOperationNode())
    });
  }
  /**
   * Adds a primary key constraint for one or more columns.
   *
   * The constraint name can be anything you want, but it must be unique
   * across the whole database.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createTable('person')
   *   .addColumn('first_name', 'varchar(64)')
   *   .addColumn('last_name', 'varchar(64)')
   *   .addPrimaryKeyConstraint('primary_key', ['first_name', 'last_name'])
   *   .execute()
   * ```
   */
  addPrimaryKeyConstraint(constraintName, columns, build2 = noop) {
    const constraintBuilder = build2(new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.create(columns, constraintName)));
    return new _CreateTableBuilder({
      ...this.#props,
      node: CreateTableNode.cloneWithConstraint(this.#props.node, constraintBuilder.toOperationNode())
    });
  }
  /**
   * Adds a unique constraint for one or more columns.
   *
   * The constraint name can be anything you want, but it must be unique
   * across the whole database.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createTable('person')
   *   .addColumn('first_name', 'varchar(64)')
   *   .addColumn('last_name', 'varchar(64)')
   *   .addUniqueConstraint(
   *     'first_name_last_name_unique',
   *     ['first_name', 'last_name']
   *   )
   *   .execute()
   * ```
   *
   * In dialects such as PostgreSQL you can specify `nulls not distinct` as follows:
   *
   * ```ts
   * await db.schema
   *   .createTable('person')
   *   .addColumn('first_name', 'varchar(64)')
   *   .addColumn('last_name', 'varchar(64)')
   *   .addUniqueConstraint(
   *     'first_name_last_name_unique',
   *     ['first_name', 'last_name'],
   *     (cb) => cb.nullsNotDistinct()
   *   )
   *   .execute()
   * ```
   */
  addUniqueConstraint(constraintName, columns, build2 = noop) {
    const uniqueConstraintBuilder = build2(new UniqueConstraintNodeBuilder(UniqueConstraintNode.create(columns, constraintName)));
    return new _CreateTableBuilder({
      ...this.#props,
      node: CreateTableNode.cloneWithConstraint(this.#props.node, uniqueConstraintBuilder.toOperationNode())
    });
  }
  /**
   * Adds a check constraint.
   *
   * The constraint name can be anything you want, but it must be unique
   * across the whole database.
   *
   * ### Examples
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db.schema
   *   .createTable('animal')
   *   .addColumn('number_of_legs', 'integer')
   *   .addCheckConstraint('check_legs', sql`number_of_legs < 5`)
   *   .execute()
   * ```
   */
  addCheckConstraint(constraintName, checkExpression, build2 = noop) {
    const constraintBuilder = build2(new CheckConstraintBuilder(CheckConstraintNode.create(checkExpression.toOperationNode(), constraintName)));
    return new _CreateTableBuilder({
      ...this.#props,
      node: CreateTableNode.cloneWithConstraint(this.#props.node, constraintBuilder.toOperationNode())
    });
  }
  /**
   * Adds a foreign key constraint.
   *
   * The constraint name can be anything you want, but it must be unique
   * across the whole database.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createTable('pet')
   *   .addColumn('owner_id', 'integer')
   *   .addForeignKeyConstraint(
   *     'owner_id_foreign',
   *     ['owner_id'],
   *     'person',
   *     ['id'],
   *   )
   *   .execute()
   * ```
   *
   * Add constraint for multiple columns:
   *
   * ```ts
   * await db.schema
   *   .createTable('pet')
   *   .addColumn('owner_id1', 'integer')
   *   .addColumn('owner_id2', 'integer')
   *   .addForeignKeyConstraint(
   *     'owner_id_foreign',
   *     ['owner_id1', 'owner_id2'],
   *     'person',
   *     ['id1', 'id2'],
   *     (cb) => cb.onDelete('cascade')
   *   )
   *   .execute()
   * ```
   */
  addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build2 = noop) {
    const builder = build2(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(columns.map(ColumnNode.create), parseTable(targetTable), targetColumns.map(ColumnNode.create), constraintName)));
    return new _CreateTableBuilder({
      ...this.#props,
      node: CreateTableNode.cloneWithConstraint(this.#props.node, builder.toOperationNode())
    });
  }
  /**
   * This can be used to add any additional SQL to the front of the query __after__ the `create` keyword.
   *
   * Also see {@link temporary}.
   *
   * ### Examples
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db.schema
   *   .createTable('person')
   *   .modifyFront(sql`global temporary`)
   *   .addColumn('id', 'integer', col => col.primaryKey())
   *   .addColumn('first_name', 'varchar(64)', col => col.notNull())
   *   .addColumn('last_name', 'varchar(64)', col => col.notNull())
   *   .execute()
   * ```
   *
   * The generated SQL (Postgres):
   *
   * ```sql
   * create global temporary table "person" (
   *   "id" integer primary key,
   *   "first_name" varchar(64) not null,
   *   "last_name" varchar(64) not null
   * )
   * ```
   */
  modifyFront(modifier) {
    return new _CreateTableBuilder({
      ...this.#props,
      node: CreateTableNode.cloneWithFrontModifier(this.#props.node, modifier.toOperationNode())
    });
  }
  /**
   * This can be used to add any additional SQL to the end of the query.
   *
   * Also see {@link onCommit}.
   *
   * ### Examples
   *
   * ```ts
   * import { sql } from 'kysely'
   *
   * await db.schema
   *   .createTable('person')
   *   .addColumn('id', 'integer', col => col.primaryKey())
   *   .addColumn('first_name', 'varchar(64)', col => col.notNull())
   *   .addColumn('last_name', 'varchar(64)', col => col.notNull())
   *   .modifyEnd(sql`collate utf8_unicode_ci`)
   *   .execute()
   * ```
   *
   * The generated SQL (MySQL):
   *
   * ```sql
   * create table `person` (
   *   `id` integer primary key,
   *   `first_name` varchar(64) not null,
   *   `last_name` varchar(64) not null
   * ) collate utf8_unicode_ci
   * ```
   */
  modifyEnd(modifier) {
    return new _CreateTableBuilder({
      ...this.#props,
      node: CreateTableNode.cloneWithEndModifier(this.#props.node, modifier.toOperationNode())
    });
  }
  /**
   * Allows to create table from `select` query.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createTable('copy')
   *   .temporary()
   *   .as(db.selectFrom('person').select(['first_name', 'last_name']))
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * create temporary table "copy" as
   * select "first_name", "last_name" from "person"
   * ```
   */
  as(expression) {
    return new _CreateTableBuilder({
      ...this.#props,
      node: CreateTableNode.cloneWith(this.#props.node, {
        selectQuery: parseExpression(expression)
      })
    });
  }
  /**
   * Calls the given function passing `this` as the only argument.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createTable('test')
   *   .$call((builder) => builder.addColumn('id', 'integer'))
   *   .execute()
   * ```
   *
   * This is useful for creating reusable functions that can be called with a builder.
   *
   * ```ts
   * import { type CreateTableBuilder, sql } from 'kysely'
   *
   * const addDefaultColumns = (ctb: CreateTableBuilder<any, any>) => {
   *   return ctb
   *     .addColumn('id', 'integer', (col) => col.notNull())
   *     .addColumn('created_at', 'date', (col) =>
   *       col.notNull().defaultTo(sql`now()`)
   *     )
   *     .addColumn('updated_at', 'date', (col) =>
   *       col.notNull().defaultTo(sql`now()`)
   *     )
   * }
   *
   * await db.schema
   *   .createTable('test')
   *   .$call(addDefaultColumns)
   *   .execute()
   * ```
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  async execute() {
    await this.#props.executor.executeQuery(this.compile());
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/drop-index-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DropIndexBuilder = class _DropIndexBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  /**
   * Specifies the table the index was created for. This is not needed
   * in all dialects.
   */
  on(table) {
    return new _DropIndexBuilder({
      ...this.#props,
      node: DropIndexNode.cloneWith(this.#props.node, {
        table: parseTable(table)
      })
    });
  }
  ifExists() {
    return new _DropIndexBuilder({
      ...this.#props,
      node: DropIndexNode.cloneWith(this.#props.node, {
        ifExists: true
      })
    });
  }
  cascade() {
    return new _DropIndexBuilder({
      ...this.#props,
      node: DropIndexNode.cloneWith(this.#props.node, {
        cascade: true
      })
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  async execute() {
    await this.#props.executor.executeQuery(this.compile());
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/drop-schema-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DropSchemaBuilder = class _DropSchemaBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  ifExists() {
    return new _DropSchemaBuilder({
      ...this.#props,
      node: DropSchemaNode.cloneWith(this.#props.node, {
        ifExists: true
      })
    });
  }
  cascade() {
    return new _DropSchemaBuilder({
      ...this.#props,
      node: DropSchemaNode.cloneWith(this.#props.node, {
        cascade: true
      })
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  async execute() {
    await this.#props.executor.executeQuery(this.compile());
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/drop-table-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DropTableBuilder = class _DropTableBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  ifExists() {
    return new _DropTableBuilder({
      ...this.#props,
      node: DropTableNode.cloneWith(this.#props.node, {
        ifExists: true
      })
    });
  }
  cascade() {
    return new _DropTableBuilder({
      ...this.#props,
      node: DropTableNode.cloneWith(this.#props.node, {
        cascade: true
      })
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  async execute() {
    await this.#props.executor.executeQuery(this.compile());
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/create-view-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/create-view-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var CreateViewNode = freeze({
  is(node) {
    return node.kind === "CreateViewNode";
  },
  create(name) {
    return freeze({
      kind: "CreateViewNode",
      name: SchemableIdentifierNode.create(name)
    });
  },
  cloneWith(createView, params) {
    return freeze({
      ...createView,
      ...params
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-plugin.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ImmediateValuePlugin = class {
  #transformer = new ImmediateValueTransformer();
  transformQuery(args) {
    return this.#transformer.transformNode(args.node, args.queryId);
  }
  transformResult(args) {
    return Promise.resolve(args.result);
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/create-view-builder.js
var CreateViewBuilder = class _CreateViewBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  /**
   * Adds the "temporary" modifier.
   *
   * Use this to create a temporary view.
   */
  temporary() {
    return new _CreateViewBuilder({
      ...this.#props,
      node: CreateViewNode.cloneWith(this.#props.node, {
        temporary: true
      })
    });
  }
  materialized() {
    return new _CreateViewBuilder({
      ...this.#props,
      node: CreateViewNode.cloneWith(this.#props.node, {
        materialized: true
      })
    });
  }
  /**
   * Only implemented on some dialects like SQLite. On most dialects, use {@link orReplace}.
   */
  ifNotExists() {
    return new _CreateViewBuilder({
      ...this.#props,
      node: CreateViewNode.cloneWith(this.#props.node, {
        ifNotExists: true
      })
    });
  }
  orReplace() {
    return new _CreateViewBuilder({
      ...this.#props,
      node: CreateViewNode.cloneWith(this.#props.node, {
        orReplace: true
      })
    });
  }
  columns(columns) {
    return new _CreateViewBuilder({
      ...this.#props,
      node: CreateViewNode.cloneWith(this.#props.node, {
        columns: columns.map(parseColumnName)
      })
    });
  }
  /**
   * Sets the select query or a `values` statement that creates the view.
   *
   * WARNING!
   * Some dialects don't support parameterized queries in DDL statements and therefore
   * the query or raw {@link sql } expression passed here is interpolated into a single
   * string opening an SQL injection vulnerability. DO NOT pass unchecked user input
   * into the query or raw expression passed to this method!
   */
  as(query) {
    const queryNode = query.withPlugin(new ImmediateValuePlugin()).toOperationNode();
    return new _CreateViewBuilder({
      ...this.#props,
      node: CreateViewNode.cloneWith(this.#props.node, {
        as: queryNode
      })
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  async execute() {
    await this.#props.executor.executeQuery(this.compile());
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/drop-view-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/drop-view-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DropViewNode = freeze({
  is(node) {
    return node.kind === "DropViewNode";
  },
  create(name) {
    return freeze({
      kind: "DropViewNode",
      name: SchemableIdentifierNode.create(name)
    });
  },
  cloneWith(dropView, params) {
    return freeze({
      ...dropView,
      ...params
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/drop-view-builder.js
var DropViewBuilder = class _DropViewBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  materialized() {
    return new _DropViewBuilder({
      ...this.#props,
      node: DropViewNode.cloneWith(this.#props.node, {
        materialized: true
      })
    });
  }
  ifExists() {
    return new _DropViewBuilder({
      ...this.#props,
      node: DropViewNode.cloneWith(this.#props.node, {
        ifExists: true
      })
    });
  }
  cascade() {
    return new _DropViewBuilder({
      ...this.#props,
      node: DropViewNode.cloneWith(this.#props.node, {
        cascade: true
      })
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  async execute() {
    await this.#props.executor.executeQuery(this.compile());
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/create-type-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/create-type-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var CreateTypeNode = freeze({
  is(node) {
    return node.kind === "CreateTypeNode";
  },
  create(name) {
    return freeze({
      kind: "CreateTypeNode",
      name
    });
  },
  cloneWithEnum(createType, values) {
    return freeze({
      ...createType,
      enum: ValueListNode.create(values.map(ValueNode.createImmediate))
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/create-type-builder.js
var CreateTypeBuilder = class _CreateTypeBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
  }
  /**
   * Creates an anum type.
   *
   * ### Examples
   *
   * ```ts
   * db.schema.createType('species').asEnum(['cat', 'dog', 'frog'])
   * ```
   */
  asEnum(values) {
    return new _CreateTypeBuilder({
      ...this.#props,
      node: CreateTypeNode.cloneWithEnum(this.#props.node, values)
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  async execute() {
    await this.#props.executor.executeQuery(this.compile());
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/drop-type-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/drop-type-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DropTypeNode = freeze({
  is(node) {
    return node.kind === "DropTypeNode";
  },
  create(name) {
    return freeze({
      kind: "DropTypeNode",
      name
    });
  },
  cloneWith(dropType, params) {
    return freeze({
      ...dropType,
      ...params
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/drop-type-builder.js
var DropTypeBuilder = class _DropTypeBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  ifExists() {
    return new _DropTypeBuilder({
      ...this.#props,
      node: DropTypeNode.cloneWith(this.#props.node, {
        ifExists: true
      })
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  async execute() {
    await this.#props.executor.executeQuery(this.compile());
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/parser/identifier-parser.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function parseSchemableIdentifier(id) {
  const SCHEMA_SEPARATOR = ".";
  if (id.includes(SCHEMA_SEPARATOR)) {
    const parts = id.split(SCHEMA_SEPARATOR).map(trim3);
    if (parts.length === 2) {
      return SchemableIdentifierNode.createWithSchema(parts[0], parts[1]);
    } else {
      throw new Error(`invalid schemable identifier ${id}`);
    }
  } else {
    return SchemableIdentifierNode.create(id);
  }
}
function trim3(str) {
  return str.trim();
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/refresh-materialized-view-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/refresh-materialized-view-node.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var RefreshMaterializedViewNode = freeze({
  is(node) {
    return node.kind === "RefreshMaterializedViewNode";
  },
  create(name) {
    return freeze({
      kind: "RefreshMaterializedViewNode",
      name: SchemableIdentifierNode.create(name)
    });
  },
  cloneWith(createView, params) {
    return freeze({
      ...createView,
      ...params
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/refresh-materialized-view-builder.js
var RefreshMaterializedViewBuilder = class _RefreshMaterializedViewBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  /**
   * Adds the "concurrently" modifier.
   *
   * Use this to refresh the view without locking out concurrent selects on the materialized view.
   *
   * WARNING!
   * This cannot be used with the "with no data" modifier.
   */
  concurrently() {
    return new _RefreshMaterializedViewBuilder({
      ...this.#props,
      node: RefreshMaterializedViewNode.cloneWith(this.#props.node, {
        concurrently: true,
        withNoData: false
      })
    });
  }
  /**
   * Adds the "with data" modifier.
   *
   * If specified (or defaults) the backing query is executed to provide the new data, and the materialized view is left in a scannable state
   */
  withData() {
    return new _RefreshMaterializedViewBuilder({
      ...this.#props,
      node: RefreshMaterializedViewNode.cloneWith(this.#props.node, {
        withNoData: false
      })
    });
  }
  /**
   * Adds the "with no data" modifier.
   *
   * If specified, no new data is generated and the materialized view is left in an unscannable state.
   *
   * WARNING!
   * This cannot be used with the "concurrently" modifier.
   */
  withNoData() {
    return new _RefreshMaterializedViewBuilder({
      ...this.#props,
      node: RefreshMaterializedViewNode.cloneWith(this.#props.node, {
        withNoData: true,
        concurrently: false
      })
    });
  }
  /**
   * Simply calls the provided function passing `this` as the only argument. `$call` returns
   * what the provided function returns.
   */
  $call(func) {
    return func(this);
  }
  toOperationNode() {
    return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
  }
  compile() {
    return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
  }
  async execute() {
    await this.#props.executor.executeQuery(this.compile());
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/schema/schema.js
var SchemaModule = class _SchemaModule {
  #executor;
  constructor(executor) {
    this.#executor = executor;
  }
  /**
   * Create a new table.
   *
   * ### Examples
   *
   * This example creates a new table with columns `id`, `first_name`,
   * `last_name` and `gender`:
   *
   * ```ts
   * await db.schema
   *   .createTable('person')
   *   .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
   *   .addColumn('first_name', 'varchar', col => col.notNull())
   *   .addColumn('last_name', 'varchar', col => col.notNull())
   *   .addColumn('gender', 'varchar')
   *   .execute()
   * ```
   *
   * This example creates a table with a foreign key. Not all database
   * engines support column-level foreign key constraint definitions.
   * For example if you are using MySQL 5.X see the next example after
   * this one.
   *
   * ```ts
   * await db.schema
   *   .createTable('pet')
   *   .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
   *   .addColumn('owner_id', 'integer', col => col
   *     .references('person.id')
   *     .onDelete('cascade')
   *   )
   *   .execute()
   * ```
   *
   * This example adds a foreign key constraint for a columns just
   * like the previous example, but using a table-level statement.
   * On MySQL 5.X you need to define foreign key constraints like
   * this:
   *
   * ```ts
   * await db.schema
   *   .createTable('pet')
   *   .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
   *   .addColumn('owner_id', 'integer')
   *   .addForeignKeyConstraint(
   *     'pet_owner_id_foreign', ['owner_id'], 'person', ['id'],
   *     (constraint) => constraint.onDelete('cascade')
   *   )
   *   .execute()
   * ```
   */
  createTable(table) {
    return new CreateTableBuilder({
      queryId: createQueryId(),
      executor: this.#executor,
      node: CreateTableNode.create(parseTable(table))
    });
  }
  /**
   * Drop a table.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .dropTable('person')
   *   .execute()
   * ```
   */
  dropTable(table) {
    return new DropTableBuilder({
      queryId: createQueryId(),
      executor: this.#executor,
      node: DropTableNode.create(parseTable(table))
    });
  }
  /**
   * Create a new index.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createIndex('person_full_name_unique_index')
   *   .on('person')
   *   .columns(['first_name', 'last_name'])
   *   .execute()
   * ```
   */
  createIndex(indexName) {
    return new CreateIndexBuilder({
      queryId: createQueryId(),
      executor: this.#executor,
      node: CreateIndexNode.create(indexName)
    });
  }
  /**
   * Drop an index.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .dropIndex('person_full_name_unique_index')
   *   .execute()
   * ```
   */
  dropIndex(indexName) {
    return new DropIndexBuilder({
      queryId: createQueryId(),
      executor: this.#executor,
      node: DropIndexNode.create(indexName)
    });
  }
  /**
   * Create a new schema.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createSchema('some_schema')
   *   .execute()
   * ```
   */
  createSchema(schema) {
    return new CreateSchemaBuilder({
      queryId: createQueryId(),
      executor: this.#executor,
      node: CreateSchemaNode.create(schema)
    });
  }
  /**
   * Drop a schema.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .dropSchema('some_schema')
   *   .execute()
   * ```
   */
  dropSchema(schema) {
    return new DropSchemaBuilder({
      queryId: createQueryId(),
      executor: this.#executor,
      node: DropSchemaNode.create(schema)
    });
  }
  /**
   * Alter a table.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .alterTable('person')
   *   .alterColumn('first_name', (ac) => ac.setDataType('text'))
   *   .execute()
   * ```
   */
  alterTable(table) {
    return new AlterTableBuilder({
      queryId: createQueryId(),
      executor: this.#executor,
      node: AlterTableNode.create(parseTable(table))
    });
  }
  /**
   * Create a new view.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createView('dogs')
   *   .orReplace()
   *   .as(db.selectFrom('pet').selectAll().where('species', '=', 'dog'))
   *   .execute()
   * ```
   */
  createView(viewName) {
    return new CreateViewBuilder({
      queryId: createQueryId(),
      executor: this.#executor,
      node: CreateViewNode.create(viewName)
    });
  }
  /**
   * Refresh a materialized view.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .refreshMaterializedView('my_view')
   *   .concurrently()
   *   .execute()
   * ```
   */
  refreshMaterializedView(viewName) {
    return new RefreshMaterializedViewBuilder({
      queryId: createQueryId(),
      executor: this.#executor,
      node: RefreshMaterializedViewNode.create(viewName)
    });
  }
  /**
   * Drop a view.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .dropView('dogs')
   *   .ifExists()
   *   .execute()
   * ```
   */
  dropView(viewName) {
    return new DropViewBuilder({
      queryId: createQueryId(),
      executor: this.#executor,
      node: DropViewNode.create(viewName)
    });
  }
  /**
   * Create a new type.
   *
   * Only some dialects like PostgreSQL have user-defined types.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .createType('species')
   *   .asEnum(['dog', 'cat', 'frog'])
   *   .execute()
   * ```
   */
  createType(typeName) {
    return new CreateTypeBuilder({
      queryId: createQueryId(),
      executor: this.#executor,
      node: CreateTypeNode.create(parseSchemableIdentifier(typeName))
    });
  }
  /**
   * Drop a type.
   *
   * Only some dialects like PostgreSQL have user-defined types.
   *
   * ### Examples
   *
   * ```ts
   * await db.schema
   *   .dropType('species')
   *   .ifExists()
   *   .execute()
   * ```
   */
  dropType(typeName) {
    return new DropTypeBuilder({
      queryId: createQueryId(),
      executor: this.#executor,
      node: DropTypeNode.create(parseSchemableIdentifier(typeName))
    });
  }
  /**
   * Returns a copy of this schema module with the given plugin installed.
   */
  withPlugin(plugin2) {
    return new _SchemaModule(this.#executor.withPlugin(plugin2));
  }
  /**
   * Returns a copy of this schema module  without any plugins.
   */
  withoutPlugins() {
    return new _SchemaModule(this.#executor.withoutPlugins());
  }
  /**
   * See {@link QueryCreator.withSchema}
   */
  withSchema(schema) {
    return new _SchemaModule(this.#executor.withPluginAtFront(new WithSchemaPlugin(schema)));
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/dynamic/dynamic.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DynamicModule = class {
  /**
   * Creates a dynamic reference to a column that is not know at compile time.
   *
   * Kysely is built in a way that by default you can't refer to tables or columns
   * that are not actually visible in the current query and context. This is all
   * done by TypeScript at compile time, which means that you need to know the
   * columns and tables at compile time. This is not always the case of course.
   *
   * This method is meant to be used in those cases where the column names
   * come from the user input or are not otherwise known at compile time.
   *
   * WARNING! Unlike values, column names are not escaped by the database engine
   * or Kysely and if you pass in unchecked column names using this method, you
   * create an SQL injection vulnerability. Always __always__ validate the user
   * input before passing it to this method.
   *
   * There are couple of examples below for some use cases, but you can pass
   * `ref` to other methods as well. If the types allow you to pass a `ref`
   * value to some place, it should work.
   *
   * ### Examples
   *
   * Filter by a column not know at compile time:
   *
   * ```ts
   * async function someQuery(filterColumn: string, filterValue: string) {
   *   const { ref } = db.dynamic
   *
   *   return await db
   *     .selectFrom('person')
   *     .selectAll()
   *     .where(ref(filterColumn), '=', filterValue)
   *     .execute()
   * }
   *
   * someQuery('first_name', 'Arnold')
   * someQuery('person.last_name', 'Aniston')
   * ```
   *
   * Order by a column not know at compile time:
   *
   * ```ts
   * async function someQuery(orderBy: string) {
   *   const { ref } = db.dynamic
   *
   *   return await db
   *     .selectFrom('person')
   *     .select('person.first_name as fn')
   *     .orderBy(ref(orderBy))
   *     .execute()
   * }
   *
   * someQuery('fn')
   * ```
   *
   * In this example we add selections dynamically:
   *
   * ```ts
   * const { ref } = db.dynamic
   *
   * // Some column name provided by the user. Value not known at compile time.
   * const columnFromUserInput: PossibleColumns = 'birthdate';
   *
   * // A type that lists all possible values `columnFromUserInput` can have.
   * // You can use `keyof Person` if any column of an interface is allowed.
   * type PossibleColumns = 'last_name' | 'first_name' | 'birthdate'
   *
   * const [person] = await db.selectFrom('person')
   *   .select([
   *     ref<PossibleColumns>(columnFromUserInput),
   *     'id'
   *   ])
   *   .execute()
   *
   * // The resulting type contains all `PossibleColumns` as optional fields
   * // because we cannot know which field was actually selected before
   * // running the code.
   * const lastName: string | null | undefined = person?.last_name
   * const firstName: string | undefined = person?.first_name
   * const birthDate: Date | null | undefined = person?.birthdate
   *
   * // The result type also contains the compile time selection `id`.
   * person?.id
   * ```
   */
  ref(reference) {
    return new DynamicReferenceBuilder(reference);
  }
  /**
   * Creates a table reference to a table that's not fully known at compile time.
   *
   * The type `T` is allowed to be a union of multiple tables.
   *
   * <!-- siteExample("select", "Generic find query", 130) -->
   *
   * A generic type-safe helper function for finding a row by a column value:
   *
   * ```ts
   * import { SelectType } from 'kysely'
   * import { Database } from 'type-editor'
   *
   * async function getRowByColumn<
   *   T extends keyof Database,
   *   C extends keyof Database[T] & string,
   *   V extends SelectType<Database[T][C]>,
   * >(t: T, c: C, v: V) {
   *   // We need to use the dynamic module since the table name
   *   // is not known at compile time.
   *   const { table, ref } = db.dynamic
   *
   *   return await db
   *     .selectFrom(table(t).as('t'))
   *     .selectAll()
   *     .where(ref(c), '=', v)
   *     .orderBy('t.id')
   *     .executeTakeFirstOrThrow()
   * }
   *
   * const person = await getRowByColumn('person', 'first_name', 'Arnold')
   * ```
   */
  table(table) {
    return new DynamicTableBuilder(table);
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/driver/default-connection-provider.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DefaultConnectionProvider = class {
  #driver;
  constructor(driver) {
    this.#driver = driver;
  }
  async provideConnection(consumer) {
    const connection = await this.#driver.acquireConnection();
    try {
      return await consumer(connection);
    } finally {
      await this.#driver.releaseConnection(connection);
    }
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-executor/default-query-executor.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DefaultQueryExecutor = class _DefaultQueryExecutor extends QueryExecutorBase {
  #compiler;
  #adapter;
  #connectionProvider;
  constructor(compiler, adapter, connectionProvider, plugins = []) {
    super(plugins);
    this.#compiler = compiler;
    this.#adapter = adapter;
    this.#connectionProvider = connectionProvider;
  }
  get adapter() {
    return this.#adapter;
  }
  compileQuery(node, queryId) {
    return this.#compiler.compileQuery(node, queryId);
  }
  provideConnection(consumer) {
    return this.#connectionProvider.provideConnection(consumer);
  }
  withPlugins(plugins) {
    return new _DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, [...this.plugins, ...plugins]);
  }
  withPlugin(plugin2) {
    return new _DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, [...this.plugins, plugin2]);
  }
  withPluginAtFront(plugin2) {
    return new _DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, [plugin2, ...this.plugins]);
  }
  withConnectionProvider(connectionProvider) {
    return new _DefaultQueryExecutor(this.#compiler, this.#adapter, connectionProvider, [...this.plugins]);
  }
  withoutPlugins() {
    return new _DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, []);
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/driver/runtime-driver.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/util/performance-now.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function performanceNow() {
  if (typeof performance !== "undefined" && isFunction(performance.now)) {
    return performance.now();
  } else {
    return Date.now();
  }
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/driver/runtime-driver.js
var RuntimeDriver = class {
  #driver;
  #log;
  #initPromise;
  #initDone;
  #destroyPromise;
  #connections = /* @__PURE__ */ new WeakSet();
  constructor(driver, log2) {
    this.#initDone = false;
    this.#driver = driver;
    this.#log = log2;
  }
  async init() {
    if (this.#destroyPromise) {
      throw new Error("driver has already been destroyed");
    }
    if (!this.#initPromise) {
      this.#initPromise = this.#driver.init().then(() => {
        this.#initDone = true;
      }).catch((err) => {
        this.#initPromise = void 0;
        return Promise.reject(err);
      });
    }
    await this.#initPromise;
  }
  async acquireConnection() {
    if (this.#destroyPromise) {
      throw new Error("driver has already been destroyed");
    }
    if (!this.#initDone) {
      await this.init();
    }
    const connection = await this.#driver.acquireConnection();
    if (!this.#connections.has(connection)) {
      if (this.#needsLogging()) {
        this.#addLogging(connection);
      }
      this.#connections.add(connection);
    }
    return connection;
  }
  async releaseConnection(connection) {
    await this.#driver.releaseConnection(connection);
  }
  beginTransaction(connection, settings) {
    return this.#driver.beginTransaction(connection, settings);
  }
  commitTransaction(connection) {
    return this.#driver.commitTransaction(connection);
  }
  rollbackTransaction(connection) {
    return this.#driver.rollbackTransaction(connection);
  }
  savepoint(connection, savepointName, compileQuery) {
    if (this.#driver.savepoint) {
      return this.#driver.savepoint(connection, savepointName, compileQuery);
    }
    throw new Error("The `savepoint` method is not supported by this driver");
  }
  rollbackToSavepoint(connection, savepointName, compileQuery) {
    if (this.#driver.rollbackToSavepoint) {
      return this.#driver.rollbackToSavepoint(connection, savepointName, compileQuery);
    }
    throw new Error("The `rollbackToSavepoint` method is not supported by this driver");
  }
  releaseSavepoint(connection, savepointName, compileQuery) {
    if (this.#driver.releaseSavepoint) {
      return this.#driver.releaseSavepoint(connection, savepointName, compileQuery);
    }
    throw new Error("The `releaseSavepoint` method is not supported by this driver");
  }
  async destroy() {
    if (!this.#initPromise) {
      return;
    }
    await this.#initPromise;
    if (!this.#destroyPromise) {
      this.#destroyPromise = this.#driver.destroy().catch((err) => {
        this.#destroyPromise = void 0;
        return Promise.reject(err);
      });
    }
    await this.#destroyPromise;
  }
  #needsLogging() {
    return this.#log.isLevelEnabled("query") || this.#log.isLevelEnabled("error");
  }
  // This method monkey patches the database connection's executeQuery method
  // by adding logging code around it. Monkey patching is not pretty, but it's
  // the best option in this case.
  #addLogging(connection) {
    const executeQuery = connection.executeQuery;
    const streamQuery = connection.streamQuery;
    const dis = this;
    connection.executeQuery = async (compiledQuery) => {
      let caughtError;
      const startTime = performanceNow();
      try {
        return await executeQuery.call(connection, compiledQuery);
      } catch (error) {
        caughtError = error;
        await dis.#logError(error, compiledQuery, startTime);
        throw error;
      } finally {
        if (!caughtError) {
          await dis.#logQuery(compiledQuery, startTime);
        }
      }
    };
    connection.streamQuery = async function* (compiledQuery, chunkSize) {
      let caughtError;
      const startTime = performanceNow();
      try {
        for await (const result of streamQuery.call(connection, compiledQuery, chunkSize)) {
          yield result;
        }
      } catch (error) {
        caughtError = error;
        await dis.#logError(error, compiledQuery, startTime);
        throw error;
      } finally {
        if (!caughtError) {
          await dis.#logQuery(compiledQuery, startTime, true);
        }
      }
    };
  }
  async #logError(error, compiledQuery, startTime) {
    await this.#log.error(() => ({
      level: "error",
      error,
      query: compiledQuery,
      queryDurationMillis: this.#calculateDurationMillis(startTime)
    }));
  }
  async #logQuery(compiledQuery, startTime, isStream = false) {
    await this.#log.query(() => ({
      level: "query",
      isStream,
      query: compiledQuery,
      queryDurationMillis: this.#calculateDurationMillis(startTime)
    }));
  }
  #calculateDurationMillis(startTime) {
    return performanceNow() - startTime;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/driver/single-connection-provider.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ignoreError = () => {
};
var SingleConnectionProvider = class {
  #connection;
  #runningPromise;
  constructor(connection) {
    this.#connection = connection;
  }
  async provideConnection(consumer) {
    while (this.#runningPromise) {
      await this.#runningPromise.catch(ignoreError);
    }
    this.#runningPromise = this.#run(consumer).finally(() => {
      this.#runningPromise = void 0;
    });
    return this.#runningPromise;
  }
  // Run the runner in an async function to make sure it doesn't
  // throw synchronous errors.
  async #run(runner) {
    return await runner(this.#connection);
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/driver/driver.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var TRANSACTION_ACCESS_MODES = ["read only", "read write"];
var TRANSACTION_ISOLATION_LEVELS = [
  "read uncommitted",
  "read committed",
  "repeatable read",
  "serializable",
  "snapshot"
];
function validateTransactionSettings(settings) {
  if (settings.accessMode && !TRANSACTION_ACCESS_MODES.includes(settings.accessMode)) {
    throw new Error(`invalid transaction access mode ${settings.accessMode}`);
  }
  if (settings.isolationLevel && !TRANSACTION_ISOLATION_LEVELS.includes(settings.isolationLevel)) {
    throw new Error(`invalid transaction isolation level ${settings.isolationLevel}`);
  }
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/util/log.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var logLevels = ["query", "error"];
var LOG_LEVELS = freeze(logLevels);
var Log = class {
  #levels;
  #logger;
  constructor(config) {
    if (isFunction(config)) {
      this.#logger = config;
      this.#levels = freeze({
        query: true,
        error: true
      });
    } else {
      this.#logger = defaultLogger;
      this.#levels = freeze({
        query: config.includes("query"),
        error: config.includes("error")
      });
    }
  }
  isLevelEnabled(level) {
    return this.#levels[level];
  }
  async query(getEvent) {
    if (this.#levels.query) {
      await this.#logger(getEvent());
    }
  }
  async error(getEvent) {
    if (this.#levels.error) {
      await this.#logger(getEvent());
    }
  }
};
function defaultLogger(event) {
  if (event.level === "query") {
    const prefix = `kysely:query:${event.isStream ? "stream:" : ""}`;
    console.log(`${prefix} ${event.query.sql}`);
    console.log(`${prefix} duration: ${event.queryDurationMillis.toFixed(1)}ms`);
  } else if (event.level === "error") {
    if (event.error instanceof Error) {
      console.error(`kysely:error: ${event.error.stack ?? event.error.message}`);
    } else {
      console.error(`kysely:error: ${JSON.stringify({
        error: event.error,
        query: event.query.sql,
        queryDurationMillis: event.queryDurationMillis
      })}`);
    }
  }
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/util/compilable.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function isCompilable(value) {
  return isObject(value) && isFunction(value.compile);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/kysely.js
Symbol.asyncDispose ??= Symbol("Symbol.asyncDispose");
var Kysely = class _Kysely extends QueryCreator {
  #props;
  constructor(args) {
    let superProps;
    let props;
    if (isKyselyProps(args)) {
      superProps = { executor: args.executor };
      props = { ...args };
    } else {
      const dialect = args.dialect;
      const driver = dialect.createDriver();
      const compiler = dialect.createQueryCompiler();
      const adapter = dialect.createAdapter();
      const log2 = new Log(args.log ?? []);
      const runtimeDriver = new RuntimeDriver(driver, log2);
      const connectionProvider = new DefaultConnectionProvider(runtimeDriver);
      const executor = new DefaultQueryExecutor(compiler, adapter, connectionProvider, args.plugins ?? []);
      superProps = { executor };
      props = {
        config: args,
        executor,
        dialect,
        driver: runtimeDriver
      };
    }
    super(superProps);
    this.#props = freeze(props);
  }
  /**
   * Returns the {@link SchemaModule} module for building database schema.
   */
  get schema() {
    return new SchemaModule(this.#props.executor);
  }
  /**
   * Returns a the {@link DynamicModule} module.
   *
   * The {@link DynamicModule} module can be used to bypass strict typing and
   * passing in dynamic values for the queries.
   */
  get dynamic() {
    return new DynamicModule();
  }
  /**
   * Returns a {@link DatabaseIntrospector | database introspector}.
   */
  get introspection() {
    return this.#props.dialect.createIntrospector(this.withoutPlugins());
  }
  case(value) {
    return new CaseBuilder({
      node: CaseNode.create(isUndefined(value) ? void 0 : parseExpression(value))
    });
  }
  /**
   * Returns a {@link FunctionModule} that can be used to write somewhat type-safe function
   * calls.
   *
   * ```ts
   * const { count } = db.fn
   *
   * await db.selectFrom('person')
   *   .innerJoin('pet', 'pet.owner_id', 'person.id')
   *   .select([
   *     'id',
   *     count('pet.id').as('person_count'),
   *   ])
   *   .groupBy('person.id')
   *   .having(count('pet.id'), '>', 10)
   *   .execute()
   * ```
   *
   * The generated SQL (PostgreSQL):
   *
   * ```sql
   * select "person"."id", count("pet"."id") as "person_count"
   * from "person"
   * inner join "pet" on "pet"."owner_id" = "person"."id"
   * group by "person"."id"
   * having count("pet"."id") > $1
   * ```
   *
   * Why "somewhat" type-safe? Because the function calls are not bound to the
   * current query context. They allow you to reference columns and tables that
   * are not in the current query. E.g. remove the `innerJoin` from the previous
   * query and TypeScript won't even complain.
   *
   * If you want to make the function calls fully type-safe, you can use the
   * {@link ExpressionBuilder.fn} getter for a query context-aware, stricter {@link FunctionModule}.
   *
   * ```ts
   * await db.selectFrom('person')
   *   .innerJoin('pet', 'pet.owner_id', 'person.id')
   *   .select((eb) => [
   *     'person.id',
   *     eb.fn.count('pet.id').as('pet_count')
   *   ])
   *   .groupBy('person.id')
   *   .having((eb) => eb.fn.count('pet.id'), '>', 10)
   *   .execute()
   * ```
   */
  get fn() {
    return createFunctionModule();
  }
  /**
   * Creates a {@link TransactionBuilder} that can be used to run queries inside a transaction.
   *
   * The returned {@link TransactionBuilder} can be used to configure the transaction. The
   * {@link TransactionBuilder.execute} method can then be called to run the transaction.
   * {@link TransactionBuilder.execute} takes a function that is run inside the
   * transaction. If the function throws an exception,
   * 1. the exception is caught,
   * 2. the transaction is rolled back, and
   * 3. the exception is thrown again.
   * Otherwise the transaction is committed.
   *
   * The callback function passed to the {@link TransactionBuilder.execute | execute}
   * method gets the transaction object as its only argument. The transaction is
   * of type {@link Transaction} which inherits {@link Kysely}. Any query
   * started through the transaction object is executed inside the transaction.
   *
   * To run a controlled transaction, allowing you to commit and rollback manually,
   * use {@link startTransaction} instead.
   *
   * ### Examples
   *
   * <!-- siteExample("transactions", "Simple transaction", 10) -->
   *
   * This example inserts two rows in a transaction. If an exception is thrown inside
   * the callback passed to the `execute` method,
   * 1. the exception is caught,
   * 2. the transaction is rolled back, and
   * 3. the exception is thrown again.
   * Otherwise the transaction is committed.
   *
   * ```ts
   * const catto = await db.transaction().execute(async (trx) => {
   *   const jennifer = await trx.insertInto('person')
   *     .values({
   *       first_name: 'Jennifer',
   *       last_name: 'Aniston',
   *       age: 40,
   *     })
   *     .returning('id')
   *     .executeTakeFirstOrThrow()
   *
   *   return await trx.insertInto('pet')
   *     .values({
   *       owner_id: jennifer.id,
   *       name: 'Catto',
   *       species: 'cat',
   *       is_favorite: false,
   *     })
   *     .returningAll()
   *     .executeTakeFirst()
   * })
   * ```
   *
   * Setting the isolation level:
   *
   * ```ts
   * import type { Kysely } from 'kysely'
   *
   * await db
   *   .transaction()
   *   .setIsolationLevel('serializable')
   *   .execute(async (trx) => {
   *     await doStuff(trx)
   *   })
   *
   * async function doStuff(kysely: typeof db) {
   *   // ...
   * }
   * ```
   */
  transaction() {
    return new TransactionBuilder({ ...this.#props });
  }
  /**
   * Creates a {@link ControlledTransactionBuilder} that can be used to run queries inside a controlled transaction.
   *
   * The returned {@link ControlledTransactionBuilder} can be used to configure the transaction.
   * The {@link ControlledTransactionBuilder.execute} method can then be called
   * to start the transaction and return a {@link ControlledTransaction}.
   *
   * A {@link ControlledTransaction} allows you to commit and rollback manually,
   * execute savepoint commands. It extends {@link Transaction} which extends {@link Kysely},
   * so you can run queries inside the transaction. Once the transaction is committed,
   * or rolled back, it can't be used anymore - all queries will throw an error.
   * This is to prevent accidentally running queries outside the transaction - where
   * atomicity is not guaranteed anymore.
   *
   * ### Examples
   *
   * <!-- siteExample("transactions", "Controlled transaction", 11) -->
   *
   * A controlled transaction allows you to commit and rollback manually, execute
   * savepoint commands, and queries in general.
   *
   * In this example we start a transaction, use it to insert two rows and then commit
   * the transaction. If an error is thrown, we catch it and rollback the transaction.
   *
   * ```ts
   * const trx = await db.startTransaction().execute()
   *
   * try {
   *   const jennifer = await trx.insertInto('person')
   *     .values({
   *       first_name: 'Jennifer',
   *       last_name: 'Aniston',
   *       age: 40,
   *     })
   *     .returning('id')
   *     .executeTakeFirstOrThrow()
   *
   *   const catto = await trx.insertInto('pet')
   *     .values({
   *       owner_id: jennifer.id,
   *       name: 'Catto',
   *       species: 'cat',
   *       is_favorite: false,
   *     })
   *     .returningAll()
   *     .executeTakeFirstOrThrow()
   *
   *   await trx.commit().execute()
   *
   *   // ...
   * } catch (error) {
   *   await trx.rollback().execute()
   * }
   * ```
   *
   * <!-- siteExample("transactions", "Controlled transaction /w savepoints", 12) -->
   *
   * A controlled transaction allows you to commit and rollback manually, execute
   * savepoint commands, and queries in general.
   *
   * In this example we start a transaction, insert a person, create a savepoint,
   * try inserting a toy and a pet, and if an error is thrown, we rollback to the
   * savepoint. Eventually we release the savepoint, insert an audit record and
   * commit the transaction. If an error is thrown, we catch it and rollback the
   * transaction.
   *
   * ```ts
   * const trx = await db.startTransaction().execute()
   *
   * try {
   *   const jennifer = await trx
   *     .insertInto('person')
   *     .values({
   *       first_name: 'Jennifer',
   *       last_name: 'Aniston',
   *       age: 40,
   *     })
   *     .returning('id')
   *     .executeTakeFirstOrThrow()
   *
   *   const trxAfterJennifer = await trx.savepoint('after_jennifer').execute()
   *
   *   try {
   *     const catto = await trxAfterJennifer
   *       .insertInto('pet')
   *       .values({
   *         owner_id: jennifer.id,
   *         name: 'Catto',
   *         species: 'cat',
   *       })
   *       .returning('id')
   *       .executeTakeFirstOrThrow()
   *
   *     await trxAfterJennifer
   *       .insertInto('toy')
   *       .values({ name: 'Bone', price: 1.99, pet_id: catto.id })
   *       .execute()
   *   } catch (error) {
   *     await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute()
   *   }
   *
   *   await trxAfterJennifer.releaseSavepoint('after_jennifer').execute()
   *
   *   await trx.insertInto('audit').values({ action: 'added Jennifer' }).execute()
   *
   *   await trx.commit().execute()
   * } catch (error) {
   *   await trx.rollback().execute()
   * }
   * ```
   */
  startTransaction() {
    return new ControlledTransactionBuilder({ ...this.#props });
  }
  /**
   * Provides a kysely instance bound to a single database connection.
   *
   * ### Examples
   *
   * ```ts
   * await db
   *   .connection()
   *   .execute(async (db) => {
   *     // `db` is an instance of `Kysely` that's bound to a single
   *     // database connection. All queries executed through `db` use
   *     // the same connection.
   *     await doStuff(db)
   *   })
   *
   * async function doStuff(kysely: typeof db) {
   *   // ...
   * }
   * ```
   */
  connection() {
    return new ConnectionBuilder({ ...this.#props });
  }
  /**
   * Returns a copy of this Kysely instance with the given plugin installed.
   */
  withPlugin(plugin2) {
    return new _Kysely({
      ...this.#props,
      executor: this.#props.executor.withPlugin(plugin2)
    });
  }
  /**
   * Returns a copy of this Kysely instance without any plugins.
   */
  withoutPlugins() {
    return new _Kysely({
      ...this.#props,
      executor: this.#props.executor.withoutPlugins()
    });
  }
  /**
   * @override
   */
  withSchema(schema) {
    return new _Kysely({
      ...this.#props,
      executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema))
    });
  }
  /**
   * Returns a copy of this Kysely instance with tables added to its
   * database type.
   *
   * This method only modifies the types and doesn't affect any of the
   * executed queries in any way.
   *
   * ### Examples
   *
   * The following example adds and uses a temporary table:
   *
   * ```ts
   * await db.schema
   *   .createTable('temp_table')
   *   .temporary()
   *   .addColumn('some_column', 'integer')
   *   .execute()
   *
   * const tempDb = db.withTables<{
   *   temp_table: {
   *     some_column: number
   *   }
   * }>()
   *
   * await tempDb
   *   .insertInto('temp_table')
   *   .values({ some_column: 100 })
   *   .execute()
   * ```
   */
  withTables() {
    return new _Kysely({ ...this.#props });
  }
  /**
   * Releases all resources and disconnects from the database.
   *
   * You need to call this when you are done using the `Kysely` instance.
   */
  async destroy() {
    await this.#props.driver.destroy();
  }
  /**
   * Returns true if this `Kysely` instance is a transaction.
   *
   * You can also use `db instanceof Transaction`.
   */
  get isTransaction() {
    return false;
  }
  /**
   * @internal
   * @private
   */
  getExecutor() {
    return this.#props.executor;
  }
  /**
   * Executes a given compiled query or query builder.
   *
   * See {@link https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/0004-splitting-query-building-and-execution.md#execute-compiled-queries splitting build, compile and execute code recipe} for more information.
   */
  executeQuery(query, queryId) {
    if (queryId !== void 0) {
      logOnce("Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future.");
    }
    const compiledQuery = isCompilable(query) ? query.compile() : query;
    return this.getExecutor().executeQuery(compiledQuery);
  }
  async [Symbol.asyncDispose]() {
    await this.destroy();
  }
};
var Transaction = class _Transaction extends Kysely {
  #props;
  constructor(props) {
    super(props);
    this.#props = props;
  }
  // The return type is `true` instead of `boolean` to make Kysely<DB>
  // unassignable to Transaction<DB> while allowing assignment the
  // other way around.
  get isTransaction() {
    return true;
  }
  transaction() {
    throw new Error("calling the transaction method for a Transaction is not supported");
  }
  connection() {
    throw new Error("calling the connection method for a Transaction is not supported");
  }
  async destroy() {
    throw new Error("calling the destroy method for a Transaction is not supported");
  }
  withPlugin(plugin2) {
    return new _Transaction({
      ...this.#props,
      executor: this.#props.executor.withPlugin(plugin2)
    });
  }
  withoutPlugins() {
    return new _Transaction({
      ...this.#props,
      executor: this.#props.executor.withoutPlugins()
    });
  }
  withSchema(schema) {
    return new _Transaction({
      ...this.#props,
      executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema))
    });
  }
  withTables() {
    return new _Transaction({ ...this.#props });
  }
};
function isKyselyProps(obj) {
  return isObject(obj) && isObject(obj.config) && isObject(obj.driver) && isObject(obj.executor) && isObject(obj.dialect);
}
var ConnectionBuilder = class {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  async execute(callback) {
    return this.#props.executor.provideConnection(async (connection) => {
      const executor = this.#props.executor.withConnectionProvider(new SingleConnectionProvider(connection));
      const db = new Kysely({
        ...this.#props,
        executor
      });
      return await callback(db);
    });
  }
};
var TransactionBuilder = class _TransactionBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  setAccessMode(accessMode) {
    return new _TransactionBuilder({
      ...this.#props,
      accessMode
    });
  }
  setIsolationLevel(isolationLevel) {
    return new _TransactionBuilder({
      ...this.#props,
      isolationLevel
    });
  }
  async execute(callback) {
    const { isolationLevel, accessMode, ...kyselyProps } = this.#props;
    const settings = { isolationLevel, accessMode };
    validateTransactionSettings(settings);
    return this.#props.executor.provideConnection(async (connection) => {
      const state = { isCommitted: false, isRolledBack: false };
      const executor = new NotCommittedOrRolledBackAssertingExecutor(this.#props.executor.withConnectionProvider(new SingleConnectionProvider(connection)), state);
      const transaction = new Transaction({
        ...kyselyProps,
        executor
      });
      let transactionBegun = false;
      try {
        await this.#props.driver.beginTransaction(connection, settings);
        transactionBegun = true;
        const result = await callback(transaction);
        await this.#props.driver.commitTransaction(connection);
        state.isCommitted = true;
        return result;
      } catch (error) {
        if (transactionBegun) {
          await this.#props.driver.rollbackTransaction(connection);
          state.isRolledBack = true;
        }
        throw error;
      }
    });
  }
};
var ControlledTransactionBuilder = class _ControlledTransactionBuilder {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  setAccessMode(accessMode) {
    return new _ControlledTransactionBuilder({
      ...this.#props,
      accessMode
    });
  }
  setIsolationLevel(isolationLevel) {
    return new _ControlledTransactionBuilder({
      ...this.#props,
      isolationLevel
    });
  }
  async execute() {
    const { isolationLevel, accessMode, ...props } = this.#props;
    const settings = { isolationLevel, accessMode };
    validateTransactionSettings(settings);
    const connection = await provideControlledConnection(this.#props.executor);
    await this.#props.driver.beginTransaction(connection.connection, settings);
    return new ControlledTransaction({
      ...props,
      connection,
      executor: this.#props.executor.withConnectionProvider(new SingleConnectionProvider(connection.connection))
    });
  }
};
var ControlledTransaction = class _ControlledTransaction extends Transaction {
  #props;
  #compileQuery;
  #state;
  constructor(props) {
    const state = { isCommitted: false, isRolledBack: false };
    props = {
      ...props,
      executor: new NotCommittedOrRolledBackAssertingExecutor(props.executor, state)
    };
    const { connection, ...transactionProps } = props;
    super(transactionProps);
    this.#props = freeze(props);
    this.#state = state;
    const queryId = createQueryId();
    this.#compileQuery = (node) => props.executor.compileQuery(node, queryId);
  }
  get isCommitted() {
    return this.#state.isCommitted;
  }
  get isRolledBack() {
    return this.#state.isRolledBack;
  }
  /**
   * Commits the transaction.
   *
   * See {@link rollback}.
   *
   * ### Examples
   *
   * ```ts
   * import type { Kysely } from 'kysely'
   * import type { Database } from 'type-editor' // imaginary module
   *
   * const trx = await db.startTransaction().execute()
   *
   * try {
   *   await doSomething(trx)
   *
   *   await trx.commit().execute()
   * } catch (error) {
   *   await trx.rollback().execute()
   * }
   *
   * async function doSomething(kysely: Kysely<Database>) {}
   * ```
   */
  commit() {
    assertNotCommittedOrRolledBack(this.#state);
    return new Command2(async () => {
      await this.#props.driver.commitTransaction(this.#props.connection.connection);
      this.#state.isCommitted = true;
      this.#props.connection.release();
    });
  }
  /**
   * Rolls back the transaction.
   *
   * See {@link commit} and {@link rollbackToSavepoint}.
   *
   * ### Examples
   *
   * ```ts
   * import type { Kysely } from 'kysely'
   * import type { Database } from 'type-editor' // imaginary module
   *
   * const trx = await db.startTransaction().execute()
   *
   * try {
   *   await doSomething(trx)
   *
   *   await trx.commit().execute()
   * } catch (error) {
   *   await trx.rollback().execute()
   * }
   *
   * async function doSomething(kysely: Kysely<Database>) {}
   * ```
   */
  rollback() {
    assertNotCommittedOrRolledBack(this.#state);
    return new Command2(async () => {
      await this.#props.driver.rollbackTransaction(this.#props.connection.connection);
      this.#state.isRolledBack = true;
      this.#props.connection.release();
    });
  }
  /**
   * Creates a savepoint with a given name.
   *
   * See {@link rollbackToSavepoint} and {@link releaseSavepoint}.
   *
   * For a type-safe experience, you should use the returned instance from now on.
   *
   * ### Examples
   *
   * ```ts
   * import type { Kysely } from 'kysely'
   * import type { Database } from 'type-editor' // imaginary module
   *
   * const trx = await db.startTransaction().execute()
   *
   * await insertJennifer(trx)
   *
   * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute()
   *
   * try {
   *   await doSomething(trxAfterJennifer)
   * } catch (error) {
   *   await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute()
   * }
   *
   * async function insertJennifer(kysely: Kysely<Database>) {}
   * async function doSomething(kysely: Kysely<Database>) {}
   * ```
   */
  savepoint(savepointName) {
    assertNotCommittedOrRolledBack(this.#state);
    return new Command2(async () => {
      var _a8, _b5;
      await ((_b5 = (_a8 = this.#props.driver).savepoint) == null ? void 0 : _b5.call(_a8, this.#props.connection.connection, savepointName, this.#compileQuery));
      return new _ControlledTransaction({ ...this.#props });
    });
  }
  /**
   * Rolls back to a savepoint with a given name.
   *
   * See {@link savepoint} and {@link releaseSavepoint}.
   *
   * You must use the same instance returned by {@link savepoint}, or
   * escape the type-check by using `as any`.
   *
   * ### Examples
   *
   * ```ts
   * import type { Kysely } from 'kysely'
   * import type { Database } from 'type-editor' // imaginary module
   *
   * const trx = await db.startTransaction().execute()
   *
   * await insertJennifer(trx)
   *
   * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute()
   *
   * try {
   *   await doSomething(trxAfterJennifer)
   * } catch (error) {
   *   await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute()
   * }
   *
   * async function insertJennifer(kysely: Kysely<Database>) {}
   * async function doSomething(kysely: Kysely<Database>) {}
   * ```
   */
  rollbackToSavepoint(savepointName) {
    assertNotCommittedOrRolledBack(this.#state);
    return new Command2(async () => {
      var _a8, _b5;
      await ((_b5 = (_a8 = this.#props.driver).rollbackToSavepoint) == null ? void 0 : _b5.call(_a8, this.#props.connection.connection, savepointName, this.#compileQuery));
      return new _ControlledTransaction({ ...this.#props });
    });
  }
  /**
   * Releases a savepoint with a given name.
   *
   * See {@link savepoint} and {@link rollbackToSavepoint}.
   *
   * You must use the same instance returned by {@link savepoint}, or
   * escape the type-check by using `as any`.
   *
   * ### Examples
   *
   * ```ts
   * import type { Kysely } from 'kysely'
   * import type { Database } from 'type-editor' // imaginary module
   *
   * const trx = await db.startTransaction().execute()
   *
   * await insertJennifer(trx)
   *
   * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute()
   *
   * try {
   *   await doSomething(trxAfterJennifer)
   * } catch (error) {
   *   await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute()
   * }
   *
   * await trxAfterJennifer.releaseSavepoint('after_jennifer').execute()
   *
   * await doSomethingElse(trx)
   *
   * async function insertJennifer(kysely: Kysely<Database>) {}
   * async function doSomething(kysely: Kysely<Database>) {}
   * async function doSomethingElse(kysely: Kysely<Database>) {}
   * ```
   */
  releaseSavepoint(savepointName) {
    assertNotCommittedOrRolledBack(this.#state);
    return new Command2(async () => {
      var _a8, _b5;
      await ((_b5 = (_a8 = this.#props.driver).releaseSavepoint) == null ? void 0 : _b5.call(_a8, this.#props.connection.connection, savepointName, this.#compileQuery));
      return new _ControlledTransaction({ ...this.#props });
    });
  }
  withPlugin(plugin2) {
    return new _ControlledTransaction({
      ...this.#props,
      executor: this.#props.executor.withPlugin(plugin2)
    });
  }
  withoutPlugins() {
    return new _ControlledTransaction({
      ...this.#props,
      executor: this.#props.executor.withoutPlugins()
    });
  }
  withSchema(schema) {
    return new _ControlledTransaction({
      ...this.#props,
      executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema))
    });
  }
  withTables() {
    return new _ControlledTransaction({ ...this.#props });
  }
};
var Command2 = class {
  #cb;
  constructor(cb) {
    this.#cb = cb;
  }
  /**
   * Executes the command.
   */
  async execute() {
    return await this.#cb();
  }
};
function assertNotCommittedOrRolledBack(state) {
  if (state.isCommitted) {
    throw new Error("Transaction is already committed");
  }
  if (state.isRolledBack) {
    throw new Error("Transaction is already rolled back");
  }
}
var NotCommittedOrRolledBackAssertingExecutor = class _NotCommittedOrRolledBackAssertingExecutor {
  #executor;
  #state;
  constructor(executor, state) {
    if (executor instanceof _NotCommittedOrRolledBackAssertingExecutor) {
      this.#executor = executor.#executor;
    } else {
      this.#executor = executor;
    }
    this.#state = state;
  }
  get adapter() {
    return this.#executor.adapter;
  }
  get plugins() {
    return this.#executor.plugins;
  }
  transformQuery(node, queryId) {
    return this.#executor.transformQuery(node, queryId);
  }
  compileQuery(node, queryId) {
    return this.#executor.compileQuery(node, queryId);
  }
  provideConnection(consumer) {
    return this.#executor.provideConnection(consumer);
  }
  executeQuery(compiledQuery) {
    assertNotCommittedOrRolledBack(this.#state);
    return this.#executor.executeQuery(compiledQuery);
  }
  stream(compiledQuery, chunkSize) {
    assertNotCommittedOrRolledBack(this.#state);
    return this.#executor.stream(compiledQuery, chunkSize);
  }
  withConnectionProvider(connectionProvider) {
    return new _NotCommittedOrRolledBackAssertingExecutor(this.#executor.withConnectionProvider(connectionProvider), this.#state);
  }
  withPlugin(plugin2) {
    return new _NotCommittedOrRolledBackAssertingExecutor(this.#executor.withPlugin(plugin2), this.#state);
  }
  withPlugins(plugins) {
    return new _NotCommittedOrRolledBackAssertingExecutor(this.#executor.withPlugins(plugins), this.#state);
  }
  withPluginAtFront(plugin2) {
    return new _NotCommittedOrRolledBackAssertingExecutor(this.#executor.withPluginAtFront(plugin2), this.#state);
  }
  withoutPlugins() {
    return new _NotCommittedOrRolledBackAssertingExecutor(this.#executor.withoutPlugins(), this.#state);
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/raw-builder/raw-builder.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var RawBuilderImpl = class _RawBuilderImpl {
  #props;
  constructor(props) {
    this.#props = freeze(props);
  }
  get expressionType() {
    return void 0;
  }
  get isRawBuilder() {
    return true;
  }
  as(alias) {
    return new AliasedRawBuilderImpl(this, alias);
  }
  $castTo() {
    return new _RawBuilderImpl({ ...this.#props });
  }
  $notNull() {
    return new _RawBuilderImpl(this.#props);
  }
  withPlugin(plugin2) {
    return new _RawBuilderImpl({
      ...this.#props,
      plugins: this.#props.plugins !== void 0 ? freeze([...this.#props.plugins, plugin2]) : freeze([plugin2])
    });
  }
  toOperationNode() {
    return this.#toOperationNode(this.#getExecutor());
  }
  compile(executorProvider) {
    return this.#compile(this.#getExecutor(executorProvider));
  }
  async execute(executorProvider) {
    const executor = this.#getExecutor(executorProvider);
    return executor.executeQuery(this.#compile(executor));
  }
  #getExecutor(executorProvider) {
    const executor = executorProvider !== void 0 ? executorProvider.getExecutor() : NOOP_QUERY_EXECUTOR;
    return this.#props.plugins !== void 0 ? executor.withPlugins(this.#props.plugins) : executor;
  }
  #toOperationNode(executor) {
    return executor.transformQuery(this.#props.rawNode, this.#props.queryId);
  }
  #compile(executor) {
    return executor.compileQuery(this.#toOperationNode(executor), this.#props.queryId);
  }
};
function createRawBuilder(props) {
  return new RawBuilderImpl(props);
}
var AliasedRawBuilderImpl = class {
  #rawBuilder;
  #alias;
  constructor(rawBuilder, alias) {
    this.#rawBuilder = rawBuilder;
    this.#alias = alias;
  }
  get expression() {
    return this.#rawBuilder;
  }
  get alias() {
    return this.#alias;
  }
  get rawBuilder() {
    return this.#rawBuilder;
  }
  toOperationNode() {
    return AliasNode.create(this.#rawBuilder.toOperationNode(), isOperationNodeSource(this.#alias) ? this.#alias.toOperationNode() : IdentifierNode.create(this.#alias));
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/raw-builder/sql.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var sql = Object.assign((sqlFragments, ...parameters) => {
  return createRawBuilder({
    queryId: createQueryId(),
    rawNode: RawNode.create(sqlFragments, (parameters == null ? void 0 : parameters.map(parseParameter)) ?? [])
  });
}, {
  ref(columnReference) {
    return createRawBuilder({
      queryId: createQueryId(),
      rawNode: RawNode.createWithChild(parseStringReference(columnReference))
    });
  },
  val(value) {
    return createRawBuilder({
      queryId: createQueryId(),
      rawNode: RawNode.createWithChild(parseValueExpression(value))
    });
  },
  value(value) {
    return this.val(value);
  },
  table(tableReference) {
    return createRawBuilder({
      queryId: createQueryId(),
      rawNode: RawNode.createWithChild(parseTable(tableReference))
    });
  },
  id(...ids) {
    const fragments = new Array(ids.length + 1).fill(".");
    fragments[0] = "";
    fragments[fragments.length - 1] = "";
    return createRawBuilder({
      queryId: createQueryId(),
      rawNode: RawNode.create(fragments, ids.map(IdentifierNode.create))
    });
  },
  lit(value) {
    return createRawBuilder({
      queryId: createQueryId(),
      rawNode: RawNode.createWithChild(ValueNode.createImmediate(value))
    });
  },
  literal(value) {
    return this.lit(value);
  },
  raw(sql2) {
    return createRawBuilder({
      queryId: createQueryId(),
      rawNode: RawNode.createWithSql(sql2)
    });
  },
  join(array, separator = sql`, `) {
    const nodes = new Array(Math.max(2 * array.length - 1, 0));
    const sep2 = separator.toOperationNode();
    for (let i2 = 0; i2 < array.length; ++i2) {
      nodes[2 * i2] = parseParameter(array[i2]);
      if (i2 !== array.length - 1) {
        nodes[2 * i2 + 1] = sep2;
      }
    }
    return createRawBuilder({
      queryId: createQueryId(),
      rawNode: RawNode.createWithChildren(nodes)
    });
  }
});
function parseParameter(param) {
  if (isOperationNodeSource(param)) {
    return param.toOperationNode();
  }
  return parseValueExpression(param);
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-compiler/default-query-compiler.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/operation-node/operation-node-visitor.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var OperationNodeVisitor = class {
  nodeStack = [];
  get parentNode() {
    return this.nodeStack[this.nodeStack.length - 2];
  }
  #visitors = freeze({
    AliasNode: this.visitAlias.bind(this),
    ColumnNode: this.visitColumn.bind(this),
    IdentifierNode: this.visitIdentifier.bind(this),
    SchemableIdentifierNode: this.visitSchemableIdentifier.bind(this),
    RawNode: this.visitRaw.bind(this),
    ReferenceNode: this.visitReference.bind(this),
    SelectQueryNode: this.visitSelectQuery.bind(this),
    SelectionNode: this.visitSelection.bind(this),
    TableNode: this.visitTable.bind(this),
    FromNode: this.visitFrom.bind(this),
    SelectAllNode: this.visitSelectAll.bind(this),
    AndNode: this.visitAnd.bind(this),
    OrNode: this.visitOr.bind(this),
    ValueNode: this.visitValue.bind(this),
    ValueListNode: this.visitValueList.bind(this),
    PrimitiveValueListNode: this.visitPrimitiveValueList.bind(this),
    ParensNode: this.visitParens.bind(this),
    JoinNode: this.visitJoin.bind(this),
    OperatorNode: this.visitOperator.bind(this),
    WhereNode: this.visitWhere.bind(this),
    InsertQueryNode: this.visitInsertQuery.bind(this),
    DeleteQueryNode: this.visitDeleteQuery.bind(this),
    ReturningNode: this.visitReturning.bind(this),
    CreateTableNode: this.visitCreateTable.bind(this),
    AddColumnNode: this.visitAddColumn.bind(this),
    ColumnDefinitionNode: this.visitColumnDefinition.bind(this),
    DropTableNode: this.visitDropTable.bind(this),
    DataTypeNode: this.visitDataType.bind(this),
    OrderByNode: this.visitOrderBy.bind(this),
    OrderByItemNode: this.visitOrderByItem.bind(this),
    GroupByNode: this.visitGroupBy.bind(this),
    GroupByItemNode: this.visitGroupByItem.bind(this),
    UpdateQueryNode: this.visitUpdateQuery.bind(this),
    ColumnUpdateNode: this.visitColumnUpdate.bind(this),
    LimitNode: this.visitLimit.bind(this),
    OffsetNode: this.visitOffset.bind(this),
    OnConflictNode: this.visitOnConflict.bind(this),
    OnDuplicateKeyNode: this.visitOnDuplicateKey.bind(this),
    CreateIndexNode: this.visitCreateIndex.bind(this),
    DropIndexNode: this.visitDropIndex.bind(this),
    ListNode: this.visitList.bind(this),
    PrimaryKeyConstraintNode: this.visitPrimaryKeyConstraint.bind(this),
    UniqueConstraintNode: this.visitUniqueConstraint.bind(this),
    ReferencesNode: this.visitReferences.bind(this),
    CheckConstraintNode: this.visitCheckConstraint.bind(this),
    WithNode: this.visitWith.bind(this),
    CommonTableExpressionNode: this.visitCommonTableExpression.bind(this),
    CommonTableExpressionNameNode: this.visitCommonTableExpressionName.bind(this),
    HavingNode: this.visitHaving.bind(this),
    CreateSchemaNode: this.visitCreateSchema.bind(this),
    DropSchemaNode: this.visitDropSchema.bind(this),
    AlterTableNode: this.visitAlterTable.bind(this),
    DropColumnNode: this.visitDropColumn.bind(this),
    RenameColumnNode: this.visitRenameColumn.bind(this),
    AlterColumnNode: this.visitAlterColumn.bind(this),
    ModifyColumnNode: this.visitModifyColumn.bind(this),
    AddConstraintNode: this.visitAddConstraint.bind(this),
    DropConstraintNode: this.visitDropConstraint.bind(this),
    RenameConstraintNode: this.visitRenameConstraint.bind(this),
    ForeignKeyConstraintNode: this.visitForeignKeyConstraint.bind(this),
    CreateViewNode: this.visitCreateView.bind(this),
    RefreshMaterializedViewNode: this.visitRefreshMaterializedView.bind(this),
    DropViewNode: this.visitDropView.bind(this),
    GeneratedNode: this.visitGenerated.bind(this),
    DefaultValueNode: this.visitDefaultValue.bind(this),
    OnNode: this.visitOn.bind(this),
    ValuesNode: this.visitValues.bind(this),
    SelectModifierNode: this.visitSelectModifier.bind(this),
    CreateTypeNode: this.visitCreateType.bind(this),
    DropTypeNode: this.visitDropType.bind(this),
    ExplainNode: this.visitExplain.bind(this),
    DefaultInsertValueNode: this.visitDefaultInsertValue.bind(this),
    AggregateFunctionNode: this.visitAggregateFunction.bind(this),
    OverNode: this.visitOver.bind(this),
    PartitionByNode: this.visitPartitionBy.bind(this),
    PartitionByItemNode: this.visitPartitionByItem.bind(this),
    SetOperationNode: this.visitSetOperation.bind(this),
    BinaryOperationNode: this.visitBinaryOperation.bind(this),
    UnaryOperationNode: this.visitUnaryOperation.bind(this),
    UsingNode: this.visitUsing.bind(this),
    FunctionNode: this.visitFunction.bind(this),
    CaseNode: this.visitCase.bind(this),
    WhenNode: this.visitWhen.bind(this),
    JSONReferenceNode: this.visitJSONReference.bind(this),
    JSONPathNode: this.visitJSONPath.bind(this),
    JSONPathLegNode: this.visitJSONPathLeg.bind(this),
    JSONOperatorChainNode: this.visitJSONOperatorChain.bind(this),
    TupleNode: this.visitTuple.bind(this),
    MergeQueryNode: this.visitMergeQuery.bind(this),
    MatchedNode: this.visitMatched.bind(this),
    AddIndexNode: this.visitAddIndex.bind(this),
    CastNode: this.visitCast.bind(this),
    FetchNode: this.visitFetch.bind(this),
    TopNode: this.visitTop.bind(this),
    OutputNode: this.visitOutput.bind(this),
    OrActionNode: this.visitOrAction.bind(this),
    CollateNode: this.visitCollate.bind(this)
  });
  visitNode = (node) => {
    this.nodeStack.push(node);
    this.#visitors[node.kind](node);
    this.nodeStack.pop();
  };
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-compiler/default-query-compiler.js
var LIT_WRAP_REGEX = /'/g;
var DefaultQueryCompiler = class extends OperationNodeVisitor {
  #sql = "";
  #parameters = [];
  get numParameters() {
    return this.#parameters.length;
  }
  compileQuery(node, queryId) {
    this.#sql = "";
    this.#parameters = [];
    this.nodeStack.splice(0, this.nodeStack.length);
    this.visitNode(node);
    return freeze({
      query: node,
      queryId,
      sql: this.getSql(),
      parameters: [...this.#parameters]
    });
  }
  getSql() {
    return this.#sql;
  }
  visitSelectQuery(node) {
    var _a8, _b5;
    const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !InsertQueryNode.is(this.parentNode) && !CreateTableNode.is(this.parentNode) && !CreateViewNode.is(this.parentNode) && !SetOperationNode.is(this.parentNode);
    if (this.parentNode === void 0 && node.explain) {
      this.visitNode(node.explain);
      this.append(" ");
    }
    if (wrapInParens) {
      this.append("(");
    }
    if (node.with) {
      this.visitNode(node.with);
      this.append(" ");
    }
    this.append("select");
    if (node.distinctOn) {
      this.append(" ");
      this.compileDistinctOn(node.distinctOn);
    }
    if ((_a8 = node.frontModifiers) == null ? void 0 : _a8.length) {
      this.append(" ");
      this.compileList(node.frontModifiers, " ");
    }
    if (node.top) {
      this.append(" ");
      this.visitNode(node.top);
    }
    if (node.selections) {
      this.append(" ");
      this.compileList(node.selections);
    }
    if (node.from) {
      this.append(" ");
      this.visitNode(node.from);
    }
    if (node.joins) {
      this.append(" ");
      this.compileList(node.joins, " ");
    }
    if (node.where) {
      this.append(" ");
      this.visitNode(node.where);
    }
    if (node.groupBy) {
      this.append(" ");
      this.visitNode(node.groupBy);
    }
    if (node.having) {
      this.append(" ");
      this.visitNode(node.having);
    }
    if (node.setOperations) {
      this.append(" ");
      this.compileList(node.setOperations, " ");
    }
    if (node.orderBy) {
      this.append(" ");
      this.visitNode(node.orderBy);
    }
    if (node.limit) {
      this.append(" ");
      this.visitNode(node.limit);
    }
    if (node.offset) {
      this.append(" ");
      this.visitNode(node.offset);
    }
    if (node.fetch) {
      this.append(" ");
      this.visitNode(node.fetch);
    }
    if ((_b5 = node.endModifiers) == null ? void 0 : _b5.length) {
      this.append(" ");
      this.compileList(this.sortSelectModifiers([...node.endModifiers]), " ");
    }
    if (wrapInParens) {
      this.append(")");
    }
  }
  visitFrom(node) {
    this.append("from ");
    this.compileList(node.froms);
  }
  visitSelection(node) {
    this.visitNode(node.selection);
  }
  visitColumn(node) {
    this.visitNode(node.column);
  }
  compileDistinctOn(expressions) {
    this.append("distinct on (");
    this.compileList(expressions);
    this.append(")");
  }
  compileList(nodes, separator = ", ") {
    const lastIndex = nodes.length - 1;
    for (let i2 = 0; i2 <= lastIndex; i2++) {
      this.visitNode(nodes[i2]);
      if (i2 < lastIndex) {
        this.append(separator);
      }
    }
  }
  visitWhere(node) {
    this.append("where ");
    this.visitNode(node.where);
  }
  visitHaving(node) {
    this.append("having ");
    this.visitNode(node.having);
  }
  visitInsertQuery(node) {
    var _a8;
    const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !RawNode.is(this.parentNode) && !WhenNode.is(this.parentNode);
    if (this.parentNode === void 0 && node.explain) {
      this.visitNode(node.explain);
      this.append(" ");
    }
    if (wrapInParens) {
      this.append("(");
    }
    if (node.with) {
      this.visitNode(node.with);
      this.append(" ");
    }
    this.append(node.replace ? "replace" : "insert");
    if (node.ignore) {
      logOnce("`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead.");
      this.append(" ignore");
    }
    if (node.orAction) {
      this.append(" ");
      this.visitNode(node.orAction);
    }
    if (node.top) {
      this.append(" ");
      this.visitNode(node.top);
    }
    if (node.into) {
      this.append(" into ");
      this.visitNode(node.into);
    }
    if (node.columns) {
      this.append(" (");
      this.compileList(node.columns);
      this.append(")");
    }
    if (node.output) {
      this.append(" ");
      this.visitNode(node.output);
    }
    if (node.values) {
      this.append(" ");
      this.visitNode(node.values);
    }
    if (node.defaultValues) {
      this.append(" ");
      this.append("default values");
    }
    if (node.onConflict) {
      this.append(" ");
      this.visitNode(node.onConflict);
    }
    if (node.onDuplicateKey) {
      this.append(" ");
      this.visitNode(node.onDuplicateKey);
    }
    if (node.returning) {
      this.append(" ");
      this.visitNode(node.returning);
    }
    if (wrapInParens) {
      this.append(")");
    }
    if ((_a8 = node.endModifiers) == null ? void 0 : _a8.length) {
      this.append(" ");
      this.compileList(node.endModifiers, " ");
    }
  }
  visitValues(node) {
    this.append("values ");
    this.compileList(node.values);
  }
  visitDeleteQuery(node) {
    var _a8;
    const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !RawNode.is(this.parentNode);
    if (this.parentNode === void 0 && node.explain) {
      this.visitNode(node.explain);
      this.append(" ");
    }
    if (wrapInParens) {
      this.append("(");
    }
    if (node.with) {
      this.visitNode(node.with);
      this.append(" ");
    }
    this.append("delete ");
    if (node.top) {
      this.visitNode(node.top);
      this.append(" ");
    }
    this.visitNode(node.from);
    if (node.output) {
      this.append(" ");
      this.visitNode(node.output);
    }
    if (node.using) {
      this.append(" ");
      this.visitNode(node.using);
    }
    if (node.joins) {
      this.append(" ");
      this.compileList(node.joins, " ");
    }
    if (node.where) {
      this.append(" ");
      this.visitNode(node.where);
    }
    if (node.orderBy) {
      this.append(" ");
      this.visitNode(node.orderBy);
    }
    if (node.limit) {
      this.append(" ");
      this.visitNode(node.limit);
    }
    if (node.returning) {
      this.append(" ");
      this.visitNode(node.returning);
    }
    if (wrapInParens) {
      this.append(")");
    }
    if ((_a8 = node.endModifiers) == null ? void 0 : _a8.length) {
      this.append(" ");
      this.compileList(node.endModifiers, " ");
    }
  }
  visitReturning(node) {
    this.append("returning ");
    this.compileList(node.selections);
  }
  visitAlias(node) {
    this.visitNode(node.node);
    this.append(" as ");
    this.visitNode(node.alias);
  }
  visitReference(node) {
    if (node.table) {
      this.visitNode(node.table);
      this.append(".");
    }
    this.visitNode(node.column);
  }
  visitSelectAll(_3) {
    this.append("*");
  }
  visitIdentifier(node) {
    this.append(this.getLeftIdentifierWrapper());
    this.compileUnwrappedIdentifier(node);
    this.append(this.getRightIdentifierWrapper());
  }
  compileUnwrappedIdentifier(node) {
    if (!isString(node.name)) {
      throw new Error("a non-string identifier was passed to compileUnwrappedIdentifier.");
    }
    this.append(this.sanitizeIdentifier(node.name));
  }
  visitAnd(node) {
    this.visitNode(node.left);
    this.append(" and ");
    this.visitNode(node.right);
  }
  visitOr(node) {
    this.visitNode(node.left);
    this.append(" or ");
    this.visitNode(node.right);
  }
  visitValue(node) {
    if (node.immediate) {
      this.appendImmediateValue(node.value);
    } else {
      this.appendValue(node.value);
    }
  }
  visitValueList(node) {
    this.append("(");
    this.compileList(node.values);
    this.append(")");
  }
  visitTuple(node) {
    this.append("(");
    this.compileList(node.values);
    this.append(")");
  }
  visitPrimitiveValueList(node) {
    this.append("(");
    const { values } = node;
    for (let i2 = 0; i2 < values.length; ++i2) {
      this.appendValue(values[i2]);
      if (i2 !== values.length - 1) {
        this.append(", ");
      }
    }
    this.append(")");
  }
  visitParens(node) {
    this.append("(");
    this.visitNode(node.node);
    this.append(")");
  }
  visitJoin(node) {
    this.append(JOIN_TYPE_SQL[node.joinType]);
    this.append(" ");
    this.visitNode(node.table);
    if (node.on) {
      this.append(" ");
      this.visitNode(node.on);
    }
  }
  visitOn(node) {
    this.append("on ");
    this.visitNode(node.on);
  }
  visitRaw(node) {
    const { sqlFragments, parameters: params } = node;
    for (let i2 = 0; i2 < sqlFragments.length; ++i2) {
      this.append(sqlFragments[i2]);
      if (params.length > i2) {
        this.visitNode(params[i2]);
      }
    }
  }
  visitOperator(node) {
    this.append(node.operator);
  }
  visitTable(node) {
    this.visitNode(node.table);
  }
  visitSchemableIdentifier(node) {
    if (node.schema) {
      this.visitNode(node.schema);
      this.append(".");
    }
    this.visitNode(node.identifier);
  }
  visitCreateTable(node) {
    var _a8, _b5;
    this.append("create ");
    if ((_a8 = node.frontModifiers) == null ? void 0 : _a8.length) {
      this.compileList(node.frontModifiers, " ");
      this.append(" ");
    }
    if (node.temporary) {
      this.append("temporary ");
    }
    this.append("table ");
    if (node.ifNotExists) {
      this.append("if not exists ");
    }
    this.visitNode(node.table);
    if (!node.selectQuery) {
      this.append(" (");
      this.compileList([...node.columns, ...node.constraints ?? []]);
      this.append(")");
    }
    if (node.onCommit) {
      this.append(" on commit ");
      this.append(node.onCommit);
    }
    if ((_b5 = node.endModifiers) == null ? void 0 : _b5.length) {
      this.append(" ");
      this.compileList(node.endModifiers, " ");
    }
    if (node.selectQuery) {
      this.append(" as ");
      this.visitNode(node.selectQuery);
    }
  }
  visitColumnDefinition(node) {
    if (node.ifNotExists) {
      this.append("if not exists ");
    }
    this.visitNode(node.column);
    this.append(" ");
    this.visitNode(node.dataType);
    if (node.unsigned) {
      this.append(" unsigned");
    }
    if (node.frontModifiers && node.frontModifiers.length > 0) {
      this.append(" ");
      this.compileList(node.frontModifiers, " ");
    }
    if (node.generated) {
      this.append(" ");
      this.visitNode(node.generated);
    }
    if (node.identity) {
      this.append(" identity");
    }
    if (node.defaultTo) {
      this.append(" ");
      this.visitNode(node.defaultTo);
    }
    if (node.notNull) {
      this.append(" not null");
    }
    if (node.unique) {
      this.append(" unique");
    }
    if (node.nullsNotDistinct) {
      this.append(" nulls not distinct");
    }
    if (node.primaryKey) {
      this.append(" primary key");
    }
    if (node.autoIncrement) {
      this.append(" ");
      this.append(this.getAutoIncrement());
    }
    if (node.references) {
      this.append(" ");
      this.visitNode(node.references);
    }
    if (node.check) {
      this.append(" ");
      this.visitNode(node.check);
    }
    if (node.endModifiers && node.endModifiers.length > 0) {
      this.append(" ");
      this.compileList(node.endModifiers, " ");
    }
  }
  getAutoIncrement() {
    return "auto_increment";
  }
  visitReferences(node) {
    this.append("references ");
    this.visitNode(node.table);
    this.append(" (");
    this.compileList(node.columns);
    this.append(")");
    if (node.onDelete) {
      this.append(" on delete ");
      this.append(node.onDelete);
    }
    if (node.onUpdate) {
      this.append(" on update ");
      this.append(node.onUpdate);
    }
  }
  visitDropTable(node) {
    this.append("drop table ");
    if (node.ifExists) {
      this.append("if exists ");
    }
    this.visitNode(node.table);
    if (node.cascade) {
      this.append(" cascade");
    }
  }
  visitDataType(node) {
    this.append(node.dataType);
  }
  visitOrderBy(node) {
    this.append("order by ");
    this.compileList(node.items);
  }
  visitOrderByItem(node) {
    this.visitNode(node.orderBy);
    if (node.collation) {
      this.append(" ");
      this.visitNode(node.collation);
    }
    if (node.direction) {
      this.append(" ");
      this.visitNode(node.direction);
    }
    if (node.nulls) {
      this.append(" nulls ");
      this.append(node.nulls);
    }
  }
  visitGroupBy(node) {
    this.append("group by ");
    this.compileList(node.items);
  }
  visitGroupByItem(node) {
    this.visitNode(node.groupBy);
  }
  visitUpdateQuery(node) {
    var _a8;
    const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !RawNode.is(this.parentNode) && !WhenNode.is(this.parentNode);
    if (this.parentNode === void 0 && node.explain) {
      this.visitNode(node.explain);
      this.append(" ");
    }
    if (wrapInParens) {
      this.append("(");
    }
    if (node.with) {
      this.visitNode(node.with);
      this.append(" ");
    }
    this.append("update ");
    if (node.top) {
      this.visitNode(node.top);
      this.append(" ");
    }
    if (node.table) {
      this.visitNode(node.table);
      this.append(" ");
    }
    this.append("set ");
    if (node.updates) {
      this.compileList(node.updates);
    }
    if (node.output) {
      this.append(" ");
      this.visitNode(node.output);
    }
    if (node.from) {
      this.append(" ");
      this.visitNode(node.from);
    }
    if (node.joins) {
      if (!node.from) {
        throw new Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins");
      }
      this.append(" ");
      this.compileList(node.joins, " ");
    }
    if (node.where) {
      this.append(" ");
      this.visitNode(node.where);
    }
    if (node.returning) {
      this.append(" ");
      this.visitNode(node.returning);
    }
    if (node.orderBy) {
      this.append(" ");
      this.visitNode(node.orderBy);
    }
    if (node.limit) {
      this.append(" ");
      this.visitNode(node.limit);
    }
    if (wrapInParens) {
      this.append(")");
    }
    if ((_a8 = node.endModifiers) == null ? void 0 : _a8.length) {
      this.append(" ");
      this.compileList(node.endModifiers, " ");
    }
  }
  visitColumnUpdate(node) {
    this.visitNode(node.column);
    this.append(" = ");
    this.visitNode(node.value);
  }
  visitLimit(node) {
    this.append("limit ");
    this.visitNode(node.limit);
  }
  visitOffset(node) {
    this.append("offset ");
    this.visitNode(node.offset);
  }
  visitOnConflict(node) {
    this.append("on conflict");
    if (node.columns) {
      this.append(" (");
      this.compileList(node.columns);
      this.append(")");
    } else if (node.constraint) {
      this.append(" on constraint ");
      this.visitNode(node.constraint);
    } else if (node.indexExpression) {
      this.append(" (");
      this.visitNode(node.indexExpression);
      this.append(")");
    }
    if (node.indexWhere) {
      this.append(" ");
      this.visitNode(node.indexWhere);
    }
    if (node.doNothing === true) {
      this.append(" do nothing");
    } else if (node.updates) {
      this.append(" do update set ");
      this.compileList(node.updates);
      if (node.updateWhere) {
        this.append(" ");
        this.visitNode(node.updateWhere);
      }
    }
  }
  visitOnDuplicateKey(node) {
    this.append("on duplicate key update ");
    this.compileList(node.updates);
  }
  visitCreateIndex(node) {
    this.append("create ");
    if (node.unique) {
      this.append("unique ");
    }
    this.append("index ");
    if (node.ifNotExists) {
      this.append("if not exists ");
    }
    this.visitNode(node.name);
    if (node.table) {
      this.append(" on ");
      this.visitNode(node.table);
    }
    if (node.using) {
      this.append(" using ");
      this.visitNode(node.using);
    }
    if (node.columns) {
      this.append(" (");
      this.compileList(node.columns);
      this.append(")");
    }
    if (node.nullsNotDistinct) {
      this.append(" nulls not distinct");
    }
    if (node.where) {
      this.append(" ");
      this.visitNode(node.where);
    }
  }
  visitDropIndex(node) {
    this.append("drop index ");
    if (node.ifExists) {
      this.append("if exists ");
    }
    this.visitNode(node.name);
    if (node.table) {
      this.append(" on ");
      this.visitNode(node.table);
    }
    if (node.cascade) {
      this.append(" cascade");
    }
  }
  visitCreateSchema(node) {
    this.append("create schema ");
    if (node.ifNotExists) {
      this.append("if not exists ");
    }
    this.visitNode(node.schema);
  }
  visitDropSchema(node) {
    this.append("drop schema ");
    if (node.ifExists) {
      this.append("if exists ");
    }
    this.visitNode(node.schema);
    if (node.cascade) {
      this.append(" cascade");
    }
  }
  visitPrimaryKeyConstraint(node) {
    if (node.name) {
      this.append("constraint ");
      this.visitNode(node.name);
      this.append(" ");
    }
    this.append("primary key (");
    this.compileList(node.columns);
    this.append(")");
    this.buildDeferrable(node);
  }
  buildDeferrable(node) {
    if (node.deferrable !== void 0) {
      if (node.deferrable) {
        this.append(" deferrable");
      } else {
        this.append(" not deferrable");
      }
    }
    if (node.initiallyDeferred !== void 0) {
      if (node.initiallyDeferred) {
        this.append(" initially deferred");
      } else {
        this.append(" initially immediate");
      }
    }
  }
  visitUniqueConstraint(node) {
    if (node.name) {
      this.append("constraint ");
      this.visitNode(node.name);
      this.append(" ");
    }
    this.append("unique");
    if (node.nullsNotDistinct) {
      this.append(" nulls not distinct");
    }
    this.append(" (");
    this.compileList(node.columns);
    this.append(")");
    this.buildDeferrable(node);
  }
  visitCheckConstraint(node) {
    if (node.name) {
      this.append("constraint ");
      this.visitNode(node.name);
      this.append(" ");
    }
    this.append("check (");
    this.visitNode(node.expression);
    this.append(")");
  }
  visitForeignKeyConstraint(node) {
    if (node.name) {
      this.append("constraint ");
      this.visitNode(node.name);
      this.append(" ");
    }
    this.append("foreign key (");
    this.compileList(node.columns);
    this.append(") ");
    this.visitNode(node.references);
    if (node.onDelete) {
      this.append(" on delete ");
      this.append(node.onDelete);
    }
    if (node.onUpdate) {
      this.append(" on update ");
      this.append(node.onUpdate);
    }
    this.buildDeferrable(node);
  }
  visitList(node) {
    this.compileList(node.items);
  }
  visitWith(node) {
    this.append("with ");
    if (node.recursive) {
      this.append("recursive ");
    }
    this.compileList(node.expressions);
  }
  visitCommonTableExpression(node) {
    this.visitNode(node.name);
    this.append(" as ");
    if (isBoolean(node.materialized)) {
      if (!node.materialized) {
        this.append("not ");
      }
      this.append("materialized ");
    }
    this.visitNode(node.expression);
  }
  visitCommonTableExpressionName(node) {
    this.visitNode(node.table);
    if (node.columns) {
      this.append("(");
      this.compileList(node.columns);
      this.append(")");
    }
  }
  visitAlterTable(node) {
    this.append("alter table ");
    this.visitNode(node.table);
    this.append(" ");
    if (node.renameTo) {
      this.append("rename to ");
      this.visitNode(node.renameTo);
    }
    if (node.setSchema) {
      this.append("set schema ");
      this.visitNode(node.setSchema);
    }
    if (node.addConstraint) {
      this.visitNode(node.addConstraint);
    }
    if (node.dropConstraint) {
      this.visitNode(node.dropConstraint);
    }
    if (node.renameConstraint) {
      this.visitNode(node.renameConstraint);
    }
    if (node.columnAlterations) {
      this.compileColumnAlterations(node.columnAlterations);
    }
    if (node.addIndex) {
      this.visitNode(node.addIndex);
    }
    if (node.dropIndex) {
      this.visitNode(node.dropIndex);
    }
  }
  visitAddColumn(node) {
    this.append("add column ");
    this.visitNode(node.column);
  }
  visitRenameColumn(node) {
    this.append("rename column ");
    this.visitNode(node.column);
    this.append(" to ");
    this.visitNode(node.renameTo);
  }
  visitDropColumn(node) {
    this.append("drop column ");
    this.visitNode(node.column);
  }
  visitAlterColumn(node) {
    this.append("alter column ");
    this.visitNode(node.column);
    this.append(" ");
    if (node.dataType) {
      if (this.announcesNewColumnDataType()) {
        this.append("type ");
      }
      this.visitNode(node.dataType);
      if (node.dataTypeExpression) {
        this.append("using ");
        this.visitNode(node.dataTypeExpression);
      }
    }
    if (node.setDefault) {
      this.append("set default ");
      this.visitNode(node.setDefault);
    }
    if (node.dropDefault) {
      this.append("drop default");
    }
    if (node.setNotNull) {
      this.append("set not null");
    }
    if (node.dropNotNull) {
      this.append("drop not null");
    }
  }
  visitModifyColumn(node) {
    this.append("modify column ");
    this.visitNode(node.column);
  }
  visitAddConstraint(node) {
    this.append("add ");
    this.visitNode(node.constraint);
  }
  visitDropConstraint(node) {
    this.append("drop constraint ");
    if (node.ifExists) {
      this.append("if exists ");
    }
    this.visitNode(node.constraintName);
    if (node.modifier === "cascade") {
      this.append(" cascade");
    } else if (node.modifier === "restrict") {
      this.append(" restrict");
    }
  }
  visitRenameConstraint(node) {
    this.append("rename constraint ");
    this.visitNode(node.oldName);
    this.append(" to ");
    this.visitNode(node.newName);
  }
  visitSetOperation(node) {
    this.append(node.operator);
    this.append(" ");
    if (node.all) {
      this.append("all ");
    }
    this.visitNode(node.expression);
  }
  visitCreateView(node) {
    this.append("create ");
    if (node.orReplace) {
      this.append("or replace ");
    }
    if (node.materialized) {
      this.append("materialized ");
    }
    if (node.temporary) {
      this.append("temporary ");
    }
    this.append("view ");
    if (node.ifNotExists) {
      this.append("if not exists ");
    }
    this.visitNode(node.name);
    this.append(" ");
    if (node.columns) {
      this.append("(");
      this.compileList(node.columns);
      this.append(") ");
    }
    if (node.as) {
      this.append("as ");
      this.visitNode(node.as);
    }
  }
  visitRefreshMaterializedView(node) {
    this.append("refresh materialized view ");
    if (node.concurrently) {
      this.append("concurrently ");
    }
    this.visitNode(node.name);
    if (node.withNoData) {
      this.append(" with no data");
    } else {
      this.append(" with data");
    }
  }
  visitDropView(node) {
    this.append("drop ");
    if (node.materialized) {
      this.append("materialized ");
    }
    this.append("view ");
    if (node.ifExists) {
      this.append("if exists ");
    }
    this.visitNode(node.name);
    if (node.cascade) {
      this.append(" cascade");
    }
  }
  visitGenerated(node) {
    this.append("generated ");
    if (node.always) {
      this.append("always ");
    }
    if (node.byDefault) {
      this.append("by default ");
    }
    this.append("as ");
    if (node.identity) {
      this.append("identity");
    }
    if (node.expression) {
      this.append("(");
      this.visitNode(node.expression);
      this.append(")");
    }
    if (node.stored) {
      this.append(" stored");
    }
  }
  visitDefaultValue(node) {
    this.append("default ");
    this.visitNode(node.defaultValue);
  }
  visitSelectModifier(node) {
    if (node.rawModifier) {
      this.visitNode(node.rawModifier);
    } else {
      this.append(SELECT_MODIFIER_SQL[node.modifier]);
    }
    if (node.of) {
      this.append(" of ");
      this.compileList(node.of, ", ");
    }
  }
  visitCreateType(node) {
    this.append("create type ");
    this.visitNode(node.name);
    if (node.enum) {
      this.append(" as enum ");
      this.visitNode(node.enum);
    }
  }
  visitDropType(node) {
    this.append("drop type ");
    if (node.ifExists) {
      this.append("if exists ");
    }
    this.visitNode(node.name);
  }
  visitExplain(node) {
    this.append("explain");
    if (node.options || node.format) {
      this.append(" ");
      this.append(this.getLeftExplainOptionsWrapper());
      if (node.options) {
        this.visitNode(node.options);
        if (node.format) {
          this.append(this.getExplainOptionsDelimiter());
        }
      }
      if (node.format) {
        this.append("format");
        this.append(this.getExplainOptionAssignment());
        this.append(node.format);
      }
      this.append(this.getRightExplainOptionsWrapper());
    }
  }
  visitDefaultInsertValue(_3) {
    this.append("default");
  }
  visitAggregateFunction(node) {
    this.append(node.func);
    this.append("(");
    if (node.distinct) {
      this.append("distinct ");
    }
    this.compileList(node.aggregated);
    if (node.orderBy) {
      this.append(" ");
      this.visitNode(node.orderBy);
    }
    this.append(")");
    if (node.withinGroup) {
      this.append(" within group (");
      this.visitNode(node.withinGroup);
      this.append(")");
    }
    if (node.filter) {
      this.append(" filter(");
      this.visitNode(node.filter);
      this.append(")");
    }
    if (node.over) {
      this.append(" ");
      this.visitNode(node.over);
    }
  }
  visitOver(node) {
    this.append("over(");
    if (node.partitionBy) {
      this.visitNode(node.partitionBy);
      if (node.orderBy) {
        this.append(" ");
      }
    }
    if (node.orderBy) {
      this.visitNode(node.orderBy);
    }
    this.append(")");
  }
  visitPartitionBy(node) {
    this.append("partition by ");
    this.compileList(node.items);
  }
  visitPartitionByItem(node) {
    this.visitNode(node.partitionBy);
  }
  visitBinaryOperation(node) {
    this.visitNode(node.leftOperand);
    this.append(" ");
    this.visitNode(node.operator);
    this.append(" ");
    this.visitNode(node.rightOperand);
  }
  visitUnaryOperation(node) {
    this.visitNode(node.operator);
    if (!this.isMinusOperator(node.operator)) {
      this.append(" ");
    }
    this.visitNode(node.operand);
  }
  isMinusOperator(node) {
    return OperatorNode.is(node) && node.operator === "-";
  }
  visitUsing(node) {
    this.append("using ");
    this.compileList(node.tables);
  }
  visitFunction(node) {
    this.append(node.func);
    this.append("(");
    this.compileList(node.arguments);
    this.append(")");
  }
  visitCase(node) {
    this.append("case");
    if (node.value) {
      this.append(" ");
      this.visitNode(node.value);
    }
    if (node.when) {
      this.append(" ");
      this.compileList(node.when, " ");
    }
    if (node.else) {
      this.append(" else ");
      this.visitNode(node.else);
    }
    this.append(" end");
    if (node.isStatement) {
      this.append(" case");
    }
  }
  visitWhen(node) {
    this.append("when ");
    this.visitNode(node.condition);
    if (node.result) {
      this.append(" then ");
      this.visitNode(node.result);
    }
  }
  visitJSONReference(node) {
    this.visitNode(node.reference);
    this.visitNode(node.traversal);
  }
  visitJSONPath(node) {
    if (node.inOperator) {
      this.visitNode(node.inOperator);
    }
    this.append("'$");
    for (const pathLeg of node.pathLegs) {
      this.visitNode(pathLeg);
    }
    this.append("'");
  }
  visitJSONPathLeg(node) {
    const isArrayLocation = node.type === "ArrayLocation";
    this.append(isArrayLocation ? "[" : ".");
    this.append(typeof node.value === "string" ? this.sanitizeStringLiteral(node.value) : String(node.value));
    if (isArrayLocation) {
      this.append("]");
    }
  }
  visitJSONOperatorChain(node) {
    for (let i2 = 0, len = node.values.length; i2 < len; i2++) {
      if (i2 === len - 1) {
        this.visitNode(node.operator);
      } else {
        this.append("->");
      }
      this.visitNode(node.values[i2]);
    }
  }
  visitMergeQuery(node) {
    var _a8;
    if (node.with) {
      this.visitNode(node.with);
      this.append(" ");
    }
    this.append("merge ");
    if (node.top) {
      this.visitNode(node.top);
      this.append(" ");
    }
    this.append("into ");
    this.visitNode(node.into);
    if (node.using) {
      this.append(" ");
      this.visitNode(node.using);
    }
    if (node.whens) {
      this.append(" ");
      this.compileList(node.whens, " ");
    }
    if (node.returning) {
      this.append(" ");
      this.visitNode(node.returning);
    }
    if (node.output) {
      this.append(" ");
      this.visitNode(node.output);
    }
    if ((_a8 = node.endModifiers) == null ? void 0 : _a8.length) {
      this.append(" ");
      this.compileList(node.endModifiers, " ");
    }
  }
  visitMatched(node) {
    if (node.not) {
      this.append("not ");
    }
    this.append("matched");
    if (node.bySource) {
      this.append(" by source");
    }
  }
  visitAddIndex(node) {
    this.append("add ");
    if (node.unique) {
      this.append("unique ");
    }
    this.append("index ");
    this.visitNode(node.name);
    if (node.columns) {
      this.append(" (");
      this.compileList(node.columns);
      this.append(")");
    }
    if (node.using) {
      this.append(" using ");
      this.visitNode(node.using);
    }
  }
  visitCast(node) {
    this.append("cast(");
    this.visitNode(node.expression);
    this.append(" as ");
    this.visitNode(node.dataType);
    this.append(")");
  }
  visitFetch(node) {
    this.append("fetch next ");
    this.visitNode(node.rowCount);
    this.append(` rows ${node.modifier}`);
  }
  visitOutput(node) {
    this.append("output ");
    this.compileList(node.selections);
  }
  visitTop(node) {
    this.append(`top(${node.expression})`);
    if (node.modifiers) {
      this.append(` ${node.modifiers}`);
    }
  }
  visitOrAction(node) {
    this.append(node.action);
  }
  visitCollate(node) {
    this.append("collate ");
    this.visitNode(node.collation);
  }
  append(str) {
    this.#sql += str;
  }
  appendValue(parameter) {
    this.addParameter(parameter);
    this.append(this.getCurrentParameterPlaceholder());
  }
  getLeftIdentifierWrapper() {
    return '"';
  }
  getRightIdentifierWrapper() {
    return '"';
  }
  getCurrentParameterPlaceholder() {
    return "$" + this.numParameters;
  }
  getLeftExplainOptionsWrapper() {
    return "(";
  }
  getExplainOptionAssignment() {
    return " ";
  }
  getExplainOptionsDelimiter() {
    return ", ";
  }
  getRightExplainOptionsWrapper() {
    return ")";
  }
  sanitizeIdentifier(identifier) {
    const leftWrap = this.getLeftIdentifierWrapper();
    const rightWrap = this.getRightIdentifierWrapper();
    let sanitized = "";
    for (const c3 of identifier) {
      sanitized += c3;
      if (c3 === leftWrap) {
        sanitized += leftWrap;
      } else if (c3 === rightWrap) {
        sanitized += rightWrap;
      }
    }
    return sanitized;
  }
  sanitizeStringLiteral(value) {
    return value.replace(LIT_WRAP_REGEX, "''");
  }
  addParameter(parameter) {
    this.#parameters.push(parameter);
  }
  appendImmediateValue(value) {
    if (isString(value)) {
      this.appendStringLiteral(value);
    } else if (isNumber(value) || isBoolean(value) || isBigInt(value)) {
      this.append(value.toString());
    } else if (isNull(value)) {
      this.append("null");
    } else if (isDate(value)) {
      this.appendImmediateValue(value.toISOString());
    } else {
      throw new Error(`invalid immediate value ${value}`);
    }
  }
  appendStringLiteral(value) {
    this.append("'");
    this.append(this.sanitizeStringLiteral(value));
    this.append("'");
  }
  sortSelectModifiers(arr) {
    arr.sort((left, right) => left.modifier && right.modifier ? SELECT_MODIFIER_PRIORITY[left.modifier] - SELECT_MODIFIER_PRIORITY[right.modifier] : 1);
    return freeze(arr);
  }
  compileColumnAlterations(columnAlterations) {
    this.compileList(columnAlterations);
  }
  /**
   * controls whether the dialect adds a "type" keyword before a column's new data
   * type in an ALTER TABLE statement.
   */
  announcesNewColumnDataType() {
    return true;
  }
};
var SELECT_MODIFIER_SQL = freeze({
  ForKeyShare: "for key share",
  ForNoKeyUpdate: "for no key update",
  ForUpdate: "for update",
  ForShare: "for share",
  NoWait: "nowait",
  SkipLocked: "skip locked",
  Distinct: "distinct"
});
var SELECT_MODIFIER_PRIORITY = freeze({
  ForKeyShare: 1,
  ForNoKeyUpdate: 1,
  ForUpdate: 1,
  ForShare: 1,
  NoWait: 2,
  SkipLocked: 2,
  Distinct: 0
});
var JOIN_TYPE_SQL = freeze({
  InnerJoin: "inner join",
  LeftJoin: "left join",
  RightJoin: "right join",
  FullJoin: "full join",
  CrossJoin: "cross join",
  LateralInnerJoin: "inner join lateral",
  LateralLeftJoin: "left join lateral",
  LateralCrossJoin: "cross join lateral",
  OuterApply: "outer apply",
  CrossApply: "cross apply",
  Using: "using"
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/query-compiler/compiled-query.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var CompiledQuery = freeze({
  raw(sql2, parameters = []) {
    return freeze({
      sql: sql2,
      query: RawNode.createWithSql(sql2),
      parameters: freeze(parameters),
      queryId: createQueryId()
    });
  }
});

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/dialect/dialect-adapter-base.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DialectAdapterBase = class {
  get supportsCreateIfNotExists() {
    return true;
  }
  get supportsTransactionalDdl() {
    return false;
  }
  get supportsReturning() {
    return false;
  }
  get supportsOutput() {
    return false;
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-query-compiler.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ID_WRAP_REGEX = /"/g;
var SqliteQueryCompiler = class extends DefaultQueryCompiler {
  visitOrAction(node) {
    this.append("or ");
    this.append(node.action);
  }
  getCurrentParameterPlaceholder() {
    return "?";
  }
  getLeftExplainOptionsWrapper() {
    return "";
  }
  getRightExplainOptionsWrapper() {
    return "";
  }
  getLeftIdentifierWrapper() {
    return '"';
  }
  getRightIdentifierWrapper() {
    return '"';
  }
  getAutoIncrement() {
    return "autoincrement";
  }
  sanitizeIdentifier(identifier) {
    return identifier.replace(ID_WRAP_REGEX, '""');
  }
  visitDefaultInsertValue(_3) {
    this.append("null");
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-introspector.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/migration/migrator.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var DEFAULT_MIGRATION_TABLE = "kysely_migration";
var DEFAULT_MIGRATION_LOCK_TABLE = "kysely_migration_lock";
var NO_MIGRATIONS = freeze({ __noMigrations__: true });

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-introspector.js
var SqliteIntrospector = class {
  #db;
  constructor(db) {
    this.#db = db;
  }
  async getSchemas() {
    return [];
  }
  async getTables(options = { withInternalKyselyTables: false }) {
    return await this.#getTableMetadata(options);
  }
  async getMetadata(options) {
    return {
      tables: await this.getTables(options)
    };
  }
  #tablesQuery(qb, options) {
    let tablesQuery = qb.selectFrom("sqlite_master").where("type", "in", ["table", "view"]).where("name", "not like", "sqlite_%").select(["name", "sql", "type"]).orderBy("name");
    if (!options.withInternalKyselyTables) {
      tablesQuery = tablesQuery.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE);
    }
    return tablesQuery;
  }
  async #getTableMetadata(options) {
    const tablesResult = await this.#tablesQuery(this.#db, options).execute();
    const tableMetadata = await this.#db.with("table_list", (qb) => this.#tablesQuery(qb, options)).selectFrom([
      "table_list as tl",
      sql`pragma_table_info(tl.name)`.as("p")
    ]).select([
      "tl.name as table",
      "p.cid",
      "p.name",
      "p.type",
      "p.notnull",
      "p.dflt_value",
      "p.pk"
    ]).orderBy("tl.name").orderBy("p.cid").execute();
    const columnsByTable = {};
    for (const row of tableMetadata) {
      columnsByTable[row.table] ??= [];
      columnsByTable[row.table].push(row);
    }
    return tablesResult.map(({ name, sql: sql2, type }) => {
      var _a8, _b5, _c, _d, _e;
      let autoIncrementCol = (_e = (_d = (_c = (_b5 = (_a8 = sql2 == null ? void 0 : sql2.split(/[\(\),]/)) == null ? void 0 : _a8.find((it) => it.toLowerCase().includes("autoincrement"))) == null ? void 0 : _b5.trimStart()) == null ? void 0 : _c.split(/\s+/)) == null ? void 0 : _d[0]) == null ? void 0 : _e.replace(/["`]/g, "");
      const columns = columnsByTable[name] ?? [];
      if (!autoIncrementCol) {
        const pkCols = columns.filter((r3) => r3.pk > 0);
        if (pkCols.length === 1 && pkCols[0].type.toLowerCase() === "integer") {
          autoIncrementCol = pkCols[0].name;
        }
      }
      return {
        name,
        isView: type === "view",
        columns: columns.map((col) => ({
          name: col.name,
          dataType: col.type,
          isNullable: !col.notnull,
          isAutoIncrementing: col.name === autoIncrementCol,
          hasDefaultValue: col.dflt_value != null,
          comment: void 0
        }))
      };
    });
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-adapter.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var SqliteAdapter = class extends DialectAdapterBase {
  get supportsTransactionalDdl() {
    return false;
  }
  get supportsReturning() {
    return true;
  }
  async acquireMigrationLock(_db, _opt) {
  }
  async releaseMigrationLock(_db, _opt) {
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/plugin/camel-case/camel-case-plugin.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/plugin/camel-case/camel-case-transformer.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var SnakeCaseTransformer = class extends OperationNodeTransformer {
  #snakeCase;
  constructor(snakeCase) {
    super();
    this.#snakeCase = snakeCase;
  }
  transformIdentifier(node, queryId) {
    node = super.transformIdentifier(node, queryId);
    return {
      ...node,
      name: this.#snakeCase(node.name)
    };
  }
};

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/plugin/camel-case/camel-case.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function createSnakeCaseMapper({ upperCase = false, underscoreBeforeDigits = false, underscoreBetweenUppercaseLetters = false } = {}) {
  return memoize((str) => {
    if (str.length === 0) {
      return str;
    }
    const upper = str.toUpperCase();
    const lower = str.toLowerCase();
    let out = lower[0];
    for (let i2 = 1, l2 = str.length; i2 < l2; ++i2) {
      const char = str[i2];
      const prevChar = str[i2 - 1];
      const upperChar = upper[i2];
      const prevUpperChar = upper[i2 - 1];
      const lowerChar = lower[i2];
      const prevLowerChar = lower[i2 - 1];
      if (underscoreBeforeDigits && isDigit(char) && !isDigit(prevChar) && !out.endsWith("_")) {
        out += "_" + char;
        continue;
      }
      if (char === upperChar && upperChar !== lowerChar) {
        const prevCharacterIsUppercase = prevChar === prevUpperChar && prevUpperChar !== prevLowerChar;
        if (underscoreBetweenUppercaseLetters || !prevCharacterIsUppercase) {
          out += "_" + lowerChar;
        } else {
          out += lowerChar;
        }
      } else {
        out += char;
      }
    }
    if (upperCase) {
      return out.toUpperCase();
    } else {
      return out;
    }
  });
}
function createCamelCaseMapper({ upperCase = false } = {}) {
  return memoize((str) => {
    if (str.length === 0) {
      return str;
    }
    if (upperCase && isAllUpperCaseSnakeCase(str)) {
      str = str.toLowerCase();
    }
    let out = str[0];
    for (let i2 = 1, l2 = str.length; i2 < l2; ++i2) {
      const char = str[i2];
      const prevChar = str[i2 - 1];
      if (char !== "_") {
        if (prevChar === "_") {
          out += char.toUpperCase();
        } else {
          out += char;
        }
      }
    }
    return out;
  });
}
function isAllUpperCaseSnakeCase(str) {
  for (let i2 = 1, l2 = str.length; i2 < l2; ++i2) {
    const char = str[i2];
    if (char !== "_" && char !== char.toUpperCase()) {
      return false;
    }
  }
  return true;
}
function isDigit(char) {
  return char >= "0" && char <= "9";
}
function memoize(func) {
  const cache = /* @__PURE__ */ new Map();
  return (str) => {
    let mapped = cache.get(str);
    if (!mapped) {
      mapped = func(str);
      cache.set(str, mapped);
    }
    return mapped;
  };
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/plugin/camel-case/camel-case-plugin.js
var CamelCasePlugin = class {
  opt;
  #camelCase;
  #snakeCase;
  #snakeCaseTransformer;
  constructor(opt = {}) {
    this.opt = opt;
    this.#camelCase = createCamelCaseMapper(opt);
    this.#snakeCase = createSnakeCaseMapper(opt);
    this.#snakeCaseTransformer = new SnakeCaseTransformer(this.snakeCase.bind(this));
  }
  transformQuery(args) {
    return this.#snakeCaseTransformer.transformNode(args.node, args.queryId);
  }
  async transformResult(args) {
    if (args.result.rows && Array.isArray(args.result.rows)) {
      return {
        ...args.result,
        rows: args.result.rows.map((row) => this.mapRow(row))
      };
    }
    return args.result;
  }
  mapRow(row) {
    return Object.keys(row).reduce((obj, key) => {
      let value = row[key];
      if (Array.isArray(value)) {
        value = value.map((it) => canMap(it, this.opt) ? this.mapRow(it) : it);
      } else if (canMap(value, this.opt)) {
        value = this.mapRow(value);
      }
      obj[this.camelCase(key)] = value;
      return obj;
    }, {});
  }
  snakeCase(str) {
    return this.#snakeCase(str);
  }
  camelCase(str) {
    return this.#camelCase(str);
  }
};
function canMap(obj, opt) {
  return isPlainObject(obj) && !(opt == null ? void 0 : opt.maintainNestedObjectKeys);
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/database/execute-sync.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function executeSync(args) {
  const compiledQuery = args.query.compile();
  const columnNames = [];
  try {
    const result = args.lix.sqlite.exec({
      sql: compiledQuery.sql,
      bind: compiledQuery.parameters,
      returnValue: "resultRows",
      columnNames
    });
    return result.map((row) => {
      const obj = {};
      columnNames.forEach((columnName, index) => {
        obj[columnName] = row[index];
      });
      return obj;
    });
  } catch (e2) {
    console.error(`Error in executeSync for query:

${compiledQuery.sql}

`, e2);
    return [];
  }
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/query-filter/change-is-leaf-in-version.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function changeIsLeafInVersion(version2) {
  return sql`
    change.id IN (
      WITH RECURSIVE version_changes(id) AS (
        SELECT change_id AS id
        FROM version_change
        WHERE version_id = ${version2.id}
        UNION ALL
        SELECT change_edge.parent_id AS id
        FROM change_edge
        INNER JOIN version_changes ON version_changes.id = change_edge.child_id
      )
      SELECT id FROM version_changes
      WHERE id NOT IN (
        SELECT parent_id
        FROM change_edge
        WHERE child_id IN (SELECT id FROM version_changes)
      )
    )
  `;
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/version/update-changes-in-version.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
async function updateChangesInVersion(args) {
  for (const change of args.changes ?? []) {
    executeSync({
      lix: args.lix,
      query: args.lix.db.insertInto("version_change").values({
        version_id: args.version.id,
        change_id: change.id,
        entity_id: change.entity_id,
        schema_key: change.schema_key,
        file_id: change.file_id
      }).onConflict((oc) => oc.doUpdateSet((eb) => ({ change_id: eb.ref("excluded.change_id") })))
    });
  }
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/change/create-change.js
async function createChange(args, options) {
  const optionsWithDefaults = {
    updateVersionChanges: true,
    ...options
  };
  if (args.authors.length === 0) {
    throw new Error("At least one author is required");
  }
  const snapshot = executeSync({
    lix: args.lix,
    query: args.lix.db.insertInto("snapshot").values({
      content: args.snapshotContent ?? null
    }).onConflict((oc) => oc.doUpdateSet((eb) => ({
      content: eb.ref("excluded.content")
    }))).returningAll().returning(sql`json(content)`.as("content"))
  })[0];
  snapshot.content = JSON.parse(snapshot.content);
  const change = executeSync({
    lix: args.lix,
    query: args.lix.db.insertInto("change").values({
      entity_id: args.entityId,
      plugin_key: args.pluginKey,
      file_id: args.fileId,
      schema_key: args.schemaKey,
      snapshot_id: snapshot.id
    }).returningAll()
  })[0];
  const parentChange = executeSync({
    lix: args.lix,
    query: args.lix.db.selectFrom("change").where("file_id", "=", change.file_id).where("schema_key", "=", change.schema_key).where("entity_id", "=", change.entity_id).where(changeIsLeafInVersion(args.version)).select("id")
  })[0];
  if (parentChange) {
    executeSync({
      lix: args.lix,
      query: args.lix.db.insertInto("change_edge").values({
        parent_id: parentChange.id,
        child_id: change.id
      })
    });
  }
  for (const author of args.authors) {
    try {
      executeSync({
        lix: args.lix,
        query: args.lix.db.insertInto("change_author").values({
          change_id: change.id,
          account_id: author.id
        })
      });
    } catch (e2) {
      console.log(e2);
    }
  }
  if (optionsWithDefaults.updateVersionChanges) {
    updateChangesInVersion({
      lix: { ...args.lix },
      changes: [change],
      version: args.version
    });
  }
  return change;
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/change/apply-changes.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/file-queue/with-skip-file-queue.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
async function withSkipFileQueue(db, operation) {
  const executeInTransaction = async (trx) => {
    const queryEntryBefore = await trx.selectFrom("file_queue").selectAll().orderBy("id", "desc").executeTakeFirst();
    const result = await operation(trx);
    await trx.deleteFrom("file_queue").where("id", ">", (queryEntryBefore == null ? void 0 : queryEntryBefore.id) ?? 0).execute();
    return result;
  };
  if (db.isTransaction) {
    return executeInTransaction(db);
  } else {
    return db.transaction().execute(executeInTransaction);
  }
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/own-change-control/apply-own-change.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/own-change-control/change-controlled-tables.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var changeControlledTableIds = {
  account: ["id"],
  comment: ["id"],
  change_set: ["id"],
  change_author: ["change_id", "account_id"],
  change_set_element: ["change_set_id", "change_id"],
  change_set_label: ["label_id", "change_set_id"],
  discussion: ["id"],
  file: ["id"],
  key_value: ["key"],
  version: ["id"],
  version_change: ["version_id", "change_id"]
};
function entityIdForRow(tableName, ...values) {
  let entityId = "";
  if (changeControlledTableIds[tableName].length === 1) {
    const index = changeControlledTableIds[tableName].indexOf(
      // @ts-expect-error - no clue why
      changeControlledTableIds[tableName][0]
    );
    entityId = values[index];
  } else {
    for (const column of changeControlledTableIds[tableName]) {
      const index = changeControlledTableIds[tableName].indexOf(
        // @ts-expect-error - no clue why
        column
      );
      if (entityId === "") {
        entityId = values[index];
      } else {
        entityId = [entityId, values[index]].join(",");
      }
    }
  }
  return entityId;
}
function primaryKeysForEntityId(tableName, entitiyId) {
  const primaryKeys = changeControlledTableIds[tableName];
  if (primaryKeys.length === 1) {
    return [[primaryKeys[0], entitiyId]];
  } else {
    return entitiyId.split(",").map((id, index) => [primaryKeys[index], id]);
  }
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/own-change-control/with-skip-own-change-control.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
async function withSkipOwnChangeControl(db, operation) {
  const executeInTransaction = async (trx) => {
    await trx.insertInto("key_value").values({
      key: "lix_skip_own_change_control",
      value: "true",
      skip_change_control: true
    }).onConflict((oc) => oc.doUpdateSet({ value: "true" })).execute();
    const result = await operation(trx);
    await trx.deleteFrom("key_value").where("key", "=", "lix_skip_own_change_control").execute();
    return result;
  };
  if (db.isTransaction) {
    return executeInTransaction(db);
  } else {
    return db.transaction().execute(executeInTransaction);
  }
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/own-change-control/apply-own-change.js
async function applyOwnChanges(args) {
  const executeInTransaction = async (trx) => {
    await withSkipOwnChangeControl(trx, async (trx2) => {
      await trx2.executeQuery(CompiledQuery.raw("PRAGMA defer_foreign_keys = ON;"));
      await Promise.all(args.changes.map(async (change) => {
        if (change.plugin_key !== "lix_own_change_control") {
          throw new Error("Expected 'lix_own_change_control' as plugin key but received " + change.plugin_key);
        }
        const snapshot = await trx2.selectFrom("snapshot").where("id", "=", change.snapshot_id).select("content").executeTakeFirstOrThrow();
        const tableName = change.schema_key.replace(/^lix_/, "").replace(/_table$/, "");
        const primaryKeys = primaryKeysForEntityId(tableName, change.entity_id);
        let query;
        if (snapshot.content === null) {
          query = trx2.deleteFrom(tableName);
          for (const [key, value] of primaryKeys) {
            query = query.where(key, "=", value);
          }
        } else {
          if (tableName === "file") {
            const data = await trx2.selectFrom("file").where("id", "=", change.entity_id).select("data").executeTakeFirst();
            snapshot.content.data = (data == null ? void 0 : data.data) ?? // empty uint8array will trigger applyChanges() to pass an empty file to the plugin
            new Uint8Array();
          }
          query = trx2.insertInto(tableName).values(snapshot.content).onConflict((oc) => oc.doUpdateSet(snapshot.content));
        }
        await query.execute();
      }));
    });
  };
  if (args.lix.db.isTransaction) {
    return await executeInTransaction(args.lix.db);
  } else {
    return await args.lix.db.transaction().execute(executeInTransaction);
  }
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/change/apply-changes.js
async function applyChanges(args) {
  const executeInTransaction = async (trx) => {
    const groupByFile = Object.groupBy(args.changes, (change) => change.file_id);
    const lixOwnChanges = groupByFile["lix_own_change_control"] ?? [];
    delete groupByFile["lix_own_change_control"];
    const plugins = await args.lix.plugin.getAll();
    for (const [fileId, changes] of [
      // applying lix own changes first
      ["lix_own_change_control", lixOwnChanges],
      ...Object.entries(groupByFile)
    ]) {
      if (changes === void 0 || changes.length === 0) {
        continue;
      }
      if (fileId === "lix_own_change_control") {
        await applyOwnChanges({ lix: { ...args.lix, db: trx }, changes });
        continue;
      }
      const groupByPlugin = Object.groupBy(changes, (c3) => c3.plugin_key);
      const file = await trx.selectFrom("file").where("id", "=", fileId).selectAll().executeTakeFirst();
      if (file === void 0) {
        continue;
      } else if (file.data.byteLength === 0) {
        delete file.data;
      }
      for (const [pluginKey, changes2] of Object.entries(groupByPlugin)) {
        if (changes2 === void 0) {
          continue;
        }
        const plugin2 = plugins.find((plugin3) => plugin3.key === pluginKey);
        if (!plugin2) {
          throw new Error(`Plugin with key ${pluginKey} not found`);
        } else if (!plugin2.applyChanges) {
          throw new Error(`Plugin with key ${pluginKey} does not support applying changes`);
        }
        const { fileData } = await plugin2.applyChanges({
          lix: { ...args.lix, db: trx },
          file,
          changes: changes2
        });
        await withSkipFileQueue(trx, async (trx2) => {
          await trx2.updateTable("file").set({ data: fileData }).where("id", "=", fileId).execute();
        });
      }
    }
  };
  if (args.lix.db.isTransaction) {
    return executeInTransaction(args.lix.db);
  } else {
    return args.lix.db.transaction().execute(executeInTransaction);
  }
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/key-value/database-schema.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function applyKeyValueDatabaseSchema(sqlite2) {
  return sqlite2.exec`
	CREATE TABLE IF NOT EXISTS key_value (
		key TEXT PRIMARY KEY,
		value TEXT NOT NULL,

		-- Options
		skip_change_control INT DEFAULT FALSE
	) STRICT;

	INSERT OR IGNORE INTO key_value (key, value)
	VALUES ('lix_id', nano_id(18));

	-- default value for lix sync to false
	-- if not exist to remove conditional logic
	-- if the key exists or not
	INSERT OR IGNORE INTO key_value (key, value, skip_change_control)
	VALUES ('lix_sync', 'false', 1);
`;
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/helpers/sqlite.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/util/json-object-args.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function getJsonObjectArgs(node, table) {
  const args = [];
  for (const { selection: s2 } of node.selections ?? []) {
    if (ReferenceNode.is(s2) && ColumnNode.is(s2.column)) {
      args.push(colName(s2.column.column.name), colRef(table, s2.column.column.name));
    } else if (ColumnNode.is(s2)) {
      args.push(colName(s2.column.name), colRef(table, s2.column.name));
    } else if (AliasNode.is(s2) && IdentifierNode.is(s2.alias)) {
      args.push(colName(s2.alias.name), colRef(table, s2.alias.name));
    } else {
      throw new Error(`can't extract column names from the select query node`);
    }
  }
  return args;
}
function colName(col) {
  return new ExpressionWrapper(ValueNode.createImmediate(col));
}
function colRef(table, col) {
  return new ExpressionWrapper(ReferenceNode.create(ColumnNode.create(col), TableNode.create(table)));
}

// ../../node_modules/.pnpm/kysely@0.28.14/node_modules/kysely/dist/esm/helpers/sqlite.js
function jsonArrayFrom(expr) {
  return sql`(select coalesce(json_group_array(json_object(${sql.join(getSqliteJsonObjectArgs(expr.toOperationNode(), "agg"))})), '[]') from ${expr} as agg)`;
}
function getSqliteJsonObjectArgs(node, table) {
  try {
    return getJsonObjectArgs(node, table);
  } catch {
    throw new Error("SQLite jsonArrayFrom and jsonObjectFrom functions can only handle explicit selections due to limitations of the json_object function. selectAll() is not allowed in the subquery.");
  }
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/file/validate-file-path.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function validateFilePath(path2) {
  if (path2.length === 0) {
    throw new Error("File path must not be empty.");
  }
  if (path2[0] !== "/") {
    throw new Error("File path must start with a slash.\n\nFiles must start with a root slash to identify the path as root.");
  }
  if (path2.endsWith("/")) {
    throw new Error("File path must not end with a slash.\n\nEnding a file with a slash leads to ambiguity whether or not the path is a directory or a file.");
  }
  if (path2.includes("//")) {
    throw new Error("File path must not contain consecutive slashes.\n\nConsecutive slashes lead to ambiguity whether or not the path is a directory or a file.");
  }
  if (path2.includes("\\")) {
    throw new Error("File path must not contain backslashes.\n\nThe restriction might be loosened in the future.");
  }
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/lix/index.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/lix/open-lix.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/sqlite-wasm-kysely@0.3.0_kysely@0.28.14/node_modules/sqlite-wasm-kysely/dist/index.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/sqlite-wasm-kysely@0.3.0_kysely@0.28.14/node_modules/sqlite-wasm-kysely/dist/util/index.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/sqlite-wasm-kysely@0.3.0_kysely@0.28.14/node_modules/sqlite-wasm-kysely/dist/util/contentFromDatabase.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var contentFromDatabase = (db) => {
  return db.sqlite3.capi.sqlite3_js_db_export(db);
};

// ../../node_modules/.pnpm/sqlite-wasm-kysely@0.3.0_kysely@0.28.14/node_modules/sqlite-wasm-kysely/dist/util/createInMemoryDatabase.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/@sqlite.org+sqlite-wasm@3.48.0-build4/node_modules/@sqlite.org/sqlite-wasm/index.mjs
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/@sqlite.org+sqlite-wasm@3.48.0-build4/node_modules/@sqlite.org/sqlite-wasm/sqlite-wasm/jswasm/sqlite3-bundler-friendly.mjs
init_define_ENV_DEFINED_IN_BUILD_STEP();
var sqlite3InitModule = (() => {
  var _scriptName = import.meta.url;
  return function(moduleArg = {}) {
    var moduleRtn;
    var Module = moduleArg;
    var readyPromiseResolve, readyPromiseReject;
    var readyPromise = new Promise((resolve2, reject) => {
      readyPromiseResolve = resolve2;
      readyPromiseReject = reject;
    });
    var ENVIRONMENT_IS_WEB = typeof window == "object";
    var ENVIRONMENT_IS_WORKER = typeof importScripts == "function";
    var ENVIRONMENT_IS_NODE = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string" && process.type != "renderer";
    var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
    const sqlite3InitModuleState = globalThis.sqlite3InitModuleState || Object.assign(/* @__PURE__ */ Object.create(null), {
      debugModule: () => {
      }
    });
    delete globalThis.sqlite3InitModuleState;
    sqlite3InitModuleState.debugModule(
      "globalThis.location =",
      globalThis.location
    );
    var moduleOverrides = Object.assign({}, Module);
    var arguments_ = [];
    var thisProgram = "./this.program";
    var quit_ = (status, toThrow) => {
      throw toThrow;
    };
    var scriptDirectory = "";
    function locateFile(path2) {
      if (Module["locateFile"]) {
        return Module["locateFile"](path2, scriptDirectory);
      }
      return scriptDirectory + path2;
    }
    var readAsync, readBinary;
    if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
      if (ENVIRONMENT_IS_WORKER) {
        scriptDirectory = self.location.href;
      } else if (typeof document != "undefined" && document.currentScript) {
        scriptDirectory = document.currentScript.src;
      }
      if (_scriptName) {
        scriptDirectory = _scriptName;
      }
      if (scriptDirectory.startsWith("blob:")) {
        scriptDirectory = "";
      } else {
        scriptDirectory = scriptDirectory.substr(
          0,
          scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1
        );
      }
      {
        if (ENVIRONMENT_IS_WORKER) {
          readBinary = (url) => {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", url, false);
            xhr.responseType = "arraybuffer";
            xhr.send(null);
            return new Uint8Array(xhr.response);
          };
        }
        readAsync = (url) => {
          return fetch(url, { credentials: "same-origin" }).then((response) => {
            if (response.ok) {
              return response.arrayBuffer();
            }
            return Promise.reject(
              new Error(response.status + " : " + response.url)
            );
          });
        };
      }
    } else {
    }
    var out = Module["print"] || console.log.bind(console);
    var err = Module["printErr"] || console.error.bind(console);
    Object.assign(Module, moduleOverrides);
    moduleOverrides = null;
    if (Module["arguments"])
      arguments_ = Module["arguments"];
    if (Module["thisProgram"])
      thisProgram = Module["thisProgram"];
    var wasmBinary2 = Module["wasmBinary"];
    var wasmMemory;
    var ABORT = false;
    var EXITSTATUS;
    function assert(condition, text) {
      if (!condition) {
        abort(text);
      }
    }
    var HEAP, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAP64, HEAPU64, HEAPF64;
    function updateMemoryViews() {
      var b = wasmMemory.buffer;
      Module["HEAP8"] = HEAP8 = new Int8Array(b);
      Module["HEAP16"] = HEAP16 = new Int16Array(b);
      Module["HEAPU8"] = HEAPU8 = new Uint8Array(b);
      Module["HEAPU16"] = HEAPU16 = new Uint16Array(b);
      Module["HEAP32"] = HEAP32 = new Int32Array(b);
      Module["HEAPU32"] = HEAPU32 = new Uint32Array(b);
      Module["HEAPF32"] = HEAPF32 = new Float32Array(b);
      Module["HEAPF64"] = HEAPF64 = new Float64Array(b);
      Module["HEAP64"] = HEAP64 = new BigInt64Array(b);
      Module["HEAPU64"] = HEAPU64 = new BigUint64Array(b);
    }
    if (Module["wasmMemory"]) {
      wasmMemory = Module["wasmMemory"];
    } else {
      var INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 16777216;
      wasmMemory = new WebAssembly.Memory({
        initial: INITIAL_MEMORY / 65536,
        maximum: 32768
      });
    }
    updateMemoryViews();
    var __ATPRERUN__ = [];
    var __ATINIT__ = [];
    var __ATEXIT__ = [];
    var __ATPOSTRUN__ = [];
    var runtimeInitialized = false;
    function preRun() {
      var preRuns = Module["preRun"];
      if (preRuns) {
        if (typeof preRuns == "function")
          preRuns = [preRuns];
        preRuns.forEach(addOnPreRun);
      }
      callRuntimeCallbacks(__ATPRERUN__);
    }
    function initRuntime() {
      runtimeInitialized = true;
      if (!Module["noFSInit"] && !FS.initialized)
        FS.init();
      FS.ignorePermissions = false;
      TTY.init();
      callRuntimeCallbacks(__ATINIT__);
    }
    function postRun() {
      var postRuns = Module["postRun"];
      if (postRuns) {
        if (typeof postRuns == "function")
          postRuns = [postRuns];
        postRuns.forEach(addOnPostRun);
      }
      callRuntimeCallbacks(__ATPOSTRUN__);
    }
    function addOnPreRun(cb) {
      __ATPRERUN__.unshift(cb);
    }
    function addOnInit(cb) {
      __ATINIT__.unshift(cb);
    }
    function addOnExit(cb) {
    }
    function addOnPostRun(cb) {
      __ATPOSTRUN__.unshift(cb);
    }
    var runDependencies = 0;
    var runDependencyWatcher = null;
    var dependenciesFulfilled = null;
    function getUniqueRunDependency(id) {
      return id;
    }
    function addRunDependency(id) {
      var _a8;
      runDependencies++;
      (_a8 = Module["monitorRunDependencies"]) == null ? void 0 : _a8.call(Module, runDependencies);
    }
    function removeRunDependency(id) {
      var _a8;
      runDependencies--;
      (_a8 = Module["monitorRunDependencies"]) == null ? void 0 : _a8.call(Module, runDependencies);
      if (runDependencies == 0) {
        if (runDependencyWatcher !== null) {
          clearInterval(runDependencyWatcher);
          runDependencyWatcher = null;
        }
        if (dependenciesFulfilled) {
          var callback = dependenciesFulfilled;
          dependenciesFulfilled = null;
          callback();
        }
      }
    }
    function abort(what) {
      var _a8;
      (_a8 = Module["onAbort"]) == null ? void 0 : _a8.call(Module, what);
      what = "Aborted(" + what + ")";
      err(what);
      ABORT = true;
      what += ". Build with -sASSERTIONS for more info.";
      var e2 = new WebAssembly.RuntimeError(what);
      readyPromiseReject(e2);
      throw e2;
    }
    var dataURIPrefix = "data:application/octet-stream;base64,";
    var isDataURI = (filename) => filename.startsWith(dataURIPrefix);
    var isFileURI = (filename) => filename.startsWith("file://");
    function findWasmBinary() {
      if (Module["locateFile"]) {
        var f2 = "sqlite3.wasm";
        if (!isDataURI(f2)) {
          return locateFile(f2);
        }
        return f2;
      }
      return new URL("sqlite3.wasm", import.meta.url).href;
    }
    var wasmBinaryFile;
    function getBinarySync(file) {
      if (file == wasmBinaryFile && wasmBinary2) {
        return new Uint8Array(wasmBinary2);
      }
      if (readBinary) {
        return readBinary(file);
      }
      throw "both async and sync fetching of the wasm failed";
    }
    function getBinaryPromise(binaryFile) {
      if (!wasmBinary2) {
        return readAsync(binaryFile).then(
          (response) => new Uint8Array(response),
          () => getBinarySync(binaryFile)
        );
      }
      return Promise.resolve().then(() => getBinarySync(binaryFile));
    }
    function instantiateArrayBuffer(binaryFile, imports, receiver) {
      return getBinaryPromise(binaryFile).then((binary) => {
        return WebAssembly.instantiate(binary, imports);
      }).then(receiver, (reason) => {
        err(`failed to asynchronously prepare wasm: ${reason}`);
        abort(reason);
      });
    }
    function instantiateAsync(binary, binaryFile, imports, callback) {
      if (!binary && typeof WebAssembly.instantiateStreaming == "function" && !isDataURI(binaryFile) && typeof fetch == "function") {
        return fetch(binaryFile, { credentials: "same-origin" }).then(
          (response) => {
            var result = WebAssembly.instantiateStreaming(response, imports);
            return result.then(callback, function(reason) {
              err(`wasm streaming compile failed: ${reason}`);
              err("falling back to ArrayBuffer instantiation");
              return instantiateArrayBuffer(binaryFile, imports, callback);
            });
          }
        );
      }
      return instantiateArrayBuffer(binaryFile, imports, callback);
    }
    function getWasmImports() {
      return {
        env: wasmImports,
        wasi_snapshot_preview1: wasmImports
      };
    }
    function createWasm() {
      var info = getWasmImports();
      function receiveInstance(instance, module) {
        wasmExports = instance.exports;
        addOnInit(wasmExports["__wasm_call_ctors"]);
        removeRunDependency("wasm-instantiate");
        return wasmExports;
      }
      addRunDependency("wasm-instantiate");
      function receiveInstantiationResult(result) {
        receiveInstance(result["instance"]);
      }
      if (Module["instantiateWasm"]) {
        try {
          return Module["instantiateWasm"](info, receiveInstance);
        } catch (e2) {
          err(`Module.instantiateWasm callback failed with error: ${e2}`);
          readyPromiseReject(e2);
        }
      }
      wasmBinaryFile ??= findWasmBinary();
      instantiateAsync(
        wasmBinary2,
        wasmBinaryFile,
        info,
        receiveInstantiationResult
      ).catch(readyPromiseReject);
      return {};
    }
    function ExitStatus(status) {
      this.name = "ExitStatus";
      this.message = `Program terminated with exit(${status})`;
      this.status = status;
    }
    var callRuntimeCallbacks = (callbacks) => {
      callbacks.forEach((f2) => f2(Module));
    };
    function getValue(ptr, type = "i8") {
      if (type.endsWith("*"))
        type = "*";
      switch (type) {
        case "i1":
          return HEAP8[ptr];
        case "i8":
          return HEAP8[ptr];
        case "i16":
          return HEAP16[ptr >> 1];
        case "i32":
          return HEAP32[ptr >> 2];
        case "i64":
          return HEAP64[ptr >> 3];
        case "float":
          return HEAPF32[ptr >> 2];
        case "double":
          return HEAPF64[ptr >> 3];
        case "*":
          return HEAPU32[ptr >> 2];
        default:
          abort(`invalid type for getValue: ${type}`);
      }
    }
    var noExitRuntime = Module["noExitRuntime"] || true;
    function setValue(ptr, value, type = "i8") {
      if (type.endsWith("*"))
        type = "*";
      switch (type) {
        case "i1":
          HEAP8[ptr] = value;
          break;
        case "i8":
          HEAP8[ptr] = value;
          break;
        case "i16":
          HEAP16[ptr >> 1] = value;
          break;
        case "i32":
          HEAP32[ptr >> 2] = value;
          break;
        case "i64":
          HEAP64[ptr >> 3] = BigInt(value);
          break;
        case "float":
          HEAPF32[ptr >> 2] = value;
          break;
        case "double":
          HEAPF64[ptr >> 3] = value;
          break;
        case "*":
          HEAPU32[ptr >> 2] = value;
          break;
        default:
          abort(`invalid type for setValue: ${type}`);
      }
    }
    var stackRestore = (val) => __emscripten_stack_restore(val);
    var stackSave = () => _emscripten_stack_get_current();
    var PATH = {
      isAbs: (path2) => path2.charAt(0) === "/",
      splitPath: (filename) => {
        var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
        return splitPathRe.exec(filename).slice(1);
      },
      normalizeArray: (parts, allowAboveRoot) => {
        var up = 0;
        for (var i2 = parts.length - 1; i2 >= 0; i2--) {
          var last = parts[i2];
          if (last === ".") {
            parts.splice(i2, 1);
          } else if (last === "..") {
            parts.splice(i2, 1);
            up++;
          } else if (up) {
            parts.splice(i2, 1);
            up--;
          }
        }
        if (allowAboveRoot) {
          for (; up; up--) {
            parts.unshift("..");
          }
        }
        return parts;
      },
      normalize: (path2) => {
        var isAbsolute = PATH.isAbs(path2), trailingSlash = path2.substr(-1) === "/";
        path2 = PATH.normalizeArray(
          path2.split("/").filter((p3) => !!p3),
          !isAbsolute
        ).join("/");
        if (!path2 && !isAbsolute) {
          path2 = ".";
        }
        if (path2 && trailingSlash) {
          path2 += "/";
        }
        return (isAbsolute ? "/" : "") + path2;
      },
      dirname: (path2) => {
        var result = PATH.splitPath(path2), root = result[0], dir = result[1];
        if (!root && !dir) {
          return ".";
        }
        if (dir) {
          dir = dir.substr(0, dir.length - 1);
        }
        return root + dir;
      },
      basename: (path2) => {
        if (path2 === "/")
          return "/";
        path2 = PATH.normalize(path2);
        path2 = path2.replace(/\/$/, "");
        var lastSlash = path2.lastIndexOf("/");
        if (lastSlash === -1)
          return path2;
        return path2.substr(lastSlash + 1);
      },
      join: (...paths) => PATH.normalize(paths.join("/")),
      join2: (l2, r3) => PATH.normalize(l2 + "/" + r3)
    };
    var initRandomFill = () => {
      if (typeof crypto == "object" && typeof crypto["getRandomValues"] == "function") {
        return (view) => crypto.getRandomValues(view);
      } else
        abort("initRandomDevice");
    };
    var randomFill = (view) => {
      return (randomFill = initRandomFill())(view);
    };
    var PATH_FS = {
      resolve: (...args) => {
        var resolvedPath = "", resolvedAbsolute = false;
        for (var i2 = args.length - 1; i2 >= -1 && !resolvedAbsolute; i2--) {
          var path2 = i2 >= 0 ? args[i2] : FS.cwd();
          if (typeof path2 != "string") {
            throw new TypeError("Arguments to path.resolve must be strings");
          } else if (!path2) {
            return "";
          }
          resolvedPath = path2 + "/" + resolvedPath;
          resolvedAbsolute = PATH.isAbs(path2);
        }
        resolvedPath = PATH.normalizeArray(
          resolvedPath.split("/").filter((p3) => !!p3),
          !resolvedAbsolute
        ).join("/");
        return (resolvedAbsolute ? "/" : "") + resolvedPath || ".";
      },
      relative: (from, to) => {
        from = PATH_FS.resolve(from).substr(1);
        to = PATH_FS.resolve(to).substr(1);
        function trim4(arr) {
          var start = 0;
          for (; start < arr.length; start++) {
            if (arr[start] !== "")
              break;
          }
          var end = arr.length - 1;
          for (; end >= 0; end--) {
            if (arr[end] !== "")
              break;
          }
          if (start > end)
            return [];
          return arr.slice(start, end - start + 1);
        }
        var fromParts = trim4(from.split("/"));
        var toParts = trim4(to.split("/"));
        var length = Math.min(fromParts.length, toParts.length);
        var samePartsLength = length;
        for (var i2 = 0; i2 < length; i2++) {
          if (fromParts[i2] !== toParts[i2]) {
            samePartsLength = i2;
            break;
          }
        }
        var outputParts = [];
        for (var i2 = samePartsLength; i2 < fromParts.length; i2++) {
          outputParts.push("..");
        }
        outputParts = outputParts.concat(toParts.slice(samePartsLength));
        return outputParts.join("/");
      }
    };
    var UTF8Decoder = typeof TextDecoder != "undefined" ? new TextDecoder() : void 0;
    var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead = NaN) => {
      var endIdx = idx + maxBytesToRead;
      var endPtr = idx;
      while (heapOrArray[endPtr] && !(endPtr >= endIdx))
        ++endPtr;
      if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
        return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
      }
      var str = "";
      while (idx < endPtr) {
        var u0 = heapOrArray[idx++];
        if (!(u0 & 128)) {
          str += String.fromCharCode(u0);
          continue;
        }
        var u1 = heapOrArray[idx++] & 63;
        if ((u0 & 224) == 192) {
          str += String.fromCharCode((u0 & 31) << 6 | u1);
          continue;
        }
        var u22 = heapOrArray[idx++] & 63;
        if ((u0 & 240) == 224) {
          u0 = (u0 & 15) << 12 | u1 << 6 | u22;
        } else {
          u0 = (u0 & 7) << 18 | u1 << 12 | u22 << 6 | heapOrArray[idx++] & 63;
        }
        if (u0 < 65536) {
          str += String.fromCharCode(u0);
        } else {
          var ch = u0 - 65536;
          str += String.fromCharCode(
            55296 | ch >> 10,
            56320 | ch & 1023
          );
        }
      }
      return str;
    };
    var FS_stdin_getChar_buffer = [];
    var lengthBytesUTF8 = (str) => {
      var len = 0;
      for (var i2 = 0; i2 < str.length; ++i2) {
        var c3 = str.charCodeAt(i2);
        if (c3 <= 127) {
          len++;
        } else if (c3 <= 2047) {
          len += 2;
        } else if (c3 >= 55296 && c3 <= 57343) {
          len += 4;
          ++i2;
        } else {
          len += 3;
        }
      }
      return len;
    };
    var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {
      if (!(maxBytesToWrite > 0))
        return 0;
      var startIdx = outIdx;
      var endIdx = outIdx + maxBytesToWrite - 1;
      for (var i2 = 0; i2 < str.length; ++i2) {
        var u3 = str.charCodeAt(i2);
        if (u3 >= 55296 && u3 <= 57343) {
          var u1 = str.charCodeAt(++i2);
          u3 = 65536 + ((u3 & 1023) << 10) | u1 & 1023;
        }
        if (u3 <= 127) {
          if (outIdx >= endIdx)
            break;
          heap[outIdx++] = u3;
        } else if (u3 <= 2047) {
          if (outIdx + 1 >= endIdx)
            break;
          heap[outIdx++] = 192 | u3 >> 6;
          heap[outIdx++] = 128 | u3 & 63;
        } else if (u3 <= 65535) {
          if (outIdx + 2 >= endIdx)
            break;
          heap[outIdx++] = 224 | u3 >> 12;
          heap[outIdx++] = 128 | u3 >> 6 & 63;
          heap[outIdx++] = 128 | u3 & 63;
        } else {
          if (outIdx + 3 >= endIdx)
            break;
          heap[outIdx++] = 240 | u3 >> 18;
          heap[outIdx++] = 128 | u3 >> 12 & 63;
          heap[outIdx++] = 128 | u3 >> 6 & 63;
          heap[outIdx++] = 128 | u3 & 63;
        }
      }
      heap[outIdx] = 0;
      return outIdx - startIdx;
    };
    function intArrayFromString(stringy, dontAddNull, length) {
      var len = length > 0 ? length : lengthBytesUTF8(stringy) + 1;
      var u8array = new Array(len);
      var numBytesWritten = stringToUTF8Array(
        stringy,
        u8array,
        0,
        u8array.length
      );
      if (dontAddNull)
        u8array.length = numBytesWritten;
      return u8array;
    }
    var FS_stdin_getChar = () => {
      if (!FS_stdin_getChar_buffer.length) {
        var result = null;
        if (typeof window != "undefined" && typeof window.prompt == "function") {
          result = window.prompt("Input: ");
          if (result !== null) {
            result += "\n";
          }
        } else {
        }
        if (!result) {
          return null;
        }
        FS_stdin_getChar_buffer = intArrayFromString(result, true);
      }
      return FS_stdin_getChar_buffer.shift();
    };
    var TTY = {
      ttys: [],
      init() {
      },
      shutdown() {
      },
      register(dev, ops) {
        TTY.ttys[dev] = { input: [], output: [], ops };
        FS.registerDevice(dev, TTY.stream_ops);
      },
      stream_ops: {
        open(stream) {
          var tty2 = TTY.ttys[stream.node.rdev];
          if (!tty2) {
            throw new FS.ErrnoError(43);
          }
          stream.tty = tty2;
          stream.seekable = false;
        },
        close(stream) {
          stream.tty.ops.fsync(stream.tty);
        },
        fsync(stream) {
          stream.tty.ops.fsync(stream.tty);
        },
        read(stream, buffer, offset, length, pos) {
          if (!stream.tty || !stream.tty.ops.get_char) {
            throw new FS.ErrnoError(60);
          }
          var bytesRead = 0;
          for (var i2 = 0; i2 < length; i2++) {
            var result;
            try {
              result = stream.tty.ops.get_char(stream.tty);
            } catch (e2) {
              throw new FS.ErrnoError(29);
            }
            if (result === void 0 && bytesRead === 0) {
              throw new FS.ErrnoError(6);
            }
            if (result === null || result === void 0)
              break;
            bytesRead++;
            buffer[offset + i2] = result;
          }
          if (bytesRead) {
            stream.node.timestamp = Date.now();
          }
          return bytesRead;
        },
        write(stream, buffer, offset, length, pos) {
          if (!stream.tty || !stream.tty.ops.put_char) {
            throw new FS.ErrnoError(60);
          }
          try {
            for (var i2 = 0; i2 < length; i2++) {
              stream.tty.ops.put_char(stream.tty, buffer[offset + i2]);
            }
          } catch (e2) {
            throw new FS.ErrnoError(29);
          }
          if (length) {
            stream.node.timestamp = Date.now();
          }
          return i2;
        }
      },
      default_tty_ops: {
        get_char(tty2) {
          return FS_stdin_getChar();
        },
        put_char(tty2, val) {
          if (val === null || val === 10) {
            out(UTF8ArrayToString(tty2.output));
            tty2.output = [];
          } else {
            if (val != 0)
              tty2.output.push(val);
          }
        },
        fsync(tty2) {
          if (tty2.output && tty2.output.length > 0) {
            out(UTF8ArrayToString(tty2.output));
            tty2.output = [];
          }
        },
        ioctl_tcgets(tty2) {
          return {
            c_iflag: 25856,
            c_oflag: 5,
            c_cflag: 191,
            c_lflag: 35387,
            c_cc: [
              3,
              28,
              127,
              21,
              4,
              0,
              1,
              0,
              17,
              19,
              26,
              0,
              18,
              15,
              23,
              22,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0
            ]
          };
        },
        ioctl_tcsets(tty2, optional_actions, data) {
          return 0;
        },
        ioctl_tiocgwinsz(tty2) {
          return [24, 80];
        }
      },
      default_tty1_ops: {
        put_char(tty2, val) {
          if (val === null || val === 10) {
            err(UTF8ArrayToString(tty2.output));
            tty2.output = [];
          } else {
            if (val != 0)
              tty2.output.push(val);
          }
        },
        fsync(tty2) {
          if (tty2.output && tty2.output.length > 0) {
            err(UTF8ArrayToString(tty2.output));
            tty2.output = [];
          }
        }
      }
    };
    var zeroMemory = (address, size) => {
      HEAPU8.fill(0, address, address + size);
    };
    var alignMemory = (size, alignment) => {
      return Math.ceil(size / alignment) * alignment;
    };
    var mmapAlloc = (size) => {
      size = alignMemory(size, 65536);
      var ptr = _emscripten_builtin_memalign(65536, size);
      if (ptr)
        zeroMemory(ptr, size);
      return ptr;
    };
    var MEMFS = {
      ops_table: null,
      mount(mount) {
        return MEMFS.createNode(null, "/", 16384 | 511, 0);
      },
      createNode(parent, name, mode, dev) {
        if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
          throw new FS.ErrnoError(63);
        }
        MEMFS.ops_table ||= {
          dir: {
            node: {
              getattr: MEMFS.node_ops.getattr,
              setattr: MEMFS.node_ops.setattr,
              lookup: MEMFS.node_ops.lookup,
              mknod: MEMFS.node_ops.mknod,
              rename: MEMFS.node_ops.rename,
              unlink: MEMFS.node_ops.unlink,
              rmdir: MEMFS.node_ops.rmdir,
              readdir: MEMFS.node_ops.readdir,
              symlink: MEMFS.node_ops.symlink
            },
            stream: {
              llseek: MEMFS.stream_ops.llseek
            }
          },
          file: {
            node: {
              getattr: MEMFS.node_ops.getattr,
              setattr: MEMFS.node_ops.setattr
            },
            stream: {
              llseek: MEMFS.stream_ops.llseek,
              read: MEMFS.stream_ops.read,
              write: MEMFS.stream_ops.write,
              allocate: MEMFS.stream_ops.allocate,
              mmap: MEMFS.stream_ops.mmap,
              msync: MEMFS.stream_ops.msync
            }
          },
          link: {
            node: {
              getattr: MEMFS.node_ops.getattr,
              setattr: MEMFS.node_ops.setattr,
              readlink: MEMFS.node_ops.readlink
            },
            stream: {}
          },
          chrdev: {
            node: {
              getattr: MEMFS.node_ops.getattr,
              setattr: MEMFS.node_ops.setattr
            },
            stream: FS.chrdev_stream_ops
          }
        };
        var node = FS.createNode(parent, name, mode, dev);
        if (FS.isDir(node.mode)) {
          node.node_ops = MEMFS.ops_table.dir.node;
          node.stream_ops = MEMFS.ops_table.dir.stream;
          node.contents = {};
        } else if (FS.isFile(node.mode)) {
          node.node_ops = MEMFS.ops_table.file.node;
          node.stream_ops = MEMFS.ops_table.file.stream;
          node.usedBytes = 0;
          node.contents = null;
        } else if (FS.isLink(node.mode)) {
          node.node_ops = MEMFS.ops_table.link.node;
          node.stream_ops = MEMFS.ops_table.link.stream;
        } else if (FS.isChrdev(node.mode)) {
          node.node_ops = MEMFS.ops_table.chrdev.node;
          node.stream_ops = MEMFS.ops_table.chrdev.stream;
        }
        node.timestamp = Date.now();
        if (parent) {
          parent.contents[name] = node;
          parent.timestamp = node.timestamp;
        }
        return node;
      },
      getFileDataAsTypedArray(node) {
        if (!node.contents)
          return new Uint8Array(0);
        if (node.contents.subarray)
          return node.contents.subarray(0, node.usedBytes);
        return new Uint8Array(node.contents);
      },
      expandFileStorage(node, newCapacity) {
        var prevCapacity = node.contents ? node.contents.length : 0;
        if (prevCapacity >= newCapacity)
          return;
        var CAPACITY_DOUBLING_MAX = 1024 * 1024;
        newCapacity = Math.max(
          newCapacity,
          prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2 : 1.125) >>> 0
        );
        if (prevCapacity != 0)
          newCapacity = Math.max(newCapacity, 256);
        var oldContents = node.contents;
        node.contents = new Uint8Array(newCapacity);
        if (node.usedBytes > 0)
          node.contents.set(oldContents.subarray(0, node.usedBytes), 0);
      },
      resizeFileStorage(node, newSize) {
        if (node.usedBytes == newSize)
          return;
        if (newSize == 0) {
          node.contents = null;
          node.usedBytes = 0;
        } else {
          var oldContents = node.contents;
          node.contents = new Uint8Array(newSize);
          if (oldContents) {
            node.contents.set(
              oldContents.subarray(0, Math.min(newSize, node.usedBytes))
            );
          }
          node.usedBytes = newSize;
        }
      },
      node_ops: {
        getattr(node) {
          var attr = {};
          attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
          attr.ino = node.id;
          attr.mode = node.mode;
          attr.nlink = 1;
          attr.uid = 0;
          attr.gid = 0;
          attr.rdev = node.rdev;
          if (FS.isDir(node.mode)) {
            attr.size = 4096;
          } else if (FS.isFile(node.mode)) {
            attr.size = node.usedBytes;
          } else if (FS.isLink(node.mode)) {
            attr.size = node.link.length;
          } else {
            attr.size = 0;
          }
          attr.atime = new Date(node.timestamp);
          attr.mtime = new Date(node.timestamp);
          attr.ctime = new Date(node.timestamp);
          attr.blksize = 4096;
          attr.blocks = Math.ceil(attr.size / attr.blksize);
          return attr;
        },
        setattr(node, attr) {
          if (attr.mode !== void 0) {
            node.mode = attr.mode;
          }
          if (attr.timestamp !== void 0) {
            node.timestamp = attr.timestamp;
          }
          if (attr.size !== void 0) {
            MEMFS.resizeFileStorage(node, attr.size);
          }
        },
        lookup(parent, name) {
          throw FS.genericErrors[44];
        },
        mknod(parent, name, mode, dev) {
          return MEMFS.createNode(parent, name, mode, dev);
        },
        rename(old_node, new_dir, new_name) {
          if (FS.isDir(old_node.mode)) {
            var new_node;
            try {
              new_node = FS.lookupNode(new_dir, new_name);
            } catch (e2) {
            }
            if (new_node) {
              for (var i2 in new_node.contents) {
                throw new FS.ErrnoError(55);
              }
            }
          }
          delete old_node.parent.contents[old_node.name];
          old_node.parent.timestamp = Date.now();
          old_node.name = new_name;
          new_dir.contents[new_name] = old_node;
          new_dir.timestamp = old_node.parent.timestamp;
        },
        unlink(parent, name) {
          delete parent.contents[name];
          parent.timestamp = Date.now();
        },
        rmdir(parent, name) {
          var node = FS.lookupNode(parent, name);
          for (var i2 in node.contents) {
            throw new FS.ErrnoError(55);
          }
          delete parent.contents[name];
          parent.timestamp = Date.now();
        },
        readdir(node) {
          var entries = [".", ".."];
          for (var key of Object.keys(node.contents)) {
            entries.push(key);
          }
          return entries;
        },
        symlink(parent, newname, oldpath) {
          var node = MEMFS.createNode(parent, newname, 511 | 40960, 0);
          node.link = oldpath;
          return node;
        },
        readlink(node) {
          if (!FS.isLink(node.mode)) {
            throw new FS.ErrnoError(28);
          }
          return node.link;
        }
      },
      stream_ops: {
        read(stream, buffer, offset, length, position) {
          var contents = stream.node.contents;
          if (position >= stream.node.usedBytes)
            return 0;
          var size = Math.min(stream.node.usedBytes - position, length);
          if (size > 8 && contents.subarray) {
            buffer.set(contents.subarray(position, position + size), offset);
          } else {
            for (var i2 = 0; i2 < size; i2++)
              buffer[offset + i2] = contents[position + i2];
          }
          return size;
        },
        write(stream, buffer, offset, length, position, canOwn) {
          if (buffer.buffer === HEAP8.buffer) {
            canOwn = false;
          }
          if (!length)
            return 0;
          var node = stream.node;
          node.timestamp = Date.now();
          if (buffer.subarray && (!node.contents || node.contents.subarray)) {
            if (canOwn) {
              node.contents = buffer.subarray(offset, offset + length);
              node.usedBytes = length;
              return length;
            } else if (node.usedBytes === 0 && position === 0) {
              node.contents = buffer.slice(offset, offset + length);
              node.usedBytes = length;
              return length;
            } else if (position + length <= node.usedBytes) {
              node.contents.set(
                buffer.subarray(offset, offset + length),
                position
              );
              return length;
            }
          }
          MEMFS.expandFileStorage(node, position + length);
          if (node.contents.subarray && buffer.subarray) {
            node.contents.set(
              buffer.subarray(offset, offset + length),
              position
            );
          } else {
            for (var i2 = 0; i2 < length; i2++) {
              node.contents[position + i2] = buffer[offset + i2];
            }
          }
          node.usedBytes = Math.max(node.usedBytes, position + length);
          return length;
        },
        llseek(stream, offset, whence) {
          var position = offset;
          if (whence === 1) {
            position += stream.position;
          } else if (whence === 2) {
            if (FS.isFile(stream.node.mode)) {
              position += stream.node.usedBytes;
            }
          }
          if (position < 0) {
            throw new FS.ErrnoError(28);
          }
          return position;
        },
        allocate(stream, offset, length) {
          MEMFS.expandFileStorage(stream.node, offset + length);
          stream.node.usedBytes = Math.max(
            stream.node.usedBytes,
            offset + length
          );
        },
        mmap(stream, length, position, prot, flags) {
          if (!FS.isFile(stream.node.mode)) {
            throw new FS.ErrnoError(43);
          }
          var ptr;
          var allocated;
          var contents = stream.node.contents;
          if (!(flags & 2) && contents && contents.buffer === HEAP8.buffer) {
            allocated = false;
            ptr = contents.byteOffset;
          } else {
            allocated = true;
            ptr = mmapAlloc(length);
            if (!ptr) {
              throw new FS.ErrnoError(48);
            }
            if (contents) {
              if (position > 0 || position + length < contents.length) {
                if (contents.subarray) {
                  contents = contents.subarray(position, position + length);
                } else {
                  contents = Array.prototype.slice.call(
                    contents,
                    position,
                    position + length
                  );
                }
              }
              HEAP8.set(contents, ptr);
            }
          }
          return { ptr, allocated };
        },
        msync(stream, buffer, offset, length, mmapFlags) {
          MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);
          return 0;
        }
      }
    };
    var asyncLoad = (url, onload, onerror, noRunDep) => {
      var dep = !noRunDep ? getUniqueRunDependency(`al ${url}`) : "";
      readAsync(url).then(
        (arrayBuffer) => {
          onload(new Uint8Array(arrayBuffer));
          if (dep)
            removeRunDependency(dep);
        },
        (err2) => {
          if (onerror) {
            onerror();
          } else {
            throw `Loading data file "${url}" failed.`;
          }
        }
      );
      if (dep)
        addRunDependency(dep);
    };
    var FS_createDataFile = (parent, name, fileData, canRead, canWrite, canOwn) => {
      FS.createDataFile(parent, name, fileData, canRead, canWrite, canOwn);
    };
    var preloadPlugins = Module["preloadPlugins"] || [];
    var FS_handledByPreloadPlugin = (byteArray, fullname, finish, onerror) => {
      if (typeof Browser != "undefined")
        Browser.init();
      var handled = false;
      preloadPlugins.forEach((plugin2) => {
        if (handled)
          return;
        if (plugin2["canHandle"](fullname)) {
          plugin2["handle"](byteArray, fullname, finish, onerror);
          handled = true;
        }
      });
      return handled;
    };
    var FS_createPreloadedFile = (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => {
      var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;
      var dep = getUniqueRunDependency(`cp ${fullname}`);
      function processData(byteArray) {
        function finish(byteArray2) {
          preFinish == null ? void 0 : preFinish();
          if (!dontCreateFile) {
            FS_createDataFile(
              parent,
              name,
              byteArray2,
              canRead,
              canWrite,
              canOwn
            );
          }
          onload == null ? void 0 : onload();
          removeRunDependency(dep);
        }
        if (FS_handledByPreloadPlugin(byteArray, fullname, finish, () => {
          onerror == null ? void 0 : onerror();
          removeRunDependency(dep);
        })) {
          return;
        }
        finish(byteArray);
      }
      addRunDependency(dep);
      if (typeof url == "string") {
        asyncLoad(url, processData, onerror);
      } else {
        processData(url);
      }
    };
    var FS_modeStringToFlags = (str) => {
      var flagModes = {
        r: 0,
        "r+": 2,
        w: 512 | 64 | 1,
        "w+": 512 | 64 | 2,
        a: 1024 | 64 | 1,
        "a+": 1024 | 64 | 2
      };
      var flags = flagModes[str];
      if (typeof flags == "undefined") {
        throw new Error(`Unknown file open mode: ${str}`);
      }
      return flags;
    };
    var FS_getMode = (canRead, canWrite) => {
      var mode = 0;
      if (canRead)
        mode |= 292 | 73;
      if (canWrite)
        mode |= 146;
      return mode;
    };
    var FS = {
      root: null,
      mounts: [],
      devices: {},
      streams: [],
      nextInode: 1,
      nameTable: null,
      currentPath: "/",
      initialized: false,
      ignorePermissions: true,
      ErrnoError: class {
        constructor(errno) {
          this.name = "ErrnoError";
          this.errno = errno;
        }
      },
      genericErrors: {},
      filesystems: null,
      syncFSRequests: 0,
      readFiles: {},
      FSStream: class {
        constructor() {
          this.shared = {};
        }
        get object() {
          return this.node;
        }
        set object(val) {
          this.node = val;
        }
        get isRead() {
          return (this.flags & 2097155) !== 1;
        }
        get isWrite() {
          return (this.flags & 2097155) !== 0;
        }
        get isAppend() {
          return this.flags & 1024;
        }
        get flags() {
          return this.shared.flags;
        }
        set flags(val) {
          this.shared.flags = val;
        }
        get position() {
          return this.shared.position;
        }
        set position(val) {
          this.shared.position = val;
        }
      },
      FSNode: class {
        constructor(parent, name, mode, rdev) {
          if (!parent) {
            parent = this;
          }
          this.parent = parent;
          this.mount = parent.mount;
          this.mounted = null;
          this.id = FS.nextInode++;
          this.name = name;
          this.mode = mode;
          this.node_ops = {};
          this.stream_ops = {};
          this.rdev = rdev;
          this.readMode = 292 | 73;
          this.writeMode = 146;
        }
        get read() {
          return (this.mode & this.readMode) === this.readMode;
        }
        set read(val) {
          val ? this.mode |= this.readMode : this.mode &= ~this.readMode;
        }
        get write() {
          return (this.mode & this.writeMode) === this.writeMode;
        }
        set write(val) {
          val ? this.mode |= this.writeMode : this.mode &= ~this.writeMode;
        }
        get isFolder() {
          return FS.isDir(this.mode);
        }
        get isDevice() {
          return FS.isChrdev(this.mode);
        }
      },
      lookupPath(path2, opts = {}) {
        path2 = PATH_FS.resolve(path2);
        if (!path2)
          return { path: "", node: null };
        var defaults = {
          follow_mount: true,
          recurse_count: 0
        };
        opts = Object.assign(defaults, opts);
        if (opts.recurse_count > 8) {
          throw new FS.ErrnoError(32);
        }
        var parts = path2.split("/").filter((p3) => !!p3);
        var current = FS.root;
        var current_path = "/";
        for (var i2 = 0; i2 < parts.length; i2++) {
          var islast = i2 === parts.length - 1;
          if (islast && opts.parent) {
            break;
          }
          current = FS.lookupNode(current, parts[i2]);
          current_path = PATH.join2(current_path, parts[i2]);
          if (FS.isMountpoint(current)) {
            if (!islast || islast && opts.follow_mount) {
              current = current.mounted.root;
            }
          }
          if (!islast || opts.follow) {
            var count = 0;
            while (FS.isLink(current.mode)) {
              var link = FS.readlink(current_path);
              current_path = PATH_FS.resolve(PATH.dirname(current_path), link);
              var lookup = FS.lookupPath(current_path, {
                recurse_count: opts.recurse_count + 1
              });
              current = lookup.node;
              if (count++ > 40) {
                throw new FS.ErrnoError(32);
              }
            }
          }
        }
        return { path: current_path, node: current };
      },
      getPath(node) {
        var path2;
        while (true) {
          if (FS.isRoot(node)) {
            var mount = node.mount.mountpoint;
            if (!path2)
              return mount;
            return mount[mount.length - 1] !== "/" ? `${mount}/${path2}` : mount + path2;
          }
          path2 = path2 ? `${node.name}/${path2}` : node.name;
          node = node.parent;
        }
      },
      hashName(parentid, name) {
        var hash = 0;
        for (var i2 = 0; i2 < name.length; i2++) {
          hash = (hash << 5) - hash + name.charCodeAt(i2) | 0;
        }
        return (parentid + hash >>> 0) % FS.nameTable.length;
      },
      hashAddNode(node) {
        var hash = FS.hashName(node.parent.id, node.name);
        node.name_next = FS.nameTable[hash];
        FS.nameTable[hash] = node;
      },
      hashRemoveNode(node) {
        var hash = FS.hashName(node.parent.id, node.name);
        if (FS.nameTable[hash] === node) {
          FS.nameTable[hash] = node.name_next;
        } else {
          var current = FS.nameTable[hash];
          while (current) {
            if (current.name_next === node) {
              current.name_next = node.name_next;
              break;
            }
            current = current.name_next;
          }
        }
      },
      lookupNode(parent, name) {
        var errCode = FS.mayLookup(parent);
        if (errCode) {
          throw new FS.ErrnoError(errCode);
        }
        var hash = FS.hashName(parent.id, name);
        for (var node = FS.nameTable[hash]; node; node = node.name_next) {
          var nodeName = node.name;
          if (node.parent.id === parent.id && nodeName === name) {
            return node;
          }
        }
        return FS.lookup(parent, name);
      },
      createNode(parent, name, mode, rdev) {
        var node = new FS.FSNode(parent, name, mode, rdev);
        FS.hashAddNode(node);
        return node;
      },
      destroyNode(node) {
        FS.hashRemoveNode(node);
      },
      isRoot(node) {
        return node === node.parent;
      },
      isMountpoint(node) {
        return !!node.mounted;
      },
      isFile(mode) {
        return (mode & 61440) === 32768;
      },
      isDir(mode) {
        return (mode & 61440) === 16384;
      },
      isLink(mode) {
        return (mode & 61440) === 40960;
      },
      isChrdev(mode) {
        return (mode & 61440) === 8192;
      },
      isBlkdev(mode) {
        return (mode & 61440) === 24576;
      },
      isFIFO(mode) {
        return (mode & 61440) === 4096;
      },
      isSocket(mode) {
        return (mode & 49152) === 49152;
      },
      flagsToPermissionString(flag) {
        var perms = ["r", "w", "rw"][flag & 3];
        if (flag & 512) {
          perms += "w";
        }
        return perms;
      },
      nodePermissions(node, perms) {
        if (FS.ignorePermissions) {
          return 0;
        }
        if (perms.includes("r") && !(node.mode & 292)) {
          return 2;
        } else if (perms.includes("w") && !(node.mode & 146)) {
          return 2;
        } else if (perms.includes("x") && !(node.mode & 73)) {
          return 2;
        }
        return 0;
      },
      mayLookup(dir) {
        if (!FS.isDir(dir.mode))
          return 54;
        var errCode = FS.nodePermissions(dir, "x");
        if (errCode)
          return errCode;
        if (!dir.node_ops.lookup)
          return 2;
        return 0;
      },
      mayCreate(dir, name) {
        try {
          var node = FS.lookupNode(dir, name);
          return 20;
        } catch (e2) {
        }
        return FS.nodePermissions(dir, "wx");
      },
      mayDelete(dir, name, isdir) {
        var node;
        try {
          node = FS.lookupNode(dir, name);
        } catch (e2) {
          return e2.errno;
        }
        var errCode = FS.nodePermissions(dir, "wx");
        if (errCode) {
          return errCode;
        }
        if (isdir) {
          if (!FS.isDir(node.mode)) {
            return 54;
          }
          if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
            return 10;
          }
        } else {
          if (FS.isDir(node.mode)) {
            return 31;
          }
        }
        return 0;
      },
      mayOpen(node, flags) {
        if (!node) {
          return 44;
        }
        if (FS.isLink(node.mode)) {
          return 32;
        } else if (FS.isDir(node.mode)) {
          if (FS.flagsToPermissionString(flags) !== "r" || flags & 512) {
            return 31;
          }
        }
        return FS.nodePermissions(node, FS.flagsToPermissionString(flags));
      },
      MAX_OPEN_FDS: 4096,
      nextfd() {
        for (var fd = 0; fd <= FS.MAX_OPEN_FDS; fd++) {
          if (!FS.streams[fd]) {
            return fd;
          }
        }
        throw new FS.ErrnoError(33);
      },
      getStreamChecked(fd) {
        var stream = FS.getStream(fd);
        if (!stream) {
          throw new FS.ErrnoError(8);
        }
        return stream;
      },
      getStream: (fd) => FS.streams[fd],
      createStream(stream, fd = -1) {
        stream = Object.assign(new FS.FSStream(), stream);
        if (fd == -1) {
          fd = FS.nextfd();
        }
        stream.fd = fd;
        FS.streams[fd] = stream;
        return stream;
      },
      closeStream(fd) {
        FS.streams[fd] = null;
      },
      dupStream(origStream, fd = -1) {
        var _a8, _b5;
        var stream = FS.createStream(origStream, fd);
        (_b5 = (_a8 = stream.stream_ops) == null ? void 0 : _a8.dup) == null ? void 0 : _b5.call(_a8, stream);
        return stream;
      },
      chrdev_stream_ops: {
        open(stream) {
          var _a8, _b5;
          var device = FS.getDevice(stream.node.rdev);
          stream.stream_ops = device.stream_ops;
          (_b5 = (_a8 = stream.stream_ops).open) == null ? void 0 : _b5.call(_a8, stream);
        },
        llseek() {
          throw new FS.ErrnoError(70);
        }
      },
      major: (dev) => dev >> 8,
      minor: (dev) => dev & 255,
      makedev: (ma, mi) => ma << 8 | mi,
      registerDevice(dev, ops) {
        FS.devices[dev] = { stream_ops: ops };
      },
      getDevice: (dev) => FS.devices[dev],
      getMounts(mount) {
        var mounts = [];
        var check = [mount];
        while (check.length) {
          var m2 = check.pop();
          mounts.push(m2);
          check.push(...m2.mounts);
        }
        return mounts;
      },
      syncfs(populate, callback) {
        if (typeof populate == "function") {
          callback = populate;
          populate = false;
        }
        FS.syncFSRequests++;
        if (FS.syncFSRequests > 1) {
          err(
            `warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`
          );
        }
        var mounts = FS.getMounts(FS.root.mount);
        var completed = 0;
        function doCallback(errCode) {
          FS.syncFSRequests--;
          return callback(errCode);
        }
        function done(errCode) {
          if (errCode) {
            if (!done.errored) {
              done.errored = true;
              return doCallback(errCode);
            }
            return;
          }
          if (++completed >= mounts.length) {
            doCallback(null);
          }
        }
        mounts.forEach((mount) => {
          if (!mount.type.syncfs) {
            return done(null);
          }
          mount.type.syncfs(mount, populate, done);
        });
      },
      mount(type, opts, mountpoint) {
        var root = mountpoint === "/";
        var pseudo = !mountpoint;
        var node;
        if (root && FS.root) {
          throw new FS.ErrnoError(10);
        } else if (!root && !pseudo) {
          var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
          mountpoint = lookup.path;
          node = lookup.node;
          if (FS.isMountpoint(node)) {
            throw new FS.ErrnoError(10);
          }
          if (!FS.isDir(node.mode)) {
            throw new FS.ErrnoError(54);
          }
        }
        var mount = {
          type,
          opts,
          mountpoint,
          mounts: []
        };
        var mountRoot = type.mount(mount);
        mountRoot.mount = mount;
        mount.root = mountRoot;
        if (root) {
          FS.root = mountRoot;
        } else if (node) {
          node.mounted = mount;
          if (node.mount) {
            node.mount.mounts.push(mount);
          }
        }
        return mountRoot;
      },
      unmount(mountpoint) {
        var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
        if (!FS.isMountpoint(lookup.node)) {
          throw new FS.ErrnoError(28);
        }
        var node = lookup.node;
        var mount = node.mounted;
        var mounts = FS.getMounts(mount);
        Object.keys(FS.nameTable).forEach((hash) => {
          var current = FS.nameTable[hash];
          while (current) {
            var next = current.name_next;
            if (mounts.includes(current.mount)) {
              FS.destroyNode(current);
            }
            current = next;
          }
        });
        node.mounted = null;
        var idx = node.mount.mounts.indexOf(mount);
        node.mount.mounts.splice(idx, 1);
      },
      lookup(parent, name) {
        return parent.node_ops.lookup(parent, name);
      },
      mknod(path2, mode, dev) {
        var lookup = FS.lookupPath(path2, { parent: true });
        var parent = lookup.node;
        var name = PATH.basename(path2);
        if (!name || name === "." || name === "..") {
          throw new FS.ErrnoError(28);
        }
        var errCode = FS.mayCreate(parent, name);
        if (errCode) {
          throw new FS.ErrnoError(errCode);
        }
        if (!parent.node_ops.mknod) {
          throw new FS.ErrnoError(63);
        }
        return parent.node_ops.mknod(parent, name, mode, dev);
      },
      create(path2, mode) {
        mode = mode !== void 0 ? mode : 438;
        mode &= 4095;
        mode |= 32768;
        return FS.mknod(path2, mode, 0);
      },
      mkdir(path2, mode) {
        mode = mode !== void 0 ? mode : 511;
        mode &= 511 | 512;
        mode |= 16384;
        return FS.mknod(path2, mode, 0);
      },
      mkdirTree(path2, mode) {
        var dirs = path2.split("/");
        var d2 = "";
        for (var i2 = 0; i2 < dirs.length; ++i2) {
          if (!dirs[i2])
            continue;
          d2 += "/" + dirs[i2];
          try {
            FS.mkdir(d2, mode);
          } catch (e2) {
            if (e2.errno != 20)
              throw e2;
          }
        }
      },
      mkdev(path2, mode, dev) {
        if (typeof dev == "undefined") {
          dev = mode;
          mode = 438;
        }
        mode |= 8192;
        return FS.mknod(path2, mode, dev);
      },
      symlink(oldpath, newpath) {
        if (!PATH_FS.resolve(oldpath)) {
          throw new FS.ErrnoError(44);
        }
        var lookup = FS.lookupPath(newpath, { parent: true });
        var parent = lookup.node;
        if (!parent) {
          throw new FS.ErrnoError(44);
        }
        var newname = PATH.basename(newpath);
        var errCode = FS.mayCreate(parent, newname);
        if (errCode) {
          throw new FS.ErrnoError(errCode);
        }
        if (!parent.node_ops.symlink) {
          throw new FS.ErrnoError(63);
        }
        return parent.node_ops.symlink(parent, newname, oldpath);
      },
      rename(old_path, new_path) {
        var old_dirname = PATH.dirname(old_path);
        var new_dirname = PATH.dirname(new_path);
        var old_name = PATH.basename(old_path);
        var new_name = PATH.basename(new_path);
        var lookup, old_dir, new_dir;
        lookup = FS.lookupPath(old_path, { parent: true });
        old_dir = lookup.node;
        lookup = FS.lookupPath(new_path, { parent: true });
        new_dir = lookup.node;
        if (!old_dir || !new_dir)
          throw new FS.ErrnoError(44);
        if (old_dir.mount !== new_dir.mount) {
          throw new FS.ErrnoError(75);
        }
        var old_node = FS.lookupNode(old_dir, old_name);
        var relative = PATH_FS.relative(old_path, new_dirname);
        if (relative.charAt(0) !== ".") {
          throw new FS.ErrnoError(28);
        }
        relative = PATH_FS.relative(new_path, old_dirname);
        if (relative.charAt(0) !== ".") {
          throw new FS.ErrnoError(55);
        }
        var new_node;
        try {
          new_node = FS.lookupNode(new_dir, new_name);
        } catch (e2) {
        }
        if (old_node === new_node) {
          return;
        }
        var isdir = FS.isDir(old_node.mode);
        var errCode = FS.mayDelete(old_dir, old_name, isdir);
        if (errCode) {
          throw new FS.ErrnoError(errCode);
        }
        errCode = new_node ? FS.mayDelete(new_dir, new_name, isdir) : FS.mayCreate(new_dir, new_name);
        if (errCode) {
          throw new FS.ErrnoError(errCode);
        }
        if (!old_dir.node_ops.rename) {
          throw new FS.ErrnoError(63);
        }
        if (FS.isMountpoint(old_node) || new_node && FS.isMountpoint(new_node)) {
          throw new FS.ErrnoError(10);
        }
        if (new_dir !== old_dir) {
          errCode = FS.nodePermissions(old_dir, "w");
          if (errCode) {
            throw new FS.ErrnoError(errCode);
          }
        }
        FS.hashRemoveNode(old_node);
        try {
          old_dir.node_ops.rename(old_node, new_dir, new_name);
          old_node.parent = new_dir;
        } catch (e2) {
          throw e2;
        } finally {
          FS.hashAddNode(old_node);
        }
      },
      rmdir(path2) {
        var lookup = FS.lookupPath(path2, { parent: true });
        var parent = lookup.node;
        var name = PATH.basename(path2);
        var node = FS.lookupNode(parent, name);
        var errCode = FS.mayDelete(parent, name, true);
        if (errCode) {
          throw new FS.ErrnoError(errCode);
        }
        if (!parent.node_ops.rmdir) {
          throw new FS.ErrnoError(63);
        }
        if (FS.isMountpoint(node)) {
          throw new FS.ErrnoError(10);
        }
        parent.node_ops.rmdir(parent, name);
        FS.destroyNode(node);
      },
      readdir(path2) {
        var lookup = FS.lookupPath(path2, { follow: true });
        var node = lookup.node;
        if (!node.node_ops.readdir) {
          throw new FS.ErrnoError(54);
        }
        return node.node_ops.readdir(node);
      },
      unlink(path2) {
        var lookup = FS.lookupPath(path2, { parent: true });
        var parent = lookup.node;
        if (!parent) {
          throw new FS.ErrnoError(44);
        }
        var name = PATH.basename(path2);
        var node = FS.lookupNode(parent, name);
        var errCode = FS.mayDelete(parent, name, false);
        if (errCode) {
          throw new FS.ErrnoError(errCode);
        }
        if (!parent.node_ops.unlink) {
          throw new FS.ErrnoError(63);
        }
        if (FS.isMountpoint(node)) {
          throw new FS.ErrnoError(10);
        }
        parent.node_ops.unlink(parent, name);
        FS.destroyNode(node);
      },
      readlink(path2) {
        var lookup = FS.lookupPath(path2);
        var link = lookup.node;
        if (!link) {
          throw new FS.ErrnoError(44);
        }
        if (!link.node_ops.readlink) {
          throw new FS.ErrnoError(28);
        }
        return PATH_FS.resolve(
          FS.getPath(link.parent),
          link.node_ops.readlink(link)
        );
      },
      stat(path2, dontFollow) {
        var lookup = FS.lookupPath(path2, { follow: !dontFollow });
        var node = lookup.node;
        if (!node) {
          throw new FS.ErrnoError(44);
        }
        if (!node.node_ops.getattr) {
          throw new FS.ErrnoError(63);
        }
        return node.node_ops.getattr(node);
      },
      lstat(path2) {
        return FS.stat(path2, true);
      },
      chmod(path2, mode, dontFollow) {
        var node;
        if (typeof path2 == "string") {
          var lookup = FS.lookupPath(path2, { follow: !dontFollow });
          node = lookup.node;
        } else {
          node = path2;
        }
        if (!node.node_ops.setattr) {
          throw new FS.ErrnoError(63);
        }
        node.node_ops.setattr(node, {
          mode: mode & 4095 | node.mode & ~4095,
          timestamp: Date.now()
        });
      },
      lchmod(path2, mode) {
        FS.chmod(path2, mode, true);
      },
      fchmod(fd, mode) {
        var stream = FS.getStreamChecked(fd);
        FS.chmod(stream.node, mode);
      },
      chown(path2, uid, gid, dontFollow) {
        var node;
        if (typeof path2 == "string") {
          var lookup = FS.lookupPath(path2, { follow: !dontFollow });
          node = lookup.node;
        } else {
          node = path2;
        }
        if (!node.node_ops.setattr) {
          throw new FS.ErrnoError(63);
        }
        node.node_ops.setattr(node, {
          timestamp: Date.now()
        });
      },
      lchown(path2, uid, gid) {
        FS.chown(path2, uid, gid, true);
      },
      fchown(fd, uid, gid) {
        var stream = FS.getStreamChecked(fd);
        FS.chown(stream.node, uid, gid);
      },
      truncate(path2, len) {
        if (len < 0) {
          throw new FS.ErrnoError(28);
        }
        var node;
        if (typeof path2 == "string") {
          var lookup = FS.lookupPath(path2, { follow: true });
          node = lookup.node;
        } else {
          node = path2;
        }
        if (!node.node_ops.setattr) {
          throw new FS.ErrnoError(63);
        }
        if (FS.isDir(node.mode)) {
          throw new FS.ErrnoError(31);
        }
        if (!FS.isFile(node.mode)) {
          throw new FS.ErrnoError(28);
        }
        var errCode = FS.nodePermissions(node, "w");
        if (errCode) {
          throw new FS.ErrnoError(errCode);
        }
        node.node_ops.setattr(node, {
          size: len,
          timestamp: Date.now()
        });
      },
      ftruncate(fd, len) {
        var stream = FS.getStreamChecked(fd);
        if ((stream.flags & 2097155) === 0) {
          throw new FS.ErrnoError(28);
        }
        FS.truncate(stream.node, len);
      },
      utime(path2, atime, mtime) {
        var lookup = FS.lookupPath(path2, { follow: true });
        var node = lookup.node;
        node.node_ops.setattr(node, {
          timestamp: Math.max(atime, mtime)
        });
      },
      open(path2, flags, mode) {
        if (path2 === "") {
          throw new FS.ErrnoError(44);
        }
        flags = typeof flags == "string" ? FS_modeStringToFlags(flags) : flags;
        if (flags & 64) {
          mode = typeof mode == "undefined" ? 438 : mode;
          mode = mode & 4095 | 32768;
        } else {
          mode = 0;
        }
        var node;
        if (typeof path2 == "object") {
          node = path2;
        } else {
          path2 = PATH.normalize(path2);
          try {
            var lookup = FS.lookupPath(path2, {
              follow: !(flags & 131072)
            });
            node = lookup.node;
          } catch (e2) {
          }
        }
        var created = false;
        if (flags & 64) {
          if (node) {
            if (flags & 128) {
              throw new FS.ErrnoError(20);
            }
          } else {
            node = FS.mknod(path2, mode, 0);
            created = true;
          }
        }
        if (!node) {
          throw new FS.ErrnoError(44);
        }
        if (FS.isChrdev(node.mode)) {
          flags &= ~512;
        }
        if (flags & 65536 && !FS.isDir(node.mode)) {
          throw new FS.ErrnoError(54);
        }
        if (!created) {
          var errCode = FS.mayOpen(node, flags);
          if (errCode) {
            throw new FS.ErrnoError(errCode);
          }
        }
        if (flags & 512 && !created) {
          FS.truncate(node, 0);
        }
        flags &= ~(128 | 512 | 131072);
        var stream = FS.createStream({
          node,
          path: FS.getPath(node),
          flags,
          seekable: true,
          position: 0,
          stream_ops: node.stream_ops,
          ungotten: [],
          error: false
        });
        if (stream.stream_ops.open) {
          stream.stream_ops.open(stream);
        }
        if (Module["logReadFiles"] && !(flags & 1)) {
          if (!(path2 in FS.readFiles)) {
            FS.readFiles[path2] = 1;
          }
        }
        return stream;
      },
      close(stream) {
        if (FS.isClosed(stream)) {
          throw new FS.ErrnoError(8);
        }
        if (stream.getdents)
          stream.getdents = null;
        try {
          if (stream.stream_ops.close) {
            stream.stream_ops.close(stream);
          }
        } catch (e2) {
          throw e2;
        } finally {
          FS.closeStream(stream.fd);
        }
        stream.fd = null;
      },
      isClosed(stream) {
        return stream.fd === null;
      },
      llseek(stream, offset, whence) {
        if (FS.isClosed(stream)) {
          throw new FS.ErrnoError(8);
        }
        if (!stream.seekable || !stream.stream_ops.llseek) {
          throw new FS.ErrnoError(70);
        }
        if (whence != 0 && whence != 1 && whence != 2) {
          throw new FS.ErrnoError(28);
        }
        stream.position = stream.stream_ops.llseek(stream, offset, whence);
        stream.ungotten = [];
        return stream.position;
      },
      read(stream, buffer, offset, length, position) {
        if (length < 0 || position < 0) {
          throw new FS.ErrnoError(28);
        }
        if (FS.isClosed(stream)) {
          throw new FS.ErrnoError(8);
        }
        if ((stream.flags & 2097155) === 1) {
          throw new FS.ErrnoError(8);
        }
        if (FS.isDir(stream.node.mode)) {
          throw new FS.ErrnoError(31);
        }
        if (!stream.stream_ops.read) {
          throw new FS.ErrnoError(28);
        }
        var seeking = typeof position != "undefined";
        if (!seeking) {
          position = stream.position;
        } else if (!stream.seekable) {
          throw new FS.ErrnoError(70);
        }
        var bytesRead = stream.stream_ops.read(
          stream,
          buffer,
          offset,
          length,
          position
        );
        if (!seeking)
          stream.position += bytesRead;
        return bytesRead;
      },
      write(stream, buffer, offset, length, position, canOwn) {
        if (length < 0 || position < 0) {
          throw new FS.ErrnoError(28);
        }
        if (FS.isClosed(stream)) {
          throw new FS.ErrnoError(8);
        }
        if ((stream.flags & 2097155) === 0) {
          throw new FS.ErrnoError(8);
        }
        if (FS.isDir(stream.node.mode)) {
          throw new FS.ErrnoError(31);
        }
        if (!stream.stream_ops.write) {
          throw new FS.ErrnoError(28);
        }
        if (stream.seekable && stream.flags & 1024) {
          FS.llseek(stream, 0, 2);
        }
        var seeking = typeof position != "undefined";
        if (!seeking) {
          position = stream.position;
        } else if (!stream.seekable) {
          throw new FS.ErrnoError(70);
        }
        var bytesWritten = stream.stream_ops.write(
          stream,
          buffer,
          offset,
          length,
          position,
          canOwn
        );
        if (!seeking)
          stream.position += bytesWritten;
        return bytesWritten;
      },
      allocate(stream, offset, length) {
        if (FS.isClosed(stream)) {
          throw new FS.ErrnoError(8);
        }
        if (offset < 0 || length <= 0) {
          throw new FS.ErrnoError(28);
        }
        if ((stream.flags & 2097155) === 0) {
          throw new FS.ErrnoError(8);
        }
        if (!FS.isFile(stream.node.mode) && !FS.isDir(stream.node.mode)) {
          throw new FS.ErrnoError(43);
        }
        if (!stream.stream_ops.allocate) {
          throw new FS.ErrnoError(138);
        }
        stream.stream_ops.allocate(stream, offset, length);
      },
      mmap(stream, length, position, prot, flags) {
        if ((prot & 2) !== 0 && (flags & 2) === 0 && (stream.flags & 2097155) !== 2) {
          throw new FS.ErrnoError(2);
        }
        if ((stream.flags & 2097155) === 1) {
          throw new FS.ErrnoError(2);
        }
        if (!stream.stream_ops.mmap) {
          throw new FS.ErrnoError(43);
        }
        if (!length) {
          throw new FS.ErrnoError(28);
        }
        return stream.stream_ops.mmap(stream, length, position, prot, flags);
      },
      msync(stream, buffer, offset, length, mmapFlags) {
        if (!stream.stream_ops.msync) {
          return 0;
        }
        return stream.stream_ops.msync(
          stream,
          buffer,
          offset,
          length,
          mmapFlags
        );
      },
      ioctl(stream, cmd, arg) {
        if (!stream.stream_ops.ioctl) {
          throw new FS.ErrnoError(59);
        }
        return stream.stream_ops.ioctl(stream, cmd, arg);
      },
      readFile(path2, opts = {}) {
        opts.flags = opts.flags || 0;
        opts.encoding = opts.encoding || "binary";
        if (opts.encoding !== "utf8" && opts.encoding !== "binary") {
          throw new Error(`Invalid encoding type "${opts.encoding}"`);
        }
        var ret;
        var stream = FS.open(path2, opts.flags);
        var stat = FS.stat(path2);
        var length = stat.size;
        var buf = new Uint8Array(length);
        FS.read(stream, buf, 0, length, 0);
        if (opts.encoding === "utf8") {
          ret = UTF8ArrayToString(buf);
        } else if (opts.encoding === "binary") {
          ret = buf;
        }
        FS.close(stream);
        return ret;
      },
      writeFile(path2, data, opts = {}) {
        opts.flags = opts.flags || 577;
        var stream = FS.open(path2, opts.flags, opts.mode);
        if (typeof data == "string") {
          var buf = new Uint8Array(lengthBytesUTF8(data) + 1);
          var actualNumBytes = stringToUTF8Array(data, buf, 0, buf.length);
          FS.write(stream, buf, 0, actualNumBytes, void 0, opts.canOwn);
        } else if (ArrayBuffer.isView(data)) {
          FS.write(stream, data, 0, data.byteLength, void 0, opts.canOwn);
        } else {
          throw new Error("Unsupported data type");
        }
        FS.close(stream);
      },
      cwd: () => FS.currentPath,
      chdir(path2) {
        var lookup = FS.lookupPath(path2, { follow: true });
        if (lookup.node === null) {
          throw new FS.ErrnoError(44);
        }
        if (!FS.isDir(lookup.node.mode)) {
          throw new FS.ErrnoError(54);
        }
        var errCode = FS.nodePermissions(lookup.node, "x");
        if (errCode) {
          throw new FS.ErrnoError(errCode);
        }
        FS.currentPath = lookup.path;
      },
      createDefaultDirectories() {
        FS.mkdir("/tmp");
        FS.mkdir("/home");
        FS.mkdir("/home/web_user");
      },
      createDefaultDevices() {
        FS.mkdir("/dev");
        FS.registerDevice(FS.makedev(1, 3), {
          read: () => 0,
          write: (stream, buffer, offset, length, pos) => length
        });
        FS.mkdev("/dev/null", FS.makedev(1, 3));
        TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
        TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
        FS.mkdev("/dev/tty", FS.makedev(5, 0));
        FS.mkdev("/dev/tty1", FS.makedev(6, 0));
        var randomBuffer = new Uint8Array(1024), randomLeft = 0;
        var randomByte = () => {
          if (randomLeft === 0) {
            randomLeft = randomFill(randomBuffer).byteLength;
          }
          return randomBuffer[--randomLeft];
        };
        FS.createDevice("/dev", "random", randomByte);
        FS.createDevice("/dev", "urandom", randomByte);
        FS.mkdir("/dev/shm");
        FS.mkdir("/dev/shm/tmp");
      },
      createSpecialDirectories() {
        FS.mkdir("/proc");
        var proc_self = FS.mkdir("/proc/self");
        FS.mkdir("/proc/self/fd");
        FS.mount(
          {
            mount() {
              var node = FS.createNode(proc_self, "fd", 16384 | 511, 73);
              node.node_ops = {
                lookup(parent, name) {
                  var fd = +name;
                  var stream = FS.getStreamChecked(fd);
                  var ret = {
                    parent: null,
                    mount: { mountpoint: "fake" },
                    node_ops: { readlink: () => stream.path }
                  };
                  ret.parent = ret;
                  return ret;
                }
              };
              return node;
            }
          },
          {},
          "/proc/self/fd"
        );
      },
      createStandardStreams(input, output, error) {
        if (input) {
          FS.createDevice("/dev", "stdin", input);
        } else {
          FS.symlink("/dev/tty", "/dev/stdin");
        }
        if (output) {
          FS.createDevice("/dev", "stdout", null, output);
        } else {
          FS.symlink("/dev/tty", "/dev/stdout");
        }
        if (error) {
          FS.createDevice("/dev", "stderr", null, error);
        } else {
          FS.symlink("/dev/tty1", "/dev/stderr");
        }
        var stdin2 = FS.open("/dev/stdin", 0);
        var stdout2 = FS.open("/dev/stdout", 1);
        var stderr = FS.open("/dev/stderr", 1);
      },
      staticInit() {
        [44].forEach((code) => {
          FS.genericErrors[code] = new FS.ErrnoError(code);
          FS.genericErrors[code].stack = "<generic error, no stack>";
        });
        FS.nameTable = new Array(4096);
        FS.mount(MEMFS, {}, "/");
        FS.createDefaultDirectories();
        FS.createDefaultDevices();
        FS.createSpecialDirectories();
        FS.filesystems = {
          MEMFS
        };
      },
      init(input, output, error) {
        FS.initialized = true;
        input ??= Module["stdin"];
        output ??= Module["stdout"];
        error ??= Module["stderr"];
        FS.createStandardStreams(input, output, error);
      },
      quit() {
        FS.initialized = false;
        for (var i2 = 0; i2 < FS.streams.length; i2++) {
          var stream = FS.streams[i2];
          if (!stream) {
            continue;
          }
          FS.close(stream);
        }
      },
      findObject(path2, dontResolveLastLink) {
        var ret = FS.analyzePath(path2, dontResolveLastLink);
        if (!ret.exists) {
          return null;
        }
        return ret.object;
      },
      analyzePath(path2, dontResolveLastLink) {
        try {
          var lookup = FS.lookupPath(path2, { follow: !dontResolveLastLink });
          path2 = lookup.path;
        } catch (e2) {
        }
        var ret = {
          isRoot: false,
          exists: false,
          error: 0,
          name: null,
          path: null,
          object: null,
          parentExists: false,
          parentPath: null,
          parentObject: null
        };
        try {
          var lookup = FS.lookupPath(path2, { parent: true });
          ret.parentExists = true;
          ret.parentPath = lookup.path;
          ret.parentObject = lookup.node;
          ret.name = PATH.basename(path2);
          lookup = FS.lookupPath(path2, { follow: !dontResolveLastLink });
          ret.exists = true;
          ret.path = lookup.path;
          ret.object = lookup.node;
          ret.name = lookup.node.name;
          ret.isRoot = lookup.path === "/";
        } catch (e2) {
          ret.error = e2.errno;
        }
        return ret;
      },
      createPath(parent, path2, canRead, canWrite) {
        parent = typeof parent == "string" ? parent : FS.getPath(parent);
        var parts = path2.split("/").reverse();
        while (parts.length) {
          var part = parts.pop();
          if (!part)
            continue;
          var current = PATH.join2(parent, part);
          try {
            FS.mkdir(current);
          } catch (e2) {
          }
          parent = current;
        }
        return current;
      },
      createFile(parent, name, properties, canRead, canWrite) {
        var path2 = PATH.join2(
          typeof parent == "string" ? parent : FS.getPath(parent),
          name
        );
        var mode = FS_getMode(canRead, canWrite);
        return FS.create(path2, mode);
      },
      createDataFile(parent, name, data, canRead, canWrite, canOwn) {
        var path2 = name;
        if (parent) {
          parent = typeof parent == "string" ? parent : FS.getPath(parent);
          path2 = name ? PATH.join2(parent, name) : parent;
        }
        var mode = FS_getMode(canRead, canWrite);
        var node = FS.create(path2, mode);
        if (data) {
          if (typeof data == "string") {
            var arr = new Array(data.length);
            for (var i2 = 0, len = data.length; i2 < len; ++i2)
              arr[i2] = data.charCodeAt(i2);
            data = arr;
          }
          FS.chmod(node, mode | 146);
          var stream = FS.open(node, 577);
          FS.write(stream, data, 0, data.length, 0, canOwn);
          FS.close(stream);
          FS.chmod(node, mode);
        }
      },
      createDevice(parent, name, input, output) {
        var path2 = PATH.join2(
          typeof parent == "string" ? parent : FS.getPath(parent),
          name
        );
        var mode = FS_getMode(!!input, !!output);
        FS.createDevice.major ??= 64;
        var dev = FS.makedev(FS.createDevice.major++, 0);
        FS.registerDevice(dev, {
          open(stream) {
            stream.seekable = false;
          },
          close(stream) {
            var _a8;
            if ((_a8 = output == null ? void 0 : output.buffer) == null ? void 0 : _a8.length) {
              output(10);
            }
          },
          read(stream, buffer, offset, length, pos) {
            var bytesRead = 0;
            for (var i2 = 0; i2 < length; i2++) {
              var result;
              try {
                result = input();
              } catch (e2) {
                throw new FS.ErrnoError(29);
              }
              if (result === void 0 && bytesRead === 0) {
                throw new FS.ErrnoError(6);
              }
              if (result === null || result === void 0)
                break;
              bytesRead++;
              buffer[offset + i2] = result;
            }
            if (bytesRead) {
              stream.node.timestamp = Date.now();
            }
            return bytesRead;
          },
          write(stream, buffer, offset, length, pos) {
            for (var i2 = 0; i2 < length; i2++) {
              try {
                output(buffer[offset + i2]);
              } catch (e2) {
                throw new FS.ErrnoError(29);
              }
            }
            if (length) {
              stream.node.timestamp = Date.now();
            }
            return i2;
          }
        });
        return FS.mkdev(path2, mode, dev);
      },
      forceLoadFile(obj) {
        if (obj.isDevice || obj.isFolder || obj.link || obj.contents)
          return true;
        if (typeof XMLHttpRequest != "undefined") {
          throw new Error(
            "Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread."
          );
        } else {
          try {
            obj.contents = readBinary(obj.url);
            obj.usedBytes = obj.contents.length;
          } catch (e2) {
            throw new FS.ErrnoError(29);
          }
        }
      },
      createLazyFile(parent, name, url, canRead, canWrite) {
        class LazyUint8Array {
          constructor() {
            this.lengthKnown = false;
            this.chunks = [];
          }
          get(idx) {
            if (idx > this.length - 1 || idx < 0) {
              return void 0;
            }
            var chunkOffset = idx % this.chunkSize;
            var chunkNum = idx / this.chunkSize | 0;
            return this.getter(chunkNum)[chunkOffset];
          }
          setDataGetter(getter) {
            this.getter = getter;
          }
          cacheLength() {
            var xhr = new XMLHttpRequest();
            xhr.open("HEAD", url, false);
            xhr.send(null);
            if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304))
              throw new Error(
                "Couldn't load " + url + ". Status: " + xhr.status
              );
            var datalength = Number(xhr.getResponseHeader("Content-length"));
            var header;
            var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
            var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";
            var chunkSize = 1024 * 1024;
            if (!hasByteServing)
              chunkSize = datalength;
            var doXHR = (from, to) => {
              if (from > to)
                throw new Error(
                  "invalid range (" + from + ", " + to + ") or no bytes requested!"
                );
              if (to > datalength - 1)
                throw new Error(
                  "only " + datalength + " bytes available! programmer error!"
                );
              var xhr2 = new XMLHttpRequest();
              xhr2.open("GET", url, false);
              if (datalength !== chunkSize)
                xhr2.setRequestHeader("Range", "bytes=" + from + "-" + to);
              xhr2.responseType = "arraybuffer";
              if (xhr2.overrideMimeType) {
                xhr2.overrideMimeType("text/plain; charset=x-user-defined");
              }
              xhr2.send(null);
              if (!(xhr2.status >= 200 && xhr2.status < 300 || xhr2.status === 304))
                throw new Error(
                  "Couldn't load " + url + ". Status: " + xhr2.status
                );
              if (xhr2.response !== void 0) {
                return new Uint8Array(xhr2.response || []);
              }
              return intArrayFromString(xhr2.responseText || "", true);
            };
            var lazyArray2 = this;
            lazyArray2.setDataGetter((chunkNum) => {
              var start = chunkNum * chunkSize;
              var end = (chunkNum + 1) * chunkSize - 1;
              end = Math.min(end, datalength - 1);
              if (typeof lazyArray2.chunks[chunkNum] == "undefined") {
                lazyArray2.chunks[chunkNum] = doXHR(start, end);
              }
              if (typeof lazyArray2.chunks[chunkNum] == "undefined")
                throw new Error("doXHR failed!");
              return lazyArray2.chunks[chunkNum];
            });
            if (usesGzip || !datalength) {
              chunkSize = datalength = 1;
              datalength = this.getter(0).length;
              chunkSize = datalength;
              out(
                "LazyFiles on gzip forces download of the whole file when length is accessed"
              );
            }
            this._length = datalength;
            this._chunkSize = chunkSize;
            this.lengthKnown = true;
          }
          get length() {
            if (!this.lengthKnown) {
              this.cacheLength();
            }
            return this._length;
          }
          get chunkSize() {
            if (!this.lengthKnown) {
              this.cacheLength();
            }
            return this._chunkSize;
          }
        }
        if (typeof XMLHttpRequest != "undefined") {
          if (!ENVIRONMENT_IS_WORKER)
            throw "Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";
          var lazyArray = new LazyUint8Array();
          var properties = { isDevice: false, contents: lazyArray };
        } else {
          var properties = { isDevice: false, url };
        }
        var node = FS.createFile(parent, name, properties, canRead, canWrite);
        if (properties.contents) {
          node.contents = properties.contents;
        } else if (properties.url) {
          node.contents = null;
          node.url = properties.url;
        }
        Object.defineProperties(node, {
          usedBytes: {
            get: function() {
              return this.contents.length;
            }
          }
        });
        var stream_ops = {};
        var keys = Object.keys(node.stream_ops);
        keys.forEach((key) => {
          var fn = node.stream_ops[key];
          stream_ops[key] = (...args) => {
            FS.forceLoadFile(node);
            return fn(...args);
          };
        });
        function writeChunks(stream, buffer, offset, length, position) {
          var contents = stream.node.contents;
          if (position >= contents.length)
            return 0;
          var size = Math.min(contents.length - position, length);
          if (contents.slice) {
            for (var i2 = 0; i2 < size; i2++) {
              buffer[offset + i2] = contents[position + i2];
            }
          } else {
            for (var i2 = 0; i2 < size; i2++) {
              buffer[offset + i2] = contents.get(position + i2);
            }
          }
          return size;
        }
        stream_ops.read = (stream, buffer, offset, length, position) => {
          FS.forceLoadFile(node);
          return writeChunks(stream, buffer, offset, length, position);
        };
        stream_ops.mmap = (stream, length, position, prot, flags) => {
          FS.forceLoadFile(node);
          var ptr = mmapAlloc(length);
          if (!ptr) {
            throw new FS.ErrnoError(48);
          }
          writeChunks(stream, HEAP8, ptr, length, position);
          return { ptr, allocated: true };
        };
        node.stream_ops = stream_ops;
        return node;
      }
    };
    var UTF8ToString = (ptr, maxBytesToRead) => {
      return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : "";
    };
    var SYSCALLS = {
      DEFAULT_POLLMASK: 5,
      calculateAt(dirfd, path2, allowEmpty) {
        if (PATH.isAbs(path2)) {
          return path2;
        }
        var dir;
        if (dirfd === -100) {
          dir = FS.cwd();
        } else {
          var dirstream = SYSCALLS.getStreamFromFD(dirfd);
          dir = dirstream.path;
        }
        if (path2.length == 0) {
          if (!allowEmpty) {
            throw new FS.ErrnoError(44);
          }
          return dir;
        }
        return PATH.join2(dir, path2);
      },
      doStat(func, path2, buf) {
        var stat = func(path2);
        HEAP32[buf >> 2] = stat.dev;
        HEAP32[buf + 4 >> 2] = stat.mode;
        HEAPU32[buf + 8 >> 2] = stat.nlink;
        HEAP32[buf + 12 >> 2] = stat.uid;
        HEAP32[buf + 16 >> 2] = stat.gid;
        HEAP32[buf + 20 >> 2] = stat.rdev;
        HEAP64[buf + 24 >> 3] = BigInt(stat.size);
        HEAP32[buf + 32 >> 2] = 4096;
        HEAP32[buf + 36 >> 2] = stat.blocks;
        var atime = stat.atime.getTime();
        var mtime = stat.mtime.getTime();
        var ctime = stat.ctime.getTime();
        HEAP64[buf + 40 >> 3] = BigInt(Math.floor(atime / 1e3));
        HEAPU32[buf + 48 >> 2] = atime % 1e3 * 1e3 * 1e3;
        HEAP64[buf + 56 >> 3] = BigInt(Math.floor(mtime / 1e3));
        HEAPU32[buf + 64 >> 2] = mtime % 1e3 * 1e3 * 1e3;
        HEAP64[buf + 72 >> 3] = BigInt(Math.floor(ctime / 1e3));
        HEAPU32[buf + 80 >> 2] = ctime % 1e3 * 1e3 * 1e3;
        HEAP64[buf + 88 >> 3] = BigInt(stat.ino);
        return 0;
      },
      doMsync(addr, stream, len, flags, offset) {
        if (!FS.isFile(stream.node.mode)) {
          throw new FS.ErrnoError(43);
        }
        if (flags & 2) {
          return 0;
        }
        var buffer = HEAPU8.slice(addr, addr + len);
        FS.msync(stream, buffer, offset, len, flags);
      },
      getStreamFromFD(fd) {
        var stream = FS.getStreamChecked(fd);
        return stream;
      },
      varargs: void 0,
      getStr(ptr) {
        var ret = UTF8ToString(ptr);
        return ret;
      }
    };
    function ___syscall_chmod(path2, mode) {
      try {
        path2 = SYSCALLS.getStr(path2);
        FS.chmod(path2, mode);
        return 0;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    function ___syscall_faccessat(dirfd, path2, amode, flags) {
      try {
        path2 = SYSCALLS.getStr(path2);
        path2 = SYSCALLS.calculateAt(dirfd, path2);
        if (amode & ~7) {
          return -28;
        }
        var lookup = FS.lookupPath(path2, { follow: true });
        var node = lookup.node;
        if (!node) {
          return -44;
        }
        var perms = "";
        if (amode & 4)
          perms += "r";
        if (amode & 2)
          perms += "w";
        if (amode & 1)
          perms += "x";
        if (perms && FS.nodePermissions(node, perms)) {
          return -2;
        }
        return 0;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    function ___syscall_fchmod(fd, mode) {
      try {
        FS.fchmod(fd, mode);
        return 0;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    function ___syscall_fchown32(fd, owner, group) {
      try {
        FS.fchown(fd, owner, group);
        return 0;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    function syscallGetVarargI() {
      var ret = HEAP32[+SYSCALLS.varargs >> 2];
      SYSCALLS.varargs += 4;
      return ret;
    }
    var syscallGetVarargP = syscallGetVarargI;
    function ___syscall_fcntl64(fd, cmd, varargs) {
      SYSCALLS.varargs = varargs;
      try {
        var stream = SYSCALLS.getStreamFromFD(fd);
        switch (cmd) {
          case 0: {
            var arg = syscallGetVarargI();
            if (arg < 0) {
              return -28;
            }
            while (FS.streams[arg]) {
              arg++;
            }
            var newStream;
            newStream = FS.dupStream(stream, arg);
            return newStream.fd;
          }
          case 1:
          case 2:
            return 0;
          case 3:
            return stream.flags;
          case 4: {
            var arg = syscallGetVarargI();
            stream.flags |= arg;
            return 0;
          }
          case 12: {
            var arg = syscallGetVarargP();
            var offset = 0;
            HEAP16[arg + offset >> 1] = 2;
            return 0;
          }
          case 13:
          case 14:
            return 0;
        }
        return -28;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    function ___syscall_fstat64(fd, buf) {
      try {
        var stream = SYSCALLS.getStreamFromFD(fd);
        return SYSCALLS.doStat(FS.stat, stream.path, buf);
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    var INT53_MAX = 9007199254740992;
    var INT53_MIN = -9007199254740992;
    var bigintToI53Checked = (num) => num < INT53_MIN || num > INT53_MAX ? NaN : Number(num);
    function ___syscall_ftruncate64(fd, length) {
      length = bigintToI53Checked(length);
      try {
        if (isNaN(length))
          return 61;
        FS.ftruncate(fd, length);
        return 0;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    var stringToUTF8 = (str, outPtr, maxBytesToWrite) => {
      return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);
    };
    function ___syscall_getcwd(buf, size) {
      try {
        if (size === 0)
          return -28;
        var cwd = FS.cwd();
        var cwdLengthInBytes = lengthBytesUTF8(cwd) + 1;
        if (size < cwdLengthInBytes)
          return -68;
        stringToUTF8(cwd, buf, size);
        return cwdLengthInBytes;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    function ___syscall_ioctl(fd, op, varargs) {
      SYSCALLS.varargs = varargs;
      try {
        var stream = SYSCALLS.getStreamFromFD(fd);
        switch (op) {
          case 21509: {
            if (!stream.tty)
              return -59;
            return 0;
          }
          case 21505: {
            if (!stream.tty)
              return -59;
            if (stream.tty.ops.ioctl_tcgets) {
              var termios = stream.tty.ops.ioctl_tcgets(stream);
              var argp = syscallGetVarargP();
              HEAP32[argp >> 2] = termios.c_iflag || 0;
              HEAP32[argp + 4 >> 2] = termios.c_oflag || 0;
              HEAP32[argp + 8 >> 2] = termios.c_cflag || 0;
              HEAP32[argp + 12 >> 2] = termios.c_lflag || 0;
              for (var i2 = 0; i2 < 32; i2++) {
                HEAP8[argp + i2 + 17] = termios.c_cc[i2] || 0;
              }
              return 0;
            }
            return 0;
          }
          case 21510:
          case 21511:
          case 21512: {
            if (!stream.tty)
              return -59;
            return 0;
          }
          case 21506:
          case 21507:
          case 21508: {
            if (!stream.tty)
              return -59;
            if (stream.tty.ops.ioctl_tcsets) {
              var argp = syscallGetVarargP();
              var c_iflag = HEAP32[argp >> 2];
              var c_oflag = HEAP32[argp + 4 >> 2];
              var c_cflag = HEAP32[argp + 8 >> 2];
              var c_lflag = HEAP32[argp + 12 >> 2];
              var c_cc = [];
              for (var i2 = 0; i2 < 32; i2++) {
                c_cc.push(HEAP8[argp + i2 + 17]);
              }
              return stream.tty.ops.ioctl_tcsets(stream.tty, op, {
                c_iflag,
                c_oflag,
                c_cflag,
                c_lflag,
                c_cc
              });
            }
            return 0;
          }
          case 21519: {
            if (!stream.tty)
              return -59;
            var argp = syscallGetVarargP();
            HEAP32[argp >> 2] = 0;
            return 0;
          }
          case 21520: {
            if (!stream.tty)
              return -59;
            return -28;
          }
          case 21531: {
            var argp = syscallGetVarargP();
            return FS.ioctl(stream, op, argp);
          }
          case 21523: {
            if (!stream.tty)
              return -59;
            if (stream.tty.ops.ioctl_tiocgwinsz) {
              var winsize = stream.tty.ops.ioctl_tiocgwinsz(stream.tty);
              var argp = syscallGetVarargP();
              HEAP16[argp >> 1] = winsize[0];
              HEAP16[argp + 2 >> 1] = winsize[1];
            }
            return 0;
          }
          case 21524: {
            if (!stream.tty)
              return -59;
            return 0;
          }
          case 21515: {
            if (!stream.tty)
              return -59;
            return 0;
          }
          default:
            return -28;
        }
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    function ___syscall_lstat64(path2, buf) {
      try {
        path2 = SYSCALLS.getStr(path2);
        return SYSCALLS.doStat(FS.lstat, path2, buf);
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    function ___syscall_mkdirat(dirfd, path2, mode) {
      try {
        path2 = SYSCALLS.getStr(path2);
        path2 = SYSCALLS.calculateAt(dirfd, path2);
        path2 = PATH.normalize(path2);
        if (path2[path2.length - 1] === "/")
          path2 = path2.substr(0, path2.length - 1);
        FS.mkdir(path2, mode, 0);
        return 0;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    function ___syscall_newfstatat(dirfd, path2, buf, flags) {
      try {
        path2 = SYSCALLS.getStr(path2);
        var nofollow = flags & 256;
        var allowEmpty = flags & 4096;
        flags = flags & ~6400;
        path2 = SYSCALLS.calculateAt(dirfd, path2, allowEmpty);
        return SYSCALLS.doStat(nofollow ? FS.lstat : FS.stat, path2, buf);
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    function ___syscall_openat(dirfd, path2, flags, varargs) {
      SYSCALLS.varargs = varargs;
      try {
        path2 = SYSCALLS.getStr(path2);
        path2 = SYSCALLS.calculateAt(dirfd, path2);
        var mode = varargs ? syscallGetVarargI() : 0;
        return FS.open(path2, flags, mode).fd;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    function ___syscall_readlinkat(dirfd, path2, buf, bufsize) {
      try {
        path2 = SYSCALLS.getStr(path2);
        path2 = SYSCALLS.calculateAt(dirfd, path2);
        if (bufsize <= 0)
          return -28;
        var ret = FS.readlink(path2);
        var len = Math.min(bufsize, lengthBytesUTF8(ret));
        var endChar = HEAP8[buf + len];
        stringToUTF8(ret, buf, bufsize + 1);
        HEAP8[buf + len] = endChar;
        return len;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    function ___syscall_rmdir(path2) {
      try {
        path2 = SYSCALLS.getStr(path2);
        FS.rmdir(path2);
        return 0;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    function ___syscall_stat64(path2, buf) {
      try {
        path2 = SYSCALLS.getStr(path2);
        return SYSCALLS.doStat(FS.stat, path2, buf);
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    function ___syscall_unlinkat(dirfd, path2, flags) {
      try {
        path2 = SYSCALLS.getStr(path2);
        path2 = SYSCALLS.calculateAt(dirfd, path2);
        if (flags === 0) {
          FS.unlink(path2);
        } else if (flags === 512) {
          FS.rmdir(path2);
        } else {
          abort("Invalid flags passed to unlinkat");
        }
        return 0;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    var readI53FromI64 = (ptr) => {
      return HEAPU32[ptr >> 2] + HEAP32[ptr + 4 >> 2] * 4294967296;
    };
    function ___syscall_utimensat(dirfd, path2, times, flags) {
      try {
        path2 = SYSCALLS.getStr(path2);
        path2 = SYSCALLS.calculateAt(dirfd, path2, true);
        var now = Date.now(), atime, mtime;
        if (!times) {
          atime = now;
          mtime = now;
        } else {
          var seconds = readI53FromI64(times);
          var nanoseconds = HEAP32[times + 8 >> 2];
          if (nanoseconds == 1073741823) {
            atime = now;
          } else if (nanoseconds == 1073741822) {
            atime = -1;
          } else {
            atime = seconds * 1e3 + nanoseconds / (1e3 * 1e3);
          }
          times += 16;
          seconds = readI53FromI64(times);
          nanoseconds = HEAP32[times + 8 >> 2];
          if (nanoseconds == 1073741823) {
            mtime = now;
          } else if (nanoseconds == 1073741822) {
            mtime = -1;
          } else {
            mtime = seconds * 1e3 + nanoseconds / (1e3 * 1e3);
          }
        }
        if (mtime != -1 || atime != -1) {
          FS.utime(path2, atime, mtime);
        }
        return 0;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    var nowIsMonotonic = 1;
    var __emscripten_get_now_is_monotonic = () => nowIsMonotonic;
    var isLeapYear = (year) => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    var MONTH_DAYS_LEAP_CUMULATIVE = [
      0,
      31,
      60,
      91,
      121,
      152,
      182,
      213,
      244,
      274,
      305,
      335
    ];
    var MONTH_DAYS_REGULAR_CUMULATIVE = [
      0,
      31,
      59,
      90,
      120,
      151,
      181,
      212,
      243,
      273,
      304,
      334
    ];
    var ydayFromDate = (date) => {
      var leap = isLeapYear(date.getFullYear());
      var monthDaysCumulative = leap ? MONTH_DAYS_LEAP_CUMULATIVE : MONTH_DAYS_REGULAR_CUMULATIVE;
      var yday = monthDaysCumulative[date.getMonth()] + date.getDate() - 1;
      return yday;
    };
    function __localtime_js(time, tmPtr) {
      time = bigintToI53Checked(time);
      var date = new Date(time * 1e3);
      HEAP32[tmPtr >> 2] = date.getSeconds();
      HEAP32[tmPtr + 4 >> 2] = date.getMinutes();
      HEAP32[tmPtr + 8 >> 2] = date.getHours();
      HEAP32[tmPtr + 12 >> 2] = date.getDate();
      HEAP32[tmPtr + 16 >> 2] = date.getMonth();
      HEAP32[tmPtr + 20 >> 2] = date.getFullYear() - 1900;
      HEAP32[tmPtr + 24 >> 2] = date.getDay();
      var yday = ydayFromDate(date) | 0;
      HEAP32[tmPtr + 28 >> 2] = yday;
      HEAP32[tmPtr + 36 >> 2] = -(date.getTimezoneOffset() * 60);
      var start = new Date(date.getFullYear(), 0, 1);
      var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();
      var winterOffset = start.getTimezoneOffset();
      var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset)) | 0;
      HEAP32[tmPtr + 32 >> 2] = dst;
    }
    function __mmap_js(len, prot, flags, fd, offset, allocated, addr) {
      offset = bigintToI53Checked(offset);
      try {
        if (isNaN(offset))
          return 61;
        var stream = SYSCALLS.getStreamFromFD(fd);
        var res = FS.mmap(stream, len, offset, prot, flags);
        var ptr = res.ptr;
        HEAP32[allocated >> 2] = res.allocated;
        HEAPU32[addr >> 2] = ptr;
        return 0;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    function __munmap_js(addr, len, prot, flags, fd, offset) {
      offset = bigintToI53Checked(offset);
      try {
        var stream = SYSCALLS.getStreamFromFD(fd);
        if (prot & 2) {
          SYSCALLS.doMsync(addr, stream, len, flags, offset);
        }
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return -e2.errno;
      }
    }
    var __tzset_js = (timezone, daylight, std_name, dst_name) => {
      var currentYear = (/* @__PURE__ */ new Date()).getFullYear();
      var winter = new Date(currentYear, 0, 1);
      var summer = new Date(currentYear, 6, 1);
      var winterOffset = winter.getTimezoneOffset();
      var summerOffset = summer.getTimezoneOffset();
      var stdTimezoneOffset = Math.max(winterOffset, summerOffset);
      HEAPU32[timezone >> 2] = stdTimezoneOffset * 60;
      HEAP32[daylight >> 2] = Number(winterOffset != summerOffset);
      var extractZone = (timezoneOffset) => {
        var sign = timezoneOffset >= 0 ? "-" : "+";
        var absOffset = Math.abs(timezoneOffset);
        var hours = String(Math.floor(absOffset / 60)).padStart(2, "0");
        var minutes = String(absOffset % 60).padStart(2, "0");
        return `UTC${sign}${hours}${minutes}`;
      };
      var winterName = extractZone(winterOffset);
      var summerName = extractZone(summerOffset);
      if (summerOffset < winterOffset) {
        stringToUTF8(winterName, std_name, 17);
        stringToUTF8(summerName, dst_name, 17);
      } else {
        stringToUTF8(winterName, dst_name, 17);
        stringToUTF8(summerName, std_name, 17);
      }
    };
    var _emscripten_date_now = () => Date.now();
    var _emscripten_get_now = () => performance.now();
    var getHeapMax = () => 2147483648;
    var growMemory = (size) => {
      var b = wasmMemory.buffer;
      var pages = (size - b.byteLength + 65535) / 65536 | 0;
      try {
        wasmMemory.grow(pages);
        updateMemoryViews();
        return 1;
      } catch (e2) {
      }
    };
    var _emscripten_resize_heap = (requestedSize) => {
      var oldSize = HEAPU8.length;
      requestedSize >>>= 0;
      var maxHeapSize = getHeapMax();
      if (requestedSize > maxHeapSize) {
        return false;
      }
      for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
        var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
        overGrownHeapSize = Math.min(
          overGrownHeapSize,
          requestedSize + 100663296
        );
        var newSize = Math.min(
          maxHeapSize,
          alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536)
        );
        var replacement = growMemory(newSize);
        if (replacement) {
          return true;
        }
      }
      return false;
    };
    var ENV = {};
    var getExecutableName = () => {
      return thisProgram || "./this.program";
    };
    var getEnvStrings = () => {
      if (!getEnvStrings.strings) {
        var lang = (typeof navigator == "object" && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8";
        var env2 = {
          USER: "web_user",
          LOGNAME: "web_user",
          PATH: "/",
          PWD: "/",
          HOME: "/home/web_user",
          LANG: lang,
          _: getExecutableName()
        };
        for (var x2 in ENV) {
          if (ENV[x2] === void 0)
            delete env2[x2];
          else
            env2[x2] = ENV[x2];
        }
        var strings = [];
        for (var x2 in env2) {
          strings.push(`${x2}=${env2[x2]}`);
        }
        getEnvStrings.strings = strings;
      }
      return getEnvStrings.strings;
    };
    var stringToAscii = (str, buffer) => {
      for (var i2 = 0; i2 < str.length; ++i2) {
        HEAP8[buffer++] = str.charCodeAt(i2);
      }
      HEAP8[buffer] = 0;
    };
    var _environ_get = (__environ, environ_buf) => {
      var bufSize = 0;
      getEnvStrings().forEach((string, i2) => {
        var ptr = environ_buf + bufSize;
        HEAPU32[__environ + i2 * 4 >> 2] = ptr;
        stringToAscii(string, ptr);
        bufSize += string.length + 1;
      });
      return 0;
    };
    var _environ_sizes_get = (penviron_count, penviron_buf_size) => {
      var strings = getEnvStrings();
      HEAPU32[penviron_count >> 2] = strings.length;
      var bufSize = 0;
      strings.forEach((string) => bufSize += string.length + 1);
      HEAPU32[penviron_buf_size >> 2] = bufSize;
      return 0;
    };
    function _fd_close(fd) {
      try {
        var stream = SYSCALLS.getStreamFromFD(fd);
        FS.close(stream);
        return 0;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return e2.errno;
      }
    }
    function _fd_fdstat_get(fd, pbuf) {
      try {
        var rightsBase = 0;
        var rightsInheriting = 0;
        var flags = 0;
        {
          var stream = SYSCALLS.getStreamFromFD(fd);
          var type = stream.tty ? 2 : FS.isDir(stream.mode) ? 3 : FS.isLink(stream.mode) ? 7 : 4;
        }
        HEAP8[pbuf] = type;
        HEAP16[pbuf + 2 >> 1] = flags;
        HEAP64[pbuf + 8 >> 3] = BigInt(rightsBase);
        HEAP64[pbuf + 16 >> 3] = BigInt(rightsInheriting);
        return 0;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return e2.errno;
      }
    }
    var doReadv = (stream, iov, iovcnt, offset) => {
      var ret = 0;
      for (var i2 = 0; i2 < iovcnt; i2++) {
        var ptr = HEAPU32[iov >> 2];
        var len = HEAPU32[iov + 4 >> 2];
        iov += 8;
        var curr = FS.read(stream, HEAP8, ptr, len, offset);
        if (curr < 0)
          return -1;
        ret += curr;
        if (curr < len)
          break;
        if (typeof offset != "undefined") {
          offset += curr;
        }
      }
      return ret;
    };
    function _fd_read(fd, iov, iovcnt, pnum) {
      try {
        var stream = SYSCALLS.getStreamFromFD(fd);
        var num = doReadv(stream, iov, iovcnt);
        HEAPU32[pnum >> 2] = num;
        return 0;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return e2.errno;
      }
    }
    function _fd_seek(fd, offset, whence, newOffset) {
      offset = bigintToI53Checked(offset);
      try {
        if (isNaN(offset))
          return 61;
        var stream = SYSCALLS.getStreamFromFD(fd);
        FS.llseek(stream, offset, whence);
        HEAP64[newOffset >> 3] = BigInt(stream.position);
        if (stream.getdents && offset === 0 && whence === 0)
          stream.getdents = null;
        return 0;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return e2.errno;
      }
    }
    function _fd_sync(fd) {
      var _a8;
      try {
        var stream = SYSCALLS.getStreamFromFD(fd);
        if ((_a8 = stream.stream_ops) == null ? void 0 : _a8.fsync) {
          return stream.stream_ops.fsync(stream);
        }
        return 0;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return e2.errno;
      }
    }
    var doWritev = (stream, iov, iovcnt, offset) => {
      var ret = 0;
      for (var i2 = 0; i2 < iovcnt; i2++) {
        var ptr = HEAPU32[iov >> 2];
        var len = HEAPU32[iov + 4 >> 2];
        iov += 8;
        var curr = FS.write(stream, HEAP8, ptr, len, offset);
        if (curr < 0)
          return -1;
        ret += curr;
        if (curr < len) {
          break;
        }
        if (typeof offset != "undefined") {
          offset += curr;
        }
      }
      return ret;
    };
    function _fd_write(fd, iov, iovcnt, pnum) {
      try {
        var stream = SYSCALLS.getStreamFromFD(fd);
        var num = doWritev(stream, iov, iovcnt);
        HEAPU32[pnum >> 2] = num;
        return 0;
      } catch (e2) {
        if (typeof FS == "undefined" || !(e2.name === "ErrnoError"))
          throw e2;
        return e2.errno;
      }
    }
    FS.createPreloadedFile = FS_createPreloadedFile;
    FS.staticInit();
    var wasmImports = {
      __syscall_chmod: ___syscall_chmod,
      __syscall_faccessat: ___syscall_faccessat,
      __syscall_fchmod: ___syscall_fchmod,
      __syscall_fchown32: ___syscall_fchown32,
      __syscall_fcntl64: ___syscall_fcntl64,
      __syscall_fstat64: ___syscall_fstat64,
      __syscall_ftruncate64: ___syscall_ftruncate64,
      __syscall_getcwd: ___syscall_getcwd,
      __syscall_ioctl: ___syscall_ioctl,
      __syscall_lstat64: ___syscall_lstat64,
      __syscall_mkdirat: ___syscall_mkdirat,
      __syscall_newfstatat: ___syscall_newfstatat,
      __syscall_openat: ___syscall_openat,
      __syscall_readlinkat: ___syscall_readlinkat,
      __syscall_rmdir: ___syscall_rmdir,
      __syscall_stat64: ___syscall_stat64,
      __syscall_unlinkat: ___syscall_unlinkat,
      __syscall_utimensat: ___syscall_utimensat,
      _emscripten_get_now_is_monotonic: __emscripten_get_now_is_monotonic,
      _localtime_js: __localtime_js,
      _mmap_js: __mmap_js,
      _munmap_js: __munmap_js,
      _tzset_js: __tzset_js,
      emscripten_date_now: _emscripten_date_now,
      emscripten_get_now: _emscripten_get_now,
      emscripten_resize_heap: _emscripten_resize_heap,
      environ_get: _environ_get,
      environ_sizes_get: _environ_sizes_get,
      fd_close: _fd_close,
      fd_fdstat_get: _fd_fdstat_get,
      fd_read: _fd_read,
      fd_seek: _fd_seek,
      fd_sync: _fd_sync,
      fd_write: _fd_write,
      memory: wasmMemory
    };
    var wasmExports = createWasm();
    var ___wasm_call_ctors = () => (___wasm_call_ctors = wasmExports["__wasm_call_ctors"])();
    var _sqlite3_status64 = Module["_sqlite3_status64"] = (a0, a1, a22, a3) => (_sqlite3_status64 = Module["_sqlite3_status64"] = wasmExports["sqlite3_status64"])(a0, a1, a22, a3);
    var _sqlite3_status = Module["_sqlite3_status"] = (a0, a1, a22, a3) => (_sqlite3_status = Module["_sqlite3_status"] = wasmExports["sqlite3_status"])(a0, a1, a22, a3);
    var _sqlite3_db_status = Module["_sqlite3_db_status"] = (a0, a1, a22, a3, a4) => (_sqlite3_db_status = Module["_sqlite3_db_status"] = wasmExports["sqlite3_db_status"])(a0, a1, a22, a3, a4);
    var _sqlite3_msize = Module["_sqlite3_msize"] = (a0) => (_sqlite3_msize = Module["_sqlite3_msize"] = wasmExports["sqlite3_msize"])(a0);
    var _sqlite3_vfs_find = Module["_sqlite3_vfs_find"] = (a0) => (_sqlite3_vfs_find = Module["_sqlite3_vfs_find"] = wasmExports["sqlite3_vfs_find"])(a0);
    var _sqlite3_initialize = Module["_sqlite3_initialize"] = () => (_sqlite3_initialize = Module["_sqlite3_initialize"] = wasmExports["sqlite3_initialize"])();
    var _sqlite3_malloc = Module["_sqlite3_malloc"] = (a0) => (_sqlite3_malloc = Module["_sqlite3_malloc"] = wasmExports["sqlite3_malloc"])(a0);
    var _sqlite3_free = Module["_sqlite3_free"] = (a0) => (_sqlite3_free = Module["_sqlite3_free"] = wasmExports["sqlite3_free"])(
      a0
    );
    var _sqlite3_vfs_register = Module["_sqlite3_vfs_register"] = (a0, a1) => (_sqlite3_vfs_register = Module["_sqlite3_vfs_register"] = wasmExports["sqlite3_vfs_register"])(a0, a1);
    var _sqlite3_vfs_unregister = Module["_sqlite3_vfs_unregister"] = (a0) => (_sqlite3_vfs_unregister = Module["_sqlite3_vfs_unregister"] = wasmExports["sqlite3_vfs_unregister"])(a0);
    var _sqlite3_malloc64 = Module["_sqlite3_malloc64"] = (a0) => (_sqlite3_malloc64 = Module["_sqlite3_malloc64"] = wasmExports["sqlite3_malloc64"])(a0);
    var _sqlite3_realloc = Module["_sqlite3_realloc"] = (a0, a1) => (_sqlite3_realloc = Module["_sqlite3_realloc"] = wasmExports["sqlite3_realloc"])(a0, a1);
    var _sqlite3_realloc64 = Module["_sqlite3_realloc64"] = (a0, a1) => (_sqlite3_realloc64 = Module["_sqlite3_realloc64"] = wasmExports["sqlite3_realloc64"])(a0, a1);
    var _sqlite3_value_text = Module["_sqlite3_value_text"] = (a0) => (_sqlite3_value_text = Module["_sqlite3_value_text"] = wasmExports["sqlite3_value_text"])(a0);
    var _sqlite3_randomness = Module["_sqlite3_randomness"] = (a0, a1) => (_sqlite3_randomness = Module["_sqlite3_randomness"] = wasmExports["sqlite3_randomness"])(a0, a1);
    var _sqlite3_stricmp = Module["_sqlite3_stricmp"] = (a0, a1) => (_sqlite3_stricmp = Module["_sqlite3_stricmp"] = wasmExports["sqlite3_stricmp"])(a0, a1);
    var _sqlite3_strnicmp = Module["_sqlite3_strnicmp"] = (a0, a1, a22) => (_sqlite3_strnicmp = Module["_sqlite3_strnicmp"] = wasmExports["sqlite3_strnicmp"])(a0, a1, a22);
    var _sqlite3_uri_parameter = Module["_sqlite3_uri_parameter"] = (a0, a1) => (_sqlite3_uri_parameter = Module["_sqlite3_uri_parameter"] = wasmExports["sqlite3_uri_parameter"])(a0, a1);
    var _sqlite3_uri_boolean = Module["_sqlite3_uri_boolean"] = (a0, a1, a22) => (_sqlite3_uri_boolean = Module["_sqlite3_uri_boolean"] = wasmExports["sqlite3_uri_boolean"])(a0, a1, a22);
    var _sqlite3_serialize = Module["_sqlite3_serialize"] = (a0, a1, a22, a3) => (_sqlite3_serialize = Module["_sqlite3_serialize"] = wasmExports["sqlite3_serialize"])(a0, a1, a22, a3);
    var _sqlite3_prepare_v2 = Module["_sqlite3_prepare_v2"] = (a0, a1, a22, a3, a4) => (_sqlite3_prepare_v2 = Module["_sqlite3_prepare_v2"] = wasmExports["sqlite3_prepare_v2"])(a0, a1, a22, a3, a4);
    var _sqlite3_step = Module["_sqlite3_step"] = (a0) => (_sqlite3_step = Module["_sqlite3_step"] = wasmExports["sqlite3_step"])(
      a0
    );
    var _sqlite3_column_int64 = Module["_sqlite3_column_int64"] = (a0, a1) => (_sqlite3_column_int64 = Module["_sqlite3_column_int64"] = wasmExports["sqlite3_column_int64"])(a0, a1);
    var _sqlite3_reset = Module["_sqlite3_reset"] = (a0) => (_sqlite3_reset = Module["_sqlite3_reset"] = wasmExports["sqlite3_reset"])(a0);
    var _sqlite3_exec = Module["_sqlite3_exec"] = (a0, a1, a22, a3, a4) => (_sqlite3_exec = Module["_sqlite3_exec"] = wasmExports["sqlite3_exec"])(
      a0,
      a1,
      a22,
      a3,
      a4
    );
    var _sqlite3_column_int = Module["_sqlite3_column_int"] = (a0, a1) => (_sqlite3_column_int = Module["_sqlite3_column_int"] = wasmExports["sqlite3_column_int"])(a0, a1);
    var _sqlite3_finalize = Module["_sqlite3_finalize"] = (a0) => (_sqlite3_finalize = Module["_sqlite3_finalize"] = wasmExports["sqlite3_finalize"])(a0);
    var _sqlite3_file_control = Module["_sqlite3_file_control"] = (a0, a1, a22, a3) => (_sqlite3_file_control = Module["_sqlite3_file_control"] = wasmExports["sqlite3_file_control"])(a0, a1, a22, a3);
    var _sqlite3_column_name = Module["_sqlite3_column_name"] = (a0, a1) => (_sqlite3_column_name = Module["_sqlite3_column_name"] = wasmExports["sqlite3_column_name"])(a0, a1);
    var _sqlite3_column_text = Module["_sqlite3_column_text"] = (a0, a1) => (_sqlite3_column_text = Module["_sqlite3_column_text"] = wasmExports["sqlite3_column_text"])(a0, a1);
    var _sqlite3_column_type = Module["_sqlite3_column_type"] = (a0, a1) => (_sqlite3_column_type = Module["_sqlite3_column_type"] = wasmExports["sqlite3_column_type"])(a0, a1);
    var _sqlite3_errmsg = Module["_sqlite3_errmsg"] = (a0) => (_sqlite3_errmsg = Module["_sqlite3_errmsg"] = wasmExports["sqlite3_errmsg"])(a0);
    var _sqlite3_deserialize = Module["_sqlite3_deserialize"] = (a0, a1, a22, a3, a4, a5) => (_sqlite3_deserialize = Module["_sqlite3_deserialize"] = wasmExports["sqlite3_deserialize"])(a0, a1, a22, a3, a4, a5);
    var _sqlite3_clear_bindings = Module["_sqlite3_clear_bindings"] = (a0) => (_sqlite3_clear_bindings = Module["_sqlite3_clear_bindings"] = wasmExports["sqlite3_clear_bindings"])(a0);
    var _sqlite3_value_blob = Module["_sqlite3_value_blob"] = (a0) => (_sqlite3_value_blob = Module["_sqlite3_value_blob"] = wasmExports["sqlite3_value_blob"])(a0);
    var _sqlite3_value_bytes = Module["_sqlite3_value_bytes"] = (a0) => (_sqlite3_value_bytes = Module["_sqlite3_value_bytes"] = wasmExports["sqlite3_value_bytes"])(a0);
    var _sqlite3_value_double = Module["_sqlite3_value_double"] = (a0) => (_sqlite3_value_double = Module["_sqlite3_value_double"] = wasmExports["sqlite3_value_double"])(a0);
    var _sqlite3_value_int = Module["_sqlite3_value_int"] = (a0) => (_sqlite3_value_int = Module["_sqlite3_value_int"] = wasmExports["sqlite3_value_int"])(a0);
    var _sqlite3_value_int64 = Module["_sqlite3_value_int64"] = (a0) => (_sqlite3_value_int64 = Module["_sqlite3_value_int64"] = wasmExports["sqlite3_value_int64"])(a0);
    var _sqlite3_value_subtype = Module["_sqlite3_value_subtype"] = (a0) => (_sqlite3_value_subtype = Module["_sqlite3_value_subtype"] = wasmExports["sqlite3_value_subtype"])(a0);
    var _sqlite3_value_pointer = Module["_sqlite3_value_pointer"] = (a0, a1) => (_sqlite3_value_pointer = Module["_sqlite3_value_pointer"] = wasmExports["sqlite3_value_pointer"])(a0, a1);
    var _sqlite3_value_type = Module["_sqlite3_value_type"] = (a0) => (_sqlite3_value_type = Module["_sqlite3_value_type"] = wasmExports["sqlite3_value_type"])(a0);
    var _sqlite3_value_nochange = Module["_sqlite3_value_nochange"] = (a0) => (_sqlite3_value_nochange = Module["_sqlite3_value_nochange"] = wasmExports["sqlite3_value_nochange"])(a0);
    var _sqlite3_value_frombind = Module["_sqlite3_value_frombind"] = (a0) => (_sqlite3_value_frombind = Module["_sqlite3_value_frombind"] = wasmExports["sqlite3_value_frombind"])(a0);
    var _sqlite3_value_dup = Module["_sqlite3_value_dup"] = (a0) => (_sqlite3_value_dup = Module["_sqlite3_value_dup"] = wasmExports["sqlite3_value_dup"])(a0);
    var _sqlite3_value_free = Module["_sqlite3_value_free"] = (a0) => (_sqlite3_value_free = Module["_sqlite3_value_free"] = wasmExports["sqlite3_value_free"])(a0);
    var _sqlite3_result_blob = Module["_sqlite3_result_blob"] = (a0, a1, a22, a3) => (_sqlite3_result_blob = Module["_sqlite3_result_blob"] = wasmExports["sqlite3_result_blob"])(a0, a1, a22, a3);
    var _sqlite3_result_error_toobig = Module["_sqlite3_result_error_toobig"] = (a0) => (_sqlite3_result_error_toobig = Module["_sqlite3_result_error_toobig"] = wasmExports["sqlite3_result_error_toobig"])(a0);
    var _sqlite3_result_error_nomem = Module["_sqlite3_result_error_nomem"] = (a0) => (_sqlite3_result_error_nomem = Module["_sqlite3_result_error_nomem"] = wasmExports["sqlite3_result_error_nomem"])(a0);
    var _sqlite3_result_double = Module["_sqlite3_result_double"] = (a0, a1) => (_sqlite3_result_double = Module["_sqlite3_result_double"] = wasmExports["sqlite3_result_double"])(a0, a1);
    var _sqlite3_result_error = Module["_sqlite3_result_error"] = (a0, a1, a22) => (_sqlite3_result_error = Module["_sqlite3_result_error"] = wasmExports["sqlite3_result_error"])(a0, a1, a22);
    var _sqlite3_result_int = Module["_sqlite3_result_int"] = (a0, a1) => (_sqlite3_result_int = Module["_sqlite3_result_int"] = wasmExports["sqlite3_result_int"])(a0, a1);
    var _sqlite3_result_int64 = Module["_sqlite3_result_int64"] = (a0, a1) => (_sqlite3_result_int64 = Module["_sqlite3_result_int64"] = wasmExports["sqlite3_result_int64"])(a0, a1);
    var _sqlite3_result_null = Module["_sqlite3_result_null"] = (a0) => (_sqlite3_result_null = Module["_sqlite3_result_null"] = wasmExports["sqlite3_result_null"])(a0);
    var _sqlite3_result_pointer = Module["_sqlite3_result_pointer"] = (a0, a1, a22, a3) => (_sqlite3_result_pointer = Module["_sqlite3_result_pointer"] = wasmExports["sqlite3_result_pointer"])(a0, a1, a22, a3);
    var _sqlite3_result_subtype = Module["_sqlite3_result_subtype"] = (a0, a1) => (_sqlite3_result_subtype = Module["_sqlite3_result_subtype"] = wasmExports["sqlite3_result_subtype"])(a0, a1);
    var _sqlite3_result_text = Module["_sqlite3_result_text"] = (a0, a1, a22, a3) => (_sqlite3_result_text = Module["_sqlite3_result_text"] = wasmExports["sqlite3_result_text"])(a0, a1, a22, a3);
    var _sqlite3_result_zeroblob = Module["_sqlite3_result_zeroblob"] = (a0, a1) => (_sqlite3_result_zeroblob = Module["_sqlite3_result_zeroblob"] = wasmExports["sqlite3_result_zeroblob"])(a0, a1);
    var _sqlite3_result_zeroblob64 = Module["_sqlite3_result_zeroblob64"] = (a0, a1) => (_sqlite3_result_zeroblob64 = Module["_sqlite3_result_zeroblob64"] = wasmExports["sqlite3_result_zeroblob64"])(a0, a1);
    var _sqlite3_result_error_code = Module["_sqlite3_result_error_code"] = (a0, a1) => (_sqlite3_result_error_code = Module["_sqlite3_result_error_code"] = wasmExports["sqlite3_result_error_code"])(a0, a1);
    var _sqlite3_user_data = Module["_sqlite3_user_data"] = (a0) => (_sqlite3_user_data = Module["_sqlite3_user_data"] = wasmExports["sqlite3_user_data"])(a0);
    var _sqlite3_context_db_handle = Module["_sqlite3_context_db_handle"] = (a0) => (_sqlite3_context_db_handle = Module["_sqlite3_context_db_handle"] = wasmExports["sqlite3_context_db_handle"])(a0);
    var _sqlite3_vtab_nochange = Module["_sqlite3_vtab_nochange"] = (a0) => (_sqlite3_vtab_nochange = Module["_sqlite3_vtab_nochange"] = wasmExports["sqlite3_vtab_nochange"])(a0);
    var _sqlite3_vtab_in_first = Module["_sqlite3_vtab_in_first"] = (a0, a1) => (_sqlite3_vtab_in_first = Module["_sqlite3_vtab_in_first"] = wasmExports["sqlite3_vtab_in_first"])(a0, a1);
    var _sqlite3_vtab_in_next = Module["_sqlite3_vtab_in_next"] = (a0, a1) => (_sqlite3_vtab_in_next = Module["_sqlite3_vtab_in_next"] = wasmExports["sqlite3_vtab_in_next"])(a0, a1);
    var _sqlite3_aggregate_context = Module["_sqlite3_aggregate_context"] = (a0, a1) => (_sqlite3_aggregate_context = Module["_sqlite3_aggregate_context"] = wasmExports["sqlite3_aggregate_context"])(a0, a1);
    var _sqlite3_get_auxdata = Module["_sqlite3_get_auxdata"] = (a0, a1) => (_sqlite3_get_auxdata = Module["_sqlite3_get_auxdata"] = wasmExports["sqlite3_get_auxdata"])(a0, a1);
    var _sqlite3_set_auxdata = Module["_sqlite3_set_auxdata"] = (a0, a1, a22, a3) => (_sqlite3_set_auxdata = Module["_sqlite3_set_auxdata"] = wasmExports["sqlite3_set_auxdata"])(a0, a1, a22, a3);
    var _sqlite3_column_count = Module["_sqlite3_column_count"] = (a0) => (_sqlite3_column_count = Module["_sqlite3_column_count"] = wasmExports["sqlite3_column_count"])(a0);
    var _sqlite3_data_count = Module["_sqlite3_data_count"] = (a0) => (_sqlite3_data_count = Module["_sqlite3_data_count"] = wasmExports["sqlite3_data_count"])(a0);
    var _sqlite3_column_blob = Module["_sqlite3_column_blob"] = (a0, a1) => (_sqlite3_column_blob = Module["_sqlite3_column_blob"] = wasmExports["sqlite3_column_blob"])(a0, a1);
    var _sqlite3_column_bytes = Module["_sqlite3_column_bytes"] = (a0, a1) => (_sqlite3_column_bytes = Module["_sqlite3_column_bytes"] = wasmExports["sqlite3_column_bytes"])(a0, a1);
    var _sqlite3_column_double = Module["_sqlite3_column_double"] = (a0, a1) => (_sqlite3_column_double = Module["_sqlite3_column_double"] = wasmExports["sqlite3_column_double"])(a0, a1);
    var _sqlite3_column_value = Module["_sqlite3_column_value"] = (a0, a1) => (_sqlite3_column_value = Module["_sqlite3_column_value"] = wasmExports["sqlite3_column_value"])(a0, a1);
    var _sqlite3_column_decltype = Module["_sqlite3_column_decltype"] = (a0, a1) => (_sqlite3_column_decltype = Module["_sqlite3_column_decltype"] = wasmExports["sqlite3_column_decltype"])(a0, a1);
    var _sqlite3_bind_blob = Module["_sqlite3_bind_blob"] = (a0, a1, a22, a3, a4) => (_sqlite3_bind_blob = Module["_sqlite3_bind_blob"] = wasmExports["sqlite3_bind_blob"])(a0, a1, a22, a3, a4);
    var _sqlite3_bind_double = Module["_sqlite3_bind_double"] = (a0, a1, a22) => (_sqlite3_bind_double = Module["_sqlite3_bind_double"] = wasmExports["sqlite3_bind_double"])(a0, a1, a22);
    var _sqlite3_bind_int = Module["_sqlite3_bind_int"] = (a0, a1, a22) => (_sqlite3_bind_int = Module["_sqlite3_bind_int"] = wasmExports["sqlite3_bind_int"])(a0, a1, a22);
    var _sqlite3_bind_int64 = Module["_sqlite3_bind_int64"] = (a0, a1, a22) => (_sqlite3_bind_int64 = Module["_sqlite3_bind_int64"] = wasmExports["sqlite3_bind_int64"])(a0, a1, a22);
    var _sqlite3_bind_null = Module["_sqlite3_bind_null"] = (a0, a1) => (_sqlite3_bind_null = Module["_sqlite3_bind_null"] = wasmExports["sqlite3_bind_null"])(a0, a1);
    var _sqlite3_bind_pointer = Module["_sqlite3_bind_pointer"] = (a0, a1, a22, a3, a4) => (_sqlite3_bind_pointer = Module["_sqlite3_bind_pointer"] = wasmExports["sqlite3_bind_pointer"])(a0, a1, a22, a3, a4);
    var _sqlite3_bind_text = Module["_sqlite3_bind_text"] = (a0, a1, a22, a3, a4) => (_sqlite3_bind_text = Module["_sqlite3_bind_text"] = wasmExports["sqlite3_bind_text"])(a0, a1, a22, a3, a4);
    var _sqlite3_bind_parameter_count = Module["_sqlite3_bind_parameter_count"] = (a0) => (_sqlite3_bind_parameter_count = Module["_sqlite3_bind_parameter_count"] = wasmExports["sqlite3_bind_parameter_count"])(a0);
    var _sqlite3_bind_parameter_name = Module["_sqlite3_bind_parameter_name"] = (a0, a1) => (_sqlite3_bind_parameter_name = Module["_sqlite3_bind_parameter_name"] = wasmExports["sqlite3_bind_parameter_name"])(a0, a1);
    var _sqlite3_bind_parameter_index = Module["_sqlite3_bind_parameter_index"] = (a0, a1) => (_sqlite3_bind_parameter_index = Module["_sqlite3_bind_parameter_index"] = wasmExports["sqlite3_bind_parameter_index"])(a0, a1);
    var _sqlite3_db_handle = Module["_sqlite3_db_handle"] = (a0) => (_sqlite3_db_handle = Module["_sqlite3_db_handle"] = wasmExports["sqlite3_db_handle"])(a0);
    var _sqlite3_stmt_readonly = Module["_sqlite3_stmt_readonly"] = (a0) => (_sqlite3_stmt_readonly = Module["_sqlite3_stmt_readonly"] = wasmExports["sqlite3_stmt_readonly"])(a0);
    var _sqlite3_stmt_isexplain = Module["_sqlite3_stmt_isexplain"] = (a0) => (_sqlite3_stmt_isexplain = Module["_sqlite3_stmt_isexplain"] = wasmExports["sqlite3_stmt_isexplain"])(a0);
    var _sqlite3_stmt_explain = Module["_sqlite3_stmt_explain"] = (a0, a1) => (_sqlite3_stmt_explain = Module["_sqlite3_stmt_explain"] = wasmExports["sqlite3_stmt_explain"])(a0, a1);
    var _sqlite3_stmt_busy = Module["_sqlite3_stmt_busy"] = (a0) => (_sqlite3_stmt_busy = Module["_sqlite3_stmt_busy"] = wasmExports["sqlite3_stmt_busy"])(a0);
    var _sqlite3_stmt_status = Module["_sqlite3_stmt_status"] = (a0, a1, a22) => (_sqlite3_stmt_status = Module["_sqlite3_stmt_status"] = wasmExports["sqlite3_stmt_status"])(a0, a1, a22);
    var _sqlite3_sql = Module["_sqlite3_sql"] = (a0) => (_sqlite3_sql = Module["_sqlite3_sql"] = wasmExports["sqlite3_sql"])(a0);
    var _sqlite3_expanded_sql = Module["_sqlite3_expanded_sql"] = (a0) => (_sqlite3_expanded_sql = Module["_sqlite3_expanded_sql"] = wasmExports["sqlite3_expanded_sql"])(a0);
    var _sqlite3_preupdate_old = Module["_sqlite3_preupdate_old"] = (a0, a1, a22) => (_sqlite3_preupdate_old = Module["_sqlite3_preupdate_old"] = wasmExports["sqlite3_preupdate_old"])(a0, a1, a22);
    var _sqlite3_preupdate_count = Module["_sqlite3_preupdate_count"] = (a0) => (_sqlite3_preupdate_count = Module["_sqlite3_preupdate_count"] = wasmExports["sqlite3_preupdate_count"])(a0);
    var _sqlite3_preupdate_depth = Module["_sqlite3_preupdate_depth"] = (a0) => (_sqlite3_preupdate_depth = Module["_sqlite3_preupdate_depth"] = wasmExports["sqlite3_preupdate_depth"])(a0);
    var _sqlite3_preupdate_blobwrite = Module["_sqlite3_preupdate_blobwrite"] = (a0) => (_sqlite3_preupdate_blobwrite = Module["_sqlite3_preupdate_blobwrite"] = wasmExports["sqlite3_preupdate_blobwrite"])(a0);
    var _sqlite3_preupdate_new = Module["_sqlite3_preupdate_new"] = (a0, a1, a22) => (_sqlite3_preupdate_new = Module["_sqlite3_preupdate_new"] = wasmExports["sqlite3_preupdate_new"])(a0, a1, a22);
    var _sqlite3_value_numeric_type = Module["_sqlite3_value_numeric_type"] = (a0) => (_sqlite3_value_numeric_type = Module["_sqlite3_value_numeric_type"] = wasmExports["sqlite3_value_numeric_type"])(a0);
    var _sqlite3_set_authorizer = Module["_sqlite3_set_authorizer"] = (a0, a1, a22) => (_sqlite3_set_authorizer = Module["_sqlite3_set_authorizer"] = wasmExports["sqlite3_set_authorizer"])(a0, a1, a22);
    var _sqlite3_strglob = Module["_sqlite3_strglob"] = (a0, a1) => (_sqlite3_strglob = Module["_sqlite3_strglob"] = wasmExports["sqlite3_strglob"])(a0, a1);
    var _sqlite3_strlike = Module["_sqlite3_strlike"] = (a0, a1, a22) => (_sqlite3_strlike = Module["_sqlite3_strlike"] = wasmExports["sqlite3_strlike"])(a0, a1, a22);
    var _sqlite3_auto_extension = Module["_sqlite3_auto_extension"] = (a0) => (_sqlite3_auto_extension = Module["_sqlite3_auto_extension"] = wasmExports["sqlite3_auto_extension"])(a0);
    var _sqlite3_cancel_auto_extension = Module["_sqlite3_cancel_auto_extension"] = (a0) => (_sqlite3_cancel_auto_extension = Module["_sqlite3_cancel_auto_extension"] = wasmExports["sqlite3_cancel_auto_extension"])(a0);
    var _sqlite3_reset_auto_extension = Module["_sqlite3_reset_auto_extension"] = () => (_sqlite3_reset_auto_extension = Module["_sqlite3_reset_auto_extension"] = wasmExports["sqlite3_reset_auto_extension"])();
    var _sqlite3_prepare_v3 = Module["_sqlite3_prepare_v3"] = (a0, a1, a22, a3, a4, a5) => (_sqlite3_prepare_v3 = Module["_sqlite3_prepare_v3"] = wasmExports["sqlite3_prepare_v3"])(a0, a1, a22, a3, a4, a5);
    var _sqlite3_create_module = Module["_sqlite3_create_module"] = (a0, a1, a22, a3) => (_sqlite3_create_module = Module["_sqlite3_create_module"] = wasmExports["sqlite3_create_module"])(a0, a1, a22, a3);
    var _sqlite3_create_module_v2 = Module["_sqlite3_create_module_v2"] = (a0, a1, a22, a3, a4) => (_sqlite3_create_module_v2 = Module["_sqlite3_create_module_v2"] = wasmExports["sqlite3_create_module_v2"])(a0, a1, a22, a3, a4);
    var _sqlite3_drop_modules = Module["_sqlite3_drop_modules"] = (a0, a1) => (_sqlite3_drop_modules = Module["_sqlite3_drop_modules"] = wasmExports["sqlite3_drop_modules"])(a0, a1);
    var _sqlite3_declare_vtab = Module["_sqlite3_declare_vtab"] = (a0, a1) => (_sqlite3_declare_vtab = Module["_sqlite3_declare_vtab"] = wasmExports["sqlite3_declare_vtab"])(a0, a1);
    var _sqlite3_vtab_on_conflict = Module["_sqlite3_vtab_on_conflict"] = (a0) => (_sqlite3_vtab_on_conflict = Module["_sqlite3_vtab_on_conflict"] = wasmExports["sqlite3_vtab_on_conflict"])(a0);
    var _sqlite3_vtab_collation = Module["_sqlite3_vtab_collation"] = (a0, a1) => (_sqlite3_vtab_collation = Module["_sqlite3_vtab_collation"] = wasmExports["sqlite3_vtab_collation"])(a0, a1);
    var _sqlite3_vtab_in = Module["_sqlite3_vtab_in"] = (a0, a1, a22) => (_sqlite3_vtab_in = Module["_sqlite3_vtab_in"] = wasmExports["sqlite3_vtab_in"])(a0, a1, a22);
    var _sqlite3_vtab_rhs_value = Module["_sqlite3_vtab_rhs_value"] = (a0, a1, a22) => (_sqlite3_vtab_rhs_value = Module["_sqlite3_vtab_rhs_value"] = wasmExports["sqlite3_vtab_rhs_value"])(a0, a1, a22);
    var _sqlite3_vtab_distinct = Module["_sqlite3_vtab_distinct"] = (a0) => (_sqlite3_vtab_distinct = Module["_sqlite3_vtab_distinct"] = wasmExports["sqlite3_vtab_distinct"])(a0);
    var _sqlite3_keyword_name = Module["_sqlite3_keyword_name"] = (a0, a1, a22) => (_sqlite3_keyword_name = Module["_sqlite3_keyword_name"] = wasmExports["sqlite3_keyword_name"])(a0, a1, a22);
    var _sqlite3_keyword_count = Module["_sqlite3_keyword_count"] = () => (_sqlite3_keyword_count = Module["_sqlite3_keyword_count"] = wasmExports["sqlite3_keyword_count"])();
    var _sqlite3_keyword_check = Module["_sqlite3_keyword_check"] = (a0, a1) => (_sqlite3_keyword_check = Module["_sqlite3_keyword_check"] = wasmExports["sqlite3_keyword_check"])(a0, a1);
    var _sqlite3_complete = Module["_sqlite3_complete"] = (a0) => (_sqlite3_complete = Module["_sqlite3_complete"] = wasmExports["sqlite3_complete"])(a0);
    var _sqlite3_libversion = Module["_sqlite3_libversion"] = () => (_sqlite3_libversion = Module["_sqlite3_libversion"] = wasmExports["sqlite3_libversion"])();
    var _sqlite3_libversion_number = Module["_sqlite3_libversion_number"] = () => (_sqlite3_libversion_number = Module["_sqlite3_libversion_number"] = wasmExports["sqlite3_libversion_number"])();
    var _sqlite3_shutdown = Module["_sqlite3_shutdown"] = () => (_sqlite3_shutdown = Module["_sqlite3_shutdown"] = wasmExports["sqlite3_shutdown"])();
    var _sqlite3_last_insert_rowid = Module["_sqlite3_last_insert_rowid"] = (a0) => (_sqlite3_last_insert_rowid = Module["_sqlite3_last_insert_rowid"] = wasmExports["sqlite3_last_insert_rowid"])(a0);
    var _sqlite3_set_last_insert_rowid = Module["_sqlite3_set_last_insert_rowid"] = (a0, a1) => (_sqlite3_set_last_insert_rowid = Module["_sqlite3_set_last_insert_rowid"] = wasmExports["sqlite3_set_last_insert_rowid"])(a0, a1);
    var _sqlite3_changes64 = Module["_sqlite3_changes64"] = (a0) => (_sqlite3_changes64 = Module["_sqlite3_changes64"] = wasmExports["sqlite3_changes64"])(a0);
    var _sqlite3_changes = Module["_sqlite3_changes"] = (a0) => (_sqlite3_changes = Module["_sqlite3_changes"] = wasmExports["sqlite3_changes"])(a0);
    var _sqlite3_total_changes64 = Module["_sqlite3_total_changes64"] = (a0) => (_sqlite3_total_changes64 = Module["_sqlite3_total_changes64"] = wasmExports["sqlite3_total_changes64"])(a0);
    var _sqlite3_total_changes = Module["_sqlite3_total_changes"] = (a0) => (_sqlite3_total_changes = Module["_sqlite3_total_changes"] = wasmExports["sqlite3_total_changes"])(a0);
    var _sqlite3_txn_state = Module["_sqlite3_txn_state"] = (a0, a1) => (_sqlite3_txn_state = Module["_sqlite3_txn_state"] = wasmExports["sqlite3_txn_state"])(a0, a1);
    var _sqlite3_close_v2 = Module["_sqlite3_close_v2"] = (a0) => (_sqlite3_close_v2 = Module["_sqlite3_close_v2"] = wasmExports["sqlite3_close_v2"])(a0);
    var _sqlite3_busy_handler = Module["_sqlite3_busy_handler"] = (a0, a1, a22) => (_sqlite3_busy_handler = Module["_sqlite3_busy_handler"] = wasmExports["sqlite3_busy_handler"])(a0, a1, a22);
    var _sqlite3_progress_handler = Module["_sqlite3_progress_handler"] = (a0, a1, a22, a3) => (_sqlite3_progress_handler = Module["_sqlite3_progress_handler"] = wasmExports["sqlite3_progress_handler"])(a0, a1, a22, a3);
    var _sqlite3_busy_timeout = Module["_sqlite3_busy_timeout"] = (a0, a1) => (_sqlite3_busy_timeout = Module["_sqlite3_busy_timeout"] = wasmExports["sqlite3_busy_timeout"])(a0, a1);
    var _sqlite3_interrupt = Module["_sqlite3_interrupt"] = (a0) => (_sqlite3_interrupt = Module["_sqlite3_interrupt"] = wasmExports["sqlite3_interrupt"])(a0);
    var _sqlite3_is_interrupted = Module["_sqlite3_is_interrupted"] = (a0) => (_sqlite3_is_interrupted = Module["_sqlite3_is_interrupted"] = wasmExports["sqlite3_is_interrupted"])(a0);
    var _sqlite3_create_function = Module["_sqlite3_create_function"] = (a0, a1, a22, a3, a4, a5, a6, a7) => (_sqlite3_create_function = Module["_sqlite3_create_function"] = wasmExports["sqlite3_create_function"])(
      a0,
      a1,
      a22,
      a3,
      a4,
      a5,
      a6,
      a7
    );
    var _sqlite3_create_function_v2 = Module["_sqlite3_create_function_v2"] = (a0, a1, a22, a3, a4, a5, a6, a7, a8) => (_sqlite3_create_function_v2 = Module["_sqlite3_create_function_v2"] = wasmExports["sqlite3_create_function_v2"])(
      a0,
      a1,
      a22,
      a3,
      a4,
      a5,
      a6,
      a7,
      a8
    );
    var _sqlite3_create_window_function = Module["_sqlite3_create_window_function"] = (a0, a1, a22, a3, a4, a5, a6, a7, a8, a9) => (_sqlite3_create_window_function = Module["_sqlite3_create_window_function"] = wasmExports["sqlite3_create_window_function"])(
      a0,
      a1,
      a22,
      a3,
      a4,
      a5,
      a6,
      a7,
      a8,
      a9
    );
    var _sqlite3_overload_function = Module["_sqlite3_overload_function"] = (a0, a1, a22) => (_sqlite3_overload_function = Module["_sqlite3_overload_function"] = wasmExports["sqlite3_overload_function"])(a0, a1, a22);
    var _sqlite3_trace_v2 = Module["_sqlite3_trace_v2"] = (a0, a1, a22, a3) => (_sqlite3_trace_v2 = Module["_sqlite3_trace_v2"] = wasmExports["sqlite3_trace_v2"])(a0, a1, a22, a3);
    var _sqlite3_commit_hook = Module["_sqlite3_commit_hook"] = (a0, a1, a22) => (_sqlite3_commit_hook = Module["_sqlite3_commit_hook"] = wasmExports["sqlite3_commit_hook"])(a0, a1, a22);
    var _sqlite3_update_hook = Module["_sqlite3_update_hook"] = (a0, a1, a22) => (_sqlite3_update_hook = Module["_sqlite3_update_hook"] = wasmExports["sqlite3_update_hook"])(a0, a1, a22);
    var _sqlite3_rollback_hook = Module["_sqlite3_rollback_hook"] = (a0, a1, a22) => (_sqlite3_rollback_hook = Module["_sqlite3_rollback_hook"] = wasmExports["sqlite3_rollback_hook"])(a0, a1, a22);
    var _sqlite3_preupdate_hook = Module["_sqlite3_preupdate_hook"] = (a0, a1, a22) => (_sqlite3_preupdate_hook = Module["_sqlite3_preupdate_hook"] = wasmExports["sqlite3_preupdate_hook"])(a0, a1, a22);
    var _sqlite3_error_offset = Module["_sqlite3_error_offset"] = (a0) => (_sqlite3_error_offset = Module["_sqlite3_error_offset"] = wasmExports["sqlite3_error_offset"])(a0);
    var _sqlite3_errcode = Module["_sqlite3_errcode"] = (a0) => (_sqlite3_errcode = Module["_sqlite3_errcode"] = wasmExports["sqlite3_errcode"])(a0);
    var _sqlite3_extended_errcode = Module["_sqlite3_extended_errcode"] = (a0) => (_sqlite3_extended_errcode = Module["_sqlite3_extended_errcode"] = wasmExports["sqlite3_extended_errcode"])(a0);
    var _sqlite3_errstr = Module["_sqlite3_errstr"] = (a0) => (_sqlite3_errstr = Module["_sqlite3_errstr"] = wasmExports["sqlite3_errstr"])(a0);
    var _sqlite3_limit = Module["_sqlite3_limit"] = (a0, a1, a22) => (_sqlite3_limit = Module["_sqlite3_limit"] = wasmExports["sqlite3_limit"])(a0, a1, a22);
    var _sqlite3_open = Module["_sqlite3_open"] = (a0, a1) => (_sqlite3_open = Module["_sqlite3_open"] = wasmExports["sqlite3_open"])(
      a0,
      a1
    );
    var _sqlite3_open_v2 = Module["_sqlite3_open_v2"] = (a0, a1, a22, a3) => (_sqlite3_open_v2 = Module["_sqlite3_open_v2"] = wasmExports["sqlite3_open_v2"])(a0, a1, a22, a3);
    var _sqlite3_create_collation = Module["_sqlite3_create_collation"] = (a0, a1, a22, a3, a4) => (_sqlite3_create_collation = Module["_sqlite3_create_collation"] = wasmExports["sqlite3_create_collation"])(a0, a1, a22, a3, a4);
    var _sqlite3_create_collation_v2 = Module["_sqlite3_create_collation_v2"] = (a0, a1, a22, a3, a4, a5) => (_sqlite3_create_collation_v2 = Module["_sqlite3_create_collation_v2"] = wasmExports["sqlite3_create_collation_v2"])(a0, a1, a22, a3, a4, a5);
    var _sqlite3_collation_needed = Module["_sqlite3_collation_needed"] = (a0, a1, a22) => (_sqlite3_collation_needed = Module["_sqlite3_collation_needed"] = wasmExports["sqlite3_collation_needed"])(a0, a1, a22);
    var _sqlite3_get_autocommit = Module["_sqlite3_get_autocommit"] = (a0) => (_sqlite3_get_autocommit = Module["_sqlite3_get_autocommit"] = wasmExports["sqlite3_get_autocommit"])(a0);
    var _sqlite3_table_column_metadata = Module["_sqlite3_table_column_metadata"] = (a0, a1, a22, a3, a4, a5, a6, a7, a8) => (_sqlite3_table_column_metadata = Module["_sqlite3_table_column_metadata"] = wasmExports["sqlite3_table_column_metadata"])(
      a0,
      a1,
      a22,
      a3,
      a4,
      a5,
      a6,
      a7,
      a8
    );
    var _sqlite3_extended_result_codes = Module["_sqlite3_extended_result_codes"] = (a0, a1) => (_sqlite3_extended_result_codes = Module["_sqlite3_extended_result_codes"] = wasmExports["sqlite3_extended_result_codes"])(a0, a1);
    var _sqlite3_uri_key = Module["_sqlite3_uri_key"] = (a0, a1) => (_sqlite3_uri_key = Module["_sqlite3_uri_key"] = wasmExports["sqlite3_uri_key"])(a0, a1);
    var _sqlite3_uri_int64 = Module["_sqlite3_uri_int64"] = (a0, a1, a22) => (_sqlite3_uri_int64 = Module["_sqlite3_uri_int64"] = wasmExports["sqlite3_uri_int64"])(a0, a1, a22);
    var _sqlite3_db_name = Module["_sqlite3_db_name"] = (a0, a1) => (_sqlite3_db_name = Module["_sqlite3_db_name"] = wasmExports["sqlite3_db_name"])(a0, a1);
    var _sqlite3_db_filename = Module["_sqlite3_db_filename"] = (a0, a1) => (_sqlite3_db_filename = Module["_sqlite3_db_filename"] = wasmExports["sqlite3_db_filename"])(a0, a1);
    var _sqlite3_db_readonly = Module["_sqlite3_db_readonly"] = (a0, a1) => (_sqlite3_db_readonly = Module["_sqlite3_db_readonly"] = wasmExports["sqlite3_db_readonly"])(a0, a1);
    var _sqlite3_compileoption_used = Module["_sqlite3_compileoption_used"] = (a0) => (_sqlite3_compileoption_used = Module["_sqlite3_compileoption_used"] = wasmExports["sqlite3_compileoption_used"])(a0);
    var _sqlite3_compileoption_get = Module["_sqlite3_compileoption_get"] = (a0) => (_sqlite3_compileoption_get = Module["_sqlite3_compileoption_get"] = wasmExports["sqlite3_compileoption_get"])(a0);
    var _sqlite3session_diff = Module["_sqlite3session_diff"] = (a0, a1, a22, a3) => (_sqlite3session_diff = Module["_sqlite3session_diff"] = wasmExports["sqlite3session_diff"])(a0, a1, a22, a3);
    var _sqlite3session_attach = Module["_sqlite3session_attach"] = (a0, a1) => (_sqlite3session_attach = Module["_sqlite3session_attach"] = wasmExports["sqlite3session_attach"])(a0, a1);
    var _sqlite3session_create = Module["_sqlite3session_create"] = (a0, a1, a22) => (_sqlite3session_create = Module["_sqlite3session_create"] = wasmExports["sqlite3session_create"])(a0, a1, a22);
    var _sqlite3session_delete = Module["_sqlite3session_delete"] = (a0) => (_sqlite3session_delete = Module["_sqlite3session_delete"] = wasmExports["sqlite3session_delete"])(a0);
    var _sqlite3session_table_filter = Module["_sqlite3session_table_filter"] = (a0, a1, a22) => (_sqlite3session_table_filter = Module["_sqlite3session_table_filter"] = wasmExports["sqlite3session_table_filter"])(a0, a1, a22);
    var _sqlite3session_changeset = Module["_sqlite3session_changeset"] = (a0, a1, a22) => (_sqlite3session_changeset = Module["_sqlite3session_changeset"] = wasmExports["sqlite3session_changeset"])(a0, a1, a22);
    var _sqlite3session_changeset_strm = Module["_sqlite3session_changeset_strm"] = (a0, a1, a22) => (_sqlite3session_changeset_strm = Module["_sqlite3session_changeset_strm"] = wasmExports["sqlite3session_changeset_strm"])(a0, a1, a22);
    var _sqlite3session_patchset_strm = Module["_sqlite3session_patchset_strm"] = (a0, a1, a22) => (_sqlite3session_patchset_strm = Module["_sqlite3session_patchset_strm"] = wasmExports["sqlite3session_patchset_strm"])(a0, a1, a22);
    var _sqlite3session_patchset = Module["_sqlite3session_patchset"] = (a0, a1, a22) => (_sqlite3session_patchset = Module["_sqlite3session_patchset"] = wasmExports["sqlite3session_patchset"])(a0, a1, a22);
    var _sqlite3session_enable = Module["_sqlite3session_enable"] = (a0, a1) => (_sqlite3session_enable = Module["_sqlite3session_enable"] = wasmExports["sqlite3session_enable"])(a0, a1);
    var _sqlite3session_indirect = Module["_sqlite3session_indirect"] = (a0, a1) => (_sqlite3session_indirect = Module["_sqlite3session_indirect"] = wasmExports["sqlite3session_indirect"])(a0, a1);
    var _sqlite3session_isempty = Module["_sqlite3session_isempty"] = (a0) => (_sqlite3session_isempty = Module["_sqlite3session_isempty"] = wasmExports["sqlite3session_isempty"])(a0);
    var _sqlite3session_memory_used = Module["_sqlite3session_memory_used"] = (a0) => (_sqlite3session_memory_used = Module["_sqlite3session_memory_used"] = wasmExports["sqlite3session_memory_used"])(a0);
    var _sqlite3session_object_config = Module["_sqlite3session_object_config"] = (a0, a1, a22) => (_sqlite3session_object_config = Module["_sqlite3session_object_config"] = wasmExports["sqlite3session_object_config"])(a0, a1, a22);
    var _sqlite3session_changeset_size = Module["_sqlite3session_changeset_size"] = (a0) => (_sqlite3session_changeset_size = Module["_sqlite3session_changeset_size"] = wasmExports["sqlite3session_changeset_size"])(a0);
    var _sqlite3changeset_start = Module["_sqlite3changeset_start"] = (a0, a1, a22) => (_sqlite3changeset_start = Module["_sqlite3changeset_start"] = wasmExports["sqlite3changeset_start"])(a0, a1, a22);
    var _sqlite3changeset_start_v2 = Module["_sqlite3changeset_start_v2"] = (a0, a1, a22, a3) => (_sqlite3changeset_start_v2 = Module["_sqlite3changeset_start_v2"] = wasmExports["sqlite3changeset_start_v2"])(a0, a1, a22, a3);
    var _sqlite3changeset_start_strm = Module["_sqlite3changeset_start_strm"] = (a0, a1, a22) => (_sqlite3changeset_start_strm = Module["_sqlite3changeset_start_strm"] = wasmExports["sqlite3changeset_start_strm"])(a0, a1, a22);
    var _sqlite3changeset_start_v2_strm = Module["_sqlite3changeset_start_v2_strm"] = (a0, a1, a22, a3) => (_sqlite3changeset_start_v2_strm = Module["_sqlite3changeset_start_v2_strm"] = wasmExports["sqlite3changeset_start_v2_strm"])(a0, a1, a22, a3);
    var _sqlite3changeset_next = Module["_sqlite3changeset_next"] = (a0) => (_sqlite3changeset_next = Module["_sqlite3changeset_next"] = wasmExports["sqlite3changeset_next"])(a0);
    var _sqlite3changeset_op = Module["_sqlite3changeset_op"] = (a0, a1, a22, a3, a4) => (_sqlite3changeset_op = Module["_sqlite3changeset_op"] = wasmExports["sqlite3changeset_op"])(a0, a1, a22, a3, a4);
    var _sqlite3changeset_pk = Module["_sqlite3changeset_pk"] = (a0, a1, a22) => (_sqlite3changeset_pk = Module["_sqlite3changeset_pk"] = wasmExports["sqlite3changeset_pk"])(a0, a1, a22);
    var _sqlite3changeset_old = Module["_sqlite3changeset_old"] = (a0, a1, a22) => (_sqlite3changeset_old = Module["_sqlite3changeset_old"] = wasmExports["sqlite3changeset_old"])(a0, a1, a22);
    var _sqlite3changeset_new = Module["_sqlite3changeset_new"] = (a0, a1, a22) => (_sqlite3changeset_new = Module["_sqlite3changeset_new"] = wasmExports["sqlite3changeset_new"])(a0, a1, a22);
    var _sqlite3changeset_conflict = Module["_sqlite3changeset_conflict"] = (a0, a1, a22) => (_sqlite3changeset_conflict = Module["_sqlite3changeset_conflict"] = wasmExports["sqlite3changeset_conflict"])(a0, a1, a22);
    var _sqlite3changeset_fk_conflicts = Module["_sqlite3changeset_fk_conflicts"] = (a0, a1) => (_sqlite3changeset_fk_conflicts = Module["_sqlite3changeset_fk_conflicts"] = wasmExports["sqlite3changeset_fk_conflicts"])(a0, a1);
    var _sqlite3changeset_finalize = Module["_sqlite3changeset_finalize"] = (a0) => (_sqlite3changeset_finalize = Module["_sqlite3changeset_finalize"] = wasmExports["sqlite3changeset_finalize"])(a0);
    var _sqlite3changeset_invert = Module["_sqlite3changeset_invert"] = (a0, a1, a22, a3) => (_sqlite3changeset_invert = Module["_sqlite3changeset_invert"] = wasmExports["sqlite3changeset_invert"])(a0, a1, a22, a3);
    var _sqlite3changeset_invert_strm = Module["_sqlite3changeset_invert_strm"] = (a0, a1, a22, a3) => (_sqlite3changeset_invert_strm = Module["_sqlite3changeset_invert_strm"] = wasmExports["sqlite3changeset_invert_strm"])(a0, a1, a22, a3);
    var _sqlite3changeset_apply_v2 = Module["_sqlite3changeset_apply_v2"] = (a0, a1, a22, a3, a4, a5, a6, a7, a8) => (_sqlite3changeset_apply_v2 = Module["_sqlite3changeset_apply_v2"] = wasmExports["sqlite3changeset_apply_v2"])(
      a0,
      a1,
      a22,
      a3,
      a4,
      a5,
      a6,
      a7,
      a8
    );
    var _sqlite3changeset_apply = Module["_sqlite3changeset_apply"] = (a0, a1, a22, a3, a4, a5) => (_sqlite3changeset_apply = Module["_sqlite3changeset_apply"] = wasmExports["sqlite3changeset_apply"])(a0, a1, a22, a3, a4, a5);
    var _sqlite3changeset_apply_v2_strm = Module["_sqlite3changeset_apply_v2_strm"] = (a0, a1, a22, a3, a4, a5, a6, a7, a8) => (_sqlite3changeset_apply_v2_strm = Module["_sqlite3changeset_apply_v2_strm"] = wasmExports["sqlite3changeset_apply_v2_strm"])(
      a0,
      a1,
      a22,
      a3,
      a4,
      a5,
      a6,
      a7,
      a8
    );
    var _sqlite3changeset_apply_strm = Module["_sqlite3changeset_apply_strm"] = (a0, a1, a22, a3, a4, a5) => (_sqlite3changeset_apply_strm = Module["_sqlite3changeset_apply_strm"] = wasmExports["sqlite3changeset_apply_strm"])(a0, a1, a22, a3, a4, a5);
    var _sqlite3changegroup_new = Module["_sqlite3changegroup_new"] = (a0) => (_sqlite3changegroup_new = Module["_sqlite3changegroup_new"] = wasmExports["sqlite3changegroup_new"])(a0);
    var _sqlite3changegroup_add = Module["_sqlite3changegroup_add"] = (a0, a1, a22) => (_sqlite3changegroup_add = Module["_sqlite3changegroup_add"] = wasmExports["sqlite3changegroup_add"])(a0, a1, a22);
    var _sqlite3changegroup_output = Module["_sqlite3changegroup_output"] = (a0, a1, a22) => (_sqlite3changegroup_output = Module["_sqlite3changegroup_output"] = wasmExports["sqlite3changegroup_output"])(a0, a1, a22);
    var _sqlite3changegroup_add_strm = Module["_sqlite3changegroup_add_strm"] = (a0, a1, a22) => (_sqlite3changegroup_add_strm = Module["_sqlite3changegroup_add_strm"] = wasmExports["sqlite3changegroup_add_strm"])(a0, a1, a22);
    var _sqlite3changegroup_output_strm = Module["_sqlite3changegroup_output_strm"] = (a0, a1, a22) => (_sqlite3changegroup_output_strm = Module["_sqlite3changegroup_output_strm"] = wasmExports["sqlite3changegroup_output_strm"])(a0, a1, a22);
    var _sqlite3changegroup_delete = Module["_sqlite3changegroup_delete"] = (a0) => (_sqlite3changegroup_delete = Module["_sqlite3changegroup_delete"] = wasmExports["sqlite3changegroup_delete"])(a0);
    var _sqlite3changeset_concat = Module["_sqlite3changeset_concat"] = (a0, a1, a22, a3, a4, a5) => (_sqlite3changeset_concat = Module["_sqlite3changeset_concat"] = wasmExports["sqlite3changeset_concat"])(a0, a1, a22, a3, a4, a5);
    var _sqlite3changeset_concat_strm = Module["_sqlite3changeset_concat_strm"] = (a0, a1, a22, a3, a4, a5) => (_sqlite3changeset_concat_strm = Module["_sqlite3changeset_concat_strm"] = wasmExports["sqlite3changeset_concat_strm"])(a0, a1, a22, a3, a4, a5);
    var _sqlite3session_config = Module["_sqlite3session_config"] = (a0, a1) => (_sqlite3session_config = Module["_sqlite3session_config"] = wasmExports["sqlite3session_config"])(a0, a1);
    var _sqlite3_sourceid = Module["_sqlite3_sourceid"] = () => (_sqlite3_sourceid = Module["_sqlite3_sourceid"] = wasmExports["sqlite3_sourceid"])();
    var _sqlite3__wasm_pstack_ptr = Module["_sqlite3__wasm_pstack_ptr"] = () => (_sqlite3__wasm_pstack_ptr = Module["_sqlite3__wasm_pstack_ptr"] = wasmExports["sqlite3__wasm_pstack_ptr"])();
    var _sqlite3__wasm_pstack_restore = Module["_sqlite3__wasm_pstack_restore"] = (a0) => (_sqlite3__wasm_pstack_restore = Module["_sqlite3__wasm_pstack_restore"] = wasmExports["sqlite3__wasm_pstack_restore"])(a0);
    var _sqlite3__wasm_pstack_alloc = Module["_sqlite3__wasm_pstack_alloc"] = (a0) => (_sqlite3__wasm_pstack_alloc = Module["_sqlite3__wasm_pstack_alloc"] = wasmExports["sqlite3__wasm_pstack_alloc"])(a0);
    var _sqlite3__wasm_pstack_remaining = Module["_sqlite3__wasm_pstack_remaining"] = () => (_sqlite3__wasm_pstack_remaining = Module["_sqlite3__wasm_pstack_remaining"] = wasmExports["sqlite3__wasm_pstack_remaining"])();
    var _sqlite3__wasm_pstack_quota = Module["_sqlite3__wasm_pstack_quota"] = () => (_sqlite3__wasm_pstack_quota = Module["_sqlite3__wasm_pstack_quota"] = wasmExports["sqlite3__wasm_pstack_quota"])();
    var _sqlite3__wasm_db_error = Module["_sqlite3__wasm_db_error"] = (a0, a1, a22) => (_sqlite3__wasm_db_error = Module["_sqlite3__wasm_db_error"] = wasmExports["sqlite3__wasm_db_error"])(a0, a1, a22);
    var _sqlite3__wasm_test_struct = Module["_sqlite3__wasm_test_struct"] = (a0) => (_sqlite3__wasm_test_struct = Module["_sqlite3__wasm_test_struct"] = wasmExports["sqlite3__wasm_test_struct"])(a0);
    var _sqlite3__wasm_enum_json = Module["_sqlite3__wasm_enum_json"] = () => (_sqlite3__wasm_enum_json = Module["_sqlite3__wasm_enum_json"] = wasmExports["sqlite3__wasm_enum_json"])();
    var _sqlite3__wasm_vfs_unlink = Module["_sqlite3__wasm_vfs_unlink"] = (a0, a1) => (_sqlite3__wasm_vfs_unlink = Module["_sqlite3__wasm_vfs_unlink"] = wasmExports["sqlite3__wasm_vfs_unlink"])(a0, a1);
    var _sqlite3__wasm_db_vfs = Module["_sqlite3__wasm_db_vfs"] = (a0, a1) => (_sqlite3__wasm_db_vfs = Module["_sqlite3__wasm_db_vfs"] = wasmExports["sqlite3__wasm_db_vfs"])(a0, a1);
    var _sqlite3__wasm_db_reset = Module["_sqlite3__wasm_db_reset"] = (a0) => (_sqlite3__wasm_db_reset = Module["_sqlite3__wasm_db_reset"] = wasmExports["sqlite3__wasm_db_reset"])(a0);
    var _sqlite3__wasm_db_export_chunked = Module["_sqlite3__wasm_db_export_chunked"] = (a0, a1) => (_sqlite3__wasm_db_export_chunked = Module["_sqlite3__wasm_db_export_chunked"] = wasmExports["sqlite3__wasm_db_export_chunked"])(a0, a1);
    var _sqlite3__wasm_db_serialize = Module["_sqlite3__wasm_db_serialize"] = (a0, a1, a22, a3, a4) => (_sqlite3__wasm_db_serialize = Module["_sqlite3__wasm_db_serialize"] = wasmExports["sqlite3__wasm_db_serialize"])(a0, a1, a22, a3, a4);
    var _sqlite3__wasm_vfs_create_file = Module["_sqlite3__wasm_vfs_create_file"] = (a0, a1, a22, a3) => (_sqlite3__wasm_vfs_create_file = Module["_sqlite3__wasm_vfs_create_file"] = wasmExports["sqlite3__wasm_vfs_create_file"])(a0, a1, a22, a3);
    var _sqlite3__wasm_posix_create_file = Module["_sqlite3__wasm_posix_create_file"] = (a0, a1, a22) => (_sqlite3__wasm_posix_create_file = Module["_sqlite3__wasm_posix_create_file"] = wasmExports["sqlite3__wasm_posix_create_file"])(a0, a1, a22);
    var _sqlite3__wasm_kvvfsMakeKeyOnPstack = Module["_sqlite3__wasm_kvvfsMakeKeyOnPstack"] = (a0, a1) => (_sqlite3__wasm_kvvfsMakeKeyOnPstack = Module["_sqlite3__wasm_kvvfsMakeKeyOnPstack"] = wasmExports["sqlite3__wasm_kvvfsMakeKeyOnPstack"])(a0, a1);
    var _sqlite3__wasm_kvvfs_methods = Module["_sqlite3__wasm_kvvfs_methods"] = () => (_sqlite3__wasm_kvvfs_methods = Module["_sqlite3__wasm_kvvfs_methods"] = wasmExports["sqlite3__wasm_kvvfs_methods"])();
    var _sqlite3__wasm_vtab_config = Module["_sqlite3__wasm_vtab_config"] = (a0, a1, a22) => (_sqlite3__wasm_vtab_config = Module["_sqlite3__wasm_vtab_config"] = wasmExports["sqlite3__wasm_vtab_config"])(a0, a1, a22);
    var _sqlite3__wasm_db_config_ip = Module["_sqlite3__wasm_db_config_ip"] = (a0, a1, a22, a3) => (_sqlite3__wasm_db_config_ip = Module["_sqlite3__wasm_db_config_ip"] = wasmExports["sqlite3__wasm_db_config_ip"])(a0, a1, a22, a3);
    var _sqlite3__wasm_db_config_pii = Module["_sqlite3__wasm_db_config_pii"] = (a0, a1, a22, a3, a4) => (_sqlite3__wasm_db_config_pii = Module["_sqlite3__wasm_db_config_pii"] = wasmExports["sqlite3__wasm_db_config_pii"])(a0, a1, a22, a3, a4);
    var _sqlite3__wasm_db_config_s = Module["_sqlite3__wasm_db_config_s"] = (a0, a1, a22) => (_sqlite3__wasm_db_config_s = Module["_sqlite3__wasm_db_config_s"] = wasmExports["sqlite3__wasm_db_config_s"])(a0, a1, a22);
    var _sqlite3__wasm_config_i = Module["_sqlite3__wasm_config_i"] = (a0, a1) => (_sqlite3__wasm_config_i = Module["_sqlite3__wasm_config_i"] = wasmExports["sqlite3__wasm_config_i"])(a0, a1);
    var _sqlite3__wasm_config_ii = Module["_sqlite3__wasm_config_ii"] = (a0, a1, a22) => (_sqlite3__wasm_config_ii = Module["_sqlite3__wasm_config_ii"] = wasmExports["sqlite3__wasm_config_ii"])(a0, a1, a22);
    var _sqlite3__wasm_config_j = Module["_sqlite3__wasm_config_j"] = (a0, a1) => (_sqlite3__wasm_config_j = Module["_sqlite3__wasm_config_j"] = wasmExports["sqlite3__wasm_config_j"])(a0, a1);
    var _sqlite3__wasm_qfmt_token = Module["_sqlite3__wasm_qfmt_token"] = (a0, a1) => (_sqlite3__wasm_qfmt_token = Module["_sqlite3__wasm_qfmt_token"] = wasmExports["sqlite3__wasm_qfmt_token"])(a0, a1);
    var _sqlite3__wasm_init_wasmfs = Module["_sqlite3__wasm_init_wasmfs"] = (a0) => (_sqlite3__wasm_init_wasmfs = Module["_sqlite3__wasm_init_wasmfs"] = wasmExports["sqlite3__wasm_init_wasmfs"])(a0);
    var _sqlite3__wasm_test_intptr = Module["_sqlite3__wasm_test_intptr"] = (a0) => (_sqlite3__wasm_test_intptr = Module["_sqlite3__wasm_test_intptr"] = wasmExports["sqlite3__wasm_test_intptr"])(a0);
    var _sqlite3__wasm_test_voidptr = Module["_sqlite3__wasm_test_voidptr"] = (a0) => (_sqlite3__wasm_test_voidptr = Module["_sqlite3__wasm_test_voidptr"] = wasmExports["sqlite3__wasm_test_voidptr"])(a0);
    var _sqlite3__wasm_test_int64_max = Module["_sqlite3__wasm_test_int64_max"] = () => (_sqlite3__wasm_test_int64_max = Module["_sqlite3__wasm_test_int64_max"] = wasmExports["sqlite3__wasm_test_int64_max"])();
    var _sqlite3__wasm_test_int64_min = Module["_sqlite3__wasm_test_int64_min"] = () => (_sqlite3__wasm_test_int64_min = Module["_sqlite3__wasm_test_int64_min"] = wasmExports["sqlite3__wasm_test_int64_min"])();
    var _sqlite3__wasm_test_int64_times2 = Module["_sqlite3__wasm_test_int64_times2"] = (a0) => (_sqlite3__wasm_test_int64_times2 = Module["_sqlite3__wasm_test_int64_times2"] = wasmExports["sqlite3__wasm_test_int64_times2"])(a0);
    var _sqlite3__wasm_test_int64_minmax = Module["_sqlite3__wasm_test_int64_minmax"] = (a0, a1) => (_sqlite3__wasm_test_int64_minmax = Module["_sqlite3__wasm_test_int64_minmax"] = wasmExports["sqlite3__wasm_test_int64_minmax"])(a0, a1);
    var _sqlite3__wasm_test_int64ptr = Module["_sqlite3__wasm_test_int64ptr"] = (a0) => (_sqlite3__wasm_test_int64ptr = Module["_sqlite3__wasm_test_int64ptr"] = wasmExports["sqlite3__wasm_test_int64ptr"])(a0);
    var _sqlite3__wasm_test_stack_overflow = Module["_sqlite3__wasm_test_stack_overflow"] = (a0) => (_sqlite3__wasm_test_stack_overflow = Module["_sqlite3__wasm_test_stack_overflow"] = wasmExports["sqlite3__wasm_test_stack_overflow"])(a0);
    var _sqlite3__wasm_test_str_hello = Module["_sqlite3__wasm_test_str_hello"] = (a0) => (_sqlite3__wasm_test_str_hello = Module["_sqlite3__wasm_test_str_hello"] = wasmExports["sqlite3__wasm_test_str_hello"])(a0);
    var _sqlite3__wasm_SQLTester_strglob = Module["_sqlite3__wasm_SQLTester_strglob"] = (a0, a1) => (_sqlite3__wasm_SQLTester_strglob = Module["_sqlite3__wasm_SQLTester_strglob"] = wasmExports["sqlite3__wasm_SQLTester_strglob"])(a0, a1);
    var _malloc = Module["_malloc"] = (a0) => (_malloc = Module["_malloc"] = wasmExports["malloc"])(a0);
    var _free = Module["_free"] = (a0) => (_free = Module["_free"] = wasmExports["free"])(a0);
    var _realloc = Module["_realloc"] = (a0, a1) => (_realloc = Module["_realloc"] = wasmExports["realloc"])(a0, a1);
    var _emscripten_builtin_memalign = (a0, a1) => (_emscripten_builtin_memalign = wasmExports["emscripten_builtin_memalign"])(a0, a1);
    var __emscripten_stack_restore = (a0) => (__emscripten_stack_restore = wasmExports["_emscripten_stack_restore"])(
      a0
    );
    var __emscripten_stack_alloc = (a0) => (__emscripten_stack_alloc = wasmExports["_emscripten_stack_alloc"])(a0);
    var _emscripten_stack_get_current = () => (_emscripten_stack_get_current = wasmExports["emscripten_stack_get_current"])();
    Module["wasmMemory"] = wasmMemory;
    var calledRun;
    var calledPrerun;
    dependenciesFulfilled = function runCaller() {
      if (!calledRun)
        run();
      if (!calledRun)
        dependenciesFulfilled = runCaller;
    };
    function run() {
      if (runDependencies > 0) {
        return;
      }
      if (!calledPrerun) {
        calledPrerun = 1;
        preRun();
        if (runDependencies > 0) {
          return;
        }
      }
      function doRun() {
        var _a8;
        if (calledRun)
          return;
        calledRun = 1;
        Module["calledRun"] = 1;
        if (ABORT)
          return;
        initRuntime();
        readyPromiseResolve(Module);
        (_a8 = Module["onRuntimeInitialized"]) == null ? void 0 : _a8.call(Module);
        postRun();
      }
      if (Module["setStatus"]) {
        Module["setStatus"]("Running...");
        setTimeout(() => {
          setTimeout(() => Module["setStatus"](""), 1);
          doRun();
        }, 1);
      } else {
        doRun();
      }
    }
    if (Module["preInit"]) {
      if (typeof Module["preInit"] == "function")
        Module["preInit"] = [Module["preInit"]];
      while (Module["preInit"].length > 0) {
        Module["preInit"].pop()();
      }
    }
    run();
    if (!Module.postRun)
      Module.postRun = [];
    Module.postRun.push(function(Module2) {
      "use strict";
      "use strict";
      globalThis.sqlite3ApiBootstrap = function sqlite3ApiBootstrap(apiConfig = globalThis.sqlite3ApiConfig || sqlite3ApiBootstrap.defaultConfig) {
        if (sqlite3ApiBootstrap.sqlite3) {
          (sqlite3ApiBootstrap.sqlite3.config || console).warn(
            "sqlite3ApiBootstrap() called multiple times.",
            "Config and external initializers are ignored on calls after the first."
          );
          return sqlite3ApiBootstrap.sqlite3;
        }
        const config = Object.assign(
          /* @__PURE__ */ Object.create(null),
          {
            exports: void 0,
            memory: void 0,
            bigIntEnabled: (() => {
              if ("undefined" !== typeof Module2) {
                if (!!Module2.HEAPU64)
                  return true;
              }
              return !!globalThis.BigInt64Array;
            })(),
            debug: console.debug.bind(console),
            warn: console.warn.bind(console),
            error: console.error.bind(console),
            log: console.log.bind(console),
            wasmfsOpfsDir: "/opfs",
            useStdAlloc: false
          },
          apiConfig || {}
        );
        Object.assign(
          config,
          {
            allocExportName: config.useStdAlloc ? "malloc" : "sqlite3_malloc",
            deallocExportName: config.useStdAlloc ? "free" : "sqlite3_free",
            reallocExportName: config.useStdAlloc ? "realloc" : "sqlite3_realloc"
          },
          config
        );
        ["exports", "memory", "wasmfsOpfsDir"].forEach((k2) => {
          if ("function" === typeof config[k2]) {
            config[k2] = config[k2]();
          }
        });
        delete globalThis.sqlite3ApiConfig;
        delete sqlite3ApiBootstrap.defaultConfig;
        const capi = /* @__PURE__ */ Object.create(null);
        const wasm = /* @__PURE__ */ Object.create(null);
        const __rcStr = (rc) => {
          return capi.sqlite3_js_rc_str && capi.sqlite3_js_rc_str(rc) || "Unknown result code #" + rc;
        };
        const __isInt = (n2) => "number" === typeof n2 && n2 === (n2 | 0);
        class SQLite3Error extends Error {
          constructor(...args) {
            let rc;
            if (args.length) {
              if (__isInt(args[0])) {
                rc = args[0];
                if (1 === args.length) {
                  super(__rcStr(args[0]));
                } else {
                  const rcStr = __rcStr(rc);
                  if ("object" === typeof args[1]) {
                    super(rcStr, args[1]);
                  } else {
                    args[0] = rcStr + ":";
                    super(args.join(" "));
                  }
                }
              } else {
                if (2 === args.length && "object" === typeof args[1]) {
                  super(...args);
                } else {
                  super(args.join(" "));
                }
              }
            }
            this.resultCode = rc || capi.SQLITE_ERROR;
            this.name = "SQLite3Error";
          }
        }
        SQLite3Error.toss = (...args) => {
          throw new SQLite3Error(...args);
        };
        const toss3 = SQLite3Error.toss;
        if (config.wasmfsOpfsDir && !/^\/[^/]+$/.test(config.wasmfsOpfsDir)) {
          toss3(
            "config.wasmfsOpfsDir must be falsy or in the form '/dir-name'."
          );
        }
        const isInt32 = (n2) => {
          return "bigint" !== typeof n2 && !!(n2 === (n2 | 0) && n2 <= 2147483647 && n2 >= -2147483648);
        };
        const bigIntFits64 = function f2(b) {
          if (!f2._max) {
            f2._max = BigInt("0x7fffffffffffffff");
            f2._min = ~f2._max;
          }
          return b >= f2._min && b <= f2._max;
        };
        const bigIntFits32 = (b) => b >= -0x7fffffffn - 1n && b <= 0x7fffffffn;
        const bigIntFitsDouble = function f2(b) {
          if (!f2._min) {
            f2._min = Number.MIN_SAFE_INTEGER;
            f2._max = Number.MAX_SAFE_INTEGER;
          }
          return b >= f2._min && b <= f2._max;
        };
        const isTypedArray = (v3) => {
          return v3 && v3.constructor && isInt32(v3.constructor.BYTES_PER_ELEMENT) ? v3 : false;
        };
        const __SAB = "undefined" === typeof SharedArrayBuffer ? function() {
        } : SharedArrayBuffer;
        const isSharedTypedArray = (aTypedArray) => aTypedArray.buffer instanceof __SAB;
        const typedArrayPart = (aTypedArray, begin, end) => {
          return isSharedTypedArray(aTypedArray) ? aTypedArray.slice(begin, end) : aTypedArray.subarray(begin, end);
        };
        const isBindableTypedArray = (v3) => {
          return v3 && (v3 instanceof Uint8Array || v3 instanceof Int8Array || v3 instanceof ArrayBuffer);
        };
        const isSQLableTypedArray = (v3) => {
          return v3 && (v3 instanceof Uint8Array || v3 instanceof Int8Array || v3 instanceof ArrayBuffer);
        };
        const affirmBindableTypedArray = (v3) => {
          return isBindableTypedArray(v3) || toss3("Value is not of a supported TypedArray type.");
        };
        const utf8Decoder = new TextDecoder("utf-8");
        const typedArrayToString = function(typedArray, begin, end) {
          return utf8Decoder.decode(typedArrayPart(typedArray, begin, end));
        };
        const flexibleString = function(v3) {
          if (isSQLableTypedArray(v3)) {
            return typedArrayToString(
              v3 instanceof ArrayBuffer ? new Uint8Array(v3) : v3
            );
          } else if (Array.isArray(v3))
            return v3.join("");
          else if (wasm.isPtr(v3))
            v3 = wasm.cstrToJs(v3);
          return v3;
        };
        class WasmAllocError extends Error {
          constructor(...args) {
            if (2 === args.length && "object" === typeof args[1]) {
              super(...args);
            } else if (args.length) {
              super(args.join(" "));
            } else {
              super("Allocation failed.");
            }
            this.resultCode = capi.SQLITE_NOMEM;
            this.name = "WasmAllocError";
          }
        }
        WasmAllocError.toss = (...args) => {
          throw new WasmAllocError(...args);
        };
        Object.assign(capi, {
          sqlite3_bind_blob: void 0,
          sqlite3_bind_text: void 0,
          sqlite3_create_function_v2: (pDb2, funcName, nArg, eTextRep, pApp, xFunc, xStep, xFinal, xDestroy) => {
          },
          sqlite3_create_function: (pDb2, funcName, nArg, eTextRep, pApp, xFunc, xStep, xFinal) => {
          },
          sqlite3_create_window_function: (pDb2, funcName, nArg, eTextRep, pApp, xStep, xFinal, xValue, xInverse, xDestroy) => {
          },
          sqlite3_prepare_v3: (dbPtr, sql2, sqlByteLen, prepFlags, stmtPtrPtr, strPtrPtr) => {
          },
          sqlite3_prepare_v2: (dbPtr, sql2, sqlByteLen, stmtPtrPtr, strPtrPtr) => {
          },
          sqlite3_exec: (pDb2, sql2, callback, pVoid, pErrMsg) => {
          },
          sqlite3_randomness: (n2, outPtr) => {
          }
        });
        const util = {
          affirmBindableTypedArray,
          flexibleString,
          bigIntFits32,
          bigIntFits64,
          bigIntFitsDouble,
          isBindableTypedArray,
          isInt32,
          isSQLableTypedArray,
          isTypedArray,
          typedArrayToString,
          isUIThread: () => globalThis.window === globalThis && !!globalThis.document,
          isSharedTypedArray,
          toss: function(...args) {
            throw new Error(args.join(" "));
          },
          toss3,
          typedArrayPart,
          affirmDbHeader: function(bytes) {
            if (bytes instanceof ArrayBuffer)
              bytes = new Uint8Array(bytes);
            const header = "SQLite format 3";
            if (header.length > bytes.byteLength) {
              toss3("Input does not contain an SQLite3 database header.");
            }
            for (let i2 = 0; i2 < header.length; ++i2) {
              if (header.charCodeAt(i2) !== bytes[i2]) {
                toss3("Input does not contain an SQLite3 database header.");
              }
            }
          },
          affirmIsDb: function(bytes) {
            if (bytes instanceof ArrayBuffer)
              bytes = new Uint8Array(bytes);
            const n2 = bytes.byteLength;
            if (n2 < 512 || n2 % 512 !== 0) {
              toss3("Byte array size", n2, "is invalid for an SQLite3 db.");
            }
            util.affirmDbHeader(bytes);
          }
        };
        Object.assign(wasm, {
          ptrSizeof: config.wasmPtrSizeof || 4,
          ptrIR: config.wasmPtrIR || "i32",
          bigIntEnabled: !!config.bigIntEnabled,
          exports: config.exports || toss3("Missing API config.exports (WASM module exports)."),
          memory: config.memory || config.exports["memory"] || toss3(
            "API config object requires a WebAssembly.Memory object",
            "in either config.exports.memory (exported)",
            "or config.memory (imported)."
          ),
          alloc: void 0,
          realloc: void 0,
          dealloc: void 0
        });
        wasm.allocFromTypedArray = function(srcTypedArray) {
          if (srcTypedArray instanceof ArrayBuffer) {
            srcTypedArray = new Uint8Array(srcTypedArray);
          }
          affirmBindableTypedArray(srcTypedArray);
          const pRet = wasm.alloc(srcTypedArray.byteLength || 1);
          wasm.heapForSize(srcTypedArray.constructor).set(srcTypedArray.byteLength ? srcTypedArray : [0], pRet);
          return pRet;
        };
        {
          const keyAlloc = config.allocExportName, keyDealloc = config.deallocExportName, keyRealloc = config.reallocExportName;
          for (const key of [keyAlloc, keyDealloc, keyRealloc]) {
            const f2 = wasm.exports[key];
            if (!(f2 instanceof Function))
              toss3("Missing required exports[", key, "] function.");
          }
          wasm.alloc = function f2(n2) {
            return f2.impl(n2) || WasmAllocError.toss("Failed to allocate", n2, " bytes.");
          };
          wasm.alloc.impl = wasm.exports[keyAlloc];
          wasm.realloc = function f2(m2, n2) {
            const m22 = f2.impl(m2, n2);
            return n2 ? m22 || WasmAllocError.toss("Failed to reallocate", n2, " bytes.") : 0;
          };
          wasm.realloc.impl = wasm.exports[keyRealloc];
          wasm.dealloc = wasm.exports[keyDealloc];
        }
        wasm.compileOptionUsed = function f2(optName) {
          if (!arguments.length) {
            if (f2._result)
              return f2._result;
            else if (!f2._opt) {
              f2._rx = /^([^=]+)=(.+)/;
              f2._rxInt = /^-?\d+$/;
              f2._opt = function(opt, rv) {
                const m2 = f2._rx.exec(opt);
                rv[0] = m2 ? m2[1] : opt;
                rv[1] = m2 ? f2._rxInt.test(m2[2]) ? +m2[2] : m2[2] : true;
              };
            }
            const rc = {}, ov = [0, 0];
            let i2 = 0, k2;
            while (k2 = capi.sqlite3_compileoption_get(i2++)) {
              f2._opt(k2, ov);
              rc[ov[0]] = ov[1];
            }
            return f2._result = rc;
          } else if (Array.isArray(optName)) {
            const rc = {};
            optName.forEach((v3) => {
              rc[v3] = capi.sqlite3_compileoption_used(v3);
            });
            return rc;
          } else if ("object" === typeof optName) {
            Object.keys(optName).forEach((k2) => {
              optName[k2] = capi.sqlite3_compileoption_used(k2);
            });
            return optName;
          }
          return "string" === typeof optName ? !!capi.sqlite3_compileoption_used(optName) : false;
        };
        wasm.pstack = Object.assign(/* @__PURE__ */ Object.create(null), {
          restore: wasm.exports.sqlite3__wasm_pstack_restore,
          alloc: function(n2) {
            if ("string" === typeof n2 && !(n2 = wasm.sizeofIR(n2))) {
              WasmAllocError.toss(
                "Invalid value for pstack.alloc(",
                arguments[0],
                ")"
              );
            }
            return wasm.exports.sqlite3__wasm_pstack_alloc(n2) || WasmAllocError.toss(
              "Could not allocate",
              n2,
              "bytes from the pstack."
            );
          },
          allocChunks: function(n2, sz) {
            if ("string" === typeof sz && !(sz = wasm.sizeofIR(sz))) {
              WasmAllocError.toss(
                "Invalid size value for allocChunks(",
                arguments[1],
                ")"
              );
            }
            const mem = wasm.pstack.alloc(n2 * sz);
            const rc = [];
            let i2 = 0, offset = 0;
            for (; i2 < n2; ++i2, offset += sz)
              rc.push(mem + offset);
            return rc;
          },
          allocPtr: (n2 = 1, safePtrSize = true) => {
            return 1 === n2 ? wasm.pstack.alloc(safePtrSize ? 8 : wasm.ptrSizeof) : wasm.pstack.allocChunks(n2, safePtrSize ? 8 : wasm.ptrSizeof);
          },
          call: function(f2) {
            const stackPos = wasm.pstack.pointer;
            try {
              return f2(sqlite32);
            } finally {
              wasm.pstack.restore(stackPos);
            }
          }
        });
        Object.defineProperties(wasm.pstack, {
          pointer: {
            configurable: false,
            iterable: true,
            writeable: false,
            get: wasm.exports.sqlite3__wasm_pstack_ptr
          },
          quota: {
            configurable: false,
            iterable: true,
            writeable: false,
            get: wasm.exports.sqlite3__wasm_pstack_quota
          },
          remaining: {
            configurable: false,
            iterable: true,
            writeable: false,
            get: wasm.exports.sqlite3__wasm_pstack_remaining
          }
        });
        capi.sqlite3_randomness = (...args) => {
          if (1 === args.length && util.isTypedArray(args[0]) && 1 === args[0].BYTES_PER_ELEMENT) {
            const ta = args[0];
            if (0 === ta.byteLength) {
              wasm.exports.sqlite3_randomness(0, 0);
              return ta;
            }
            const stack = wasm.pstack.pointer;
            try {
              let n2 = ta.byteLength, offset = 0;
              const r3 = wasm.exports.sqlite3_randomness;
              const heap = wasm.heap8u();
              const nAlloc = n2 < 512 ? n2 : 512;
              const ptr = wasm.pstack.alloc(nAlloc);
              do {
                const j2 = n2 > nAlloc ? nAlloc : n2;
                r3(j2, ptr);
                ta.set(typedArrayPart(heap, ptr, ptr + j2), offset);
                n2 -= j2;
                offset += j2;
              } while (n2 > 0);
            } catch (e2) {
              console.error(
                "Highly unexpected (and ignored!) exception in sqlite3_randomness():",
                e2
              );
            } finally {
              wasm.pstack.restore(stack);
            }
            return ta;
          }
          wasm.exports.sqlite3_randomness(...args);
        };
        let __wasmfsOpfsDir = void 0;
        capi.sqlite3_wasmfs_opfs_dir = function() {
          if (void 0 !== __wasmfsOpfsDir)
            return __wasmfsOpfsDir;
          const pdir = config.wasmfsOpfsDir;
          if (!pdir || !globalThis.FileSystemHandle || !globalThis.FileSystemDirectoryHandle || !globalThis.FileSystemFileHandle) {
            return __wasmfsOpfsDir = "";
          }
          try {
            if (pdir && 0 === wasm.xCallWrapped(
              "sqlite3__wasm_init_wasmfs",
              "i32",
              ["string"],
              pdir
            )) {
              return __wasmfsOpfsDir = pdir;
            } else {
              return __wasmfsOpfsDir = "";
            }
          } catch (e2) {
            return __wasmfsOpfsDir = "";
          }
        };
        capi.sqlite3_wasmfs_filename_is_persistent = function(name) {
          const p3 = capi.sqlite3_wasmfs_opfs_dir();
          return p3 && name ? name.startsWith(p3 + "/") : false;
        };
        capi.sqlite3_js_db_uses_vfs = function(pDb2, vfsName, dbName = 0) {
          try {
            const pK = capi.sqlite3_vfs_find(vfsName);
            if (!pK)
              return false;
            else if (!pDb2) {
              return pK === capi.sqlite3_vfs_find(0) ? pK : false;
            } else {
              return pK === capi.sqlite3_js_db_vfs(pDb2, dbName) ? pK : false;
            }
          } catch (e2) {
            return false;
          }
        };
        capi.sqlite3_js_vfs_list = function() {
          const rc = [];
          let pVfs = capi.sqlite3_vfs_find(0);
          while (pVfs) {
            const oVfs = new capi.sqlite3_vfs(pVfs);
            rc.push(wasm.cstrToJs(oVfs.$zName));
            pVfs = oVfs.$pNext;
            oVfs.dispose();
          }
          return rc;
        };
        capi.sqlite3_js_db_export = function(pDb2, schema = 0) {
          pDb2 = wasm.xWrap.testConvertArg("sqlite3*", pDb2);
          if (!pDb2)
            toss3("Invalid sqlite3* argument.");
          if (!wasm.bigIntEnabled)
            toss3("BigInt64 support is not enabled.");
          const scope = wasm.scopedAllocPush();
          let pOut;
          try {
            const pSize = wasm.scopedAlloc(8 + wasm.ptrSizeof);
            const ppOut = pSize + 8;
            const zSchema = schema ? wasm.isPtr(schema) ? schema : wasm.scopedAllocCString("" + schema) : 0;
            let rc = wasm.exports.sqlite3__wasm_db_serialize(
              pDb2,
              zSchema,
              ppOut,
              pSize,
              0
            );
            if (rc) {
              toss3(
                "Database serialization failed with code",
                sqlite32.capi.sqlite3_js_rc_str(rc)
              );
            }
            pOut = wasm.peekPtr(ppOut);
            const nOut = wasm.peek(pSize, "i64");
            rc = nOut ? wasm.heap8u().slice(pOut, pOut + Number(nOut)) : new Uint8Array();
            return rc;
          } finally {
            if (pOut)
              wasm.exports.sqlite3_free(pOut);
            wasm.scopedAllocPop(scope);
          }
        };
        capi.sqlite3_js_db_vfs = (dbPointer, dbName = 0) => util.sqlite3__wasm_db_vfs(dbPointer, dbName);
        capi.sqlite3_js_aggregate_context = (pCtx, n2) => {
          return capi.sqlite3_aggregate_context(pCtx, n2) || (n2 ? WasmAllocError.toss(
            "Cannot allocate",
            n2,
            "bytes for sqlite3_aggregate_context()"
          ) : 0);
        };
        capi.sqlite3_js_posix_create_file = function(filename, data, dataLen) {
          let pData;
          if (data && wasm.isPtr(data)) {
            pData = data;
          } else if (data instanceof ArrayBuffer || data instanceof Uint8Array) {
            pData = wasm.allocFromTypedArray(data);
            if (arguments.length < 3 || !util.isInt32(dataLen) || dataLen < 0) {
              dataLen = data.byteLength;
            }
          } else {
            SQLite3Error.toss(
              "Invalid 2nd argument for sqlite3_js_posix_create_file()."
            );
          }
          try {
            if (!util.isInt32(dataLen) || dataLen < 0) {
              SQLite3Error.toss(
                "Invalid 3rd argument for sqlite3_js_posix_create_file()."
              );
            }
            const rc = util.sqlite3__wasm_posix_create_file(
              filename,
              pData,
              dataLen
            );
            if (rc)
              SQLite3Error.toss(
                "Creation of file failed with sqlite3 result code",
                capi.sqlite3_js_rc_str(rc)
              );
          } finally {
            wasm.dealloc(pData);
          }
        };
        capi.sqlite3_js_vfs_create_file = function(vfs, filename, data, dataLen) {
          config.warn(
            "sqlite3_js_vfs_create_file() is deprecated and",
            "should be avoided because it can lead to C-level crashes.",
            "See its documentation for alternative options."
          );
          let pData;
          if (data) {
            if (wasm.isPtr(data)) {
              pData = data;
            } else if (data instanceof ArrayBuffer) {
              data = new Uint8Array(data);
            }
            if (data instanceof Uint8Array) {
              pData = wasm.allocFromTypedArray(data);
              if (arguments.length < 4 || !util.isInt32(dataLen) || dataLen < 0) {
                dataLen = data.byteLength;
              }
            } else {
              SQLite3Error.toss(
                "Invalid 3rd argument type for sqlite3_js_vfs_create_file()."
              );
            }
          } else {
            pData = 0;
          }
          if (!util.isInt32(dataLen) || dataLen < 0) {
            wasm.dealloc(pData);
            SQLite3Error.toss(
              "Invalid 4th argument for sqlite3_js_vfs_create_file()."
            );
          }
          try {
            const rc = util.sqlite3__wasm_vfs_create_file(
              vfs,
              filename,
              pData,
              dataLen
            );
            if (rc)
              SQLite3Error.toss(
                "Creation of file failed with sqlite3 result code",
                capi.sqlite3_js_rc_str(rc)
              );
          } finally {
            wasm.dealloc(pData);
          }
        };
        capi.sqlite3_js_sql_to_string = (sql2) => {
          if ("string" === typeof sql2) {
            return sql2;
          }
          const x2 = flexibleString(v);
          return x2 === v ? void 0 : x2;
        };
        if (util.isUIThread()) {
          const __kvvfsInfo = function(which) {
            const rc = /* @__PURE__ */ Object.create(null);
            rc.prefix = "kvvfs-" + which;
            rc.stores = [];
            if ("session" === which || "" === which)
              rc.stores.push(globalThis.sessionStorage);
            if ("local" === which || "" === which)
              rc.stores.push(globalThis.localStorage);
            return rc;
          };
          capi.sqlite3_js_kvvfs_clear = function(which = "") {
            let rc = 0;
            const kvinfo = __kvvfsInfo(which);
            kvinfo.stores.forEach((s2) => {
              const toRm = [];
              let i2;
              for (i2 = 0; i2 < s2.length; ++i2) {
                const k2 = s2.key(i2);
                if (k2.startsWith(kvinfo.prefix))
                  toRm.push(k2);
              }
              toRm.forEach((kk) => s2.removeItem(kk));
              rc += toRm.length;
            });
            return rc;
          };
          capi.sqlite3_js_kvvfs_size = function(which = "") {
            let sz = 0;
            const kvinfo = __kvvfsInfo(which);
            kvinfo.stores.forEach((s2) => {
              let i2;
              for (i2 = 0; i2 < s2.length; ++i2) {
                const k2 = s2.key(i2);
                if (k2.startsWith(kvinfo.prefix)) {
                  sz += k2.length;
                  sz += s2.getItem(k2).length;
                }
              }
            });
            return sz * 2;
          };
        }
        capi.sqlite3_db_config = function(pDb2, op, ...args) {
          if (!this.s) {
            this.s = wasm.xWrap("sqlite3__wasm_db_config_s", "int", [
              "sqlite3*",
              "int",
              "string:static"
            ]);
            this.pii = wasm.xWrap("sqlite3__wasm_db_config_pii", "int", [
              "sqlite3*",
              "int",
              "*",
              "int",
              "int"
            ]);
            this.ip = wasm.xWrap("sqlite3__wasm_db_config_ip", "int", [
              "sqlite3*",
              "int",
              "int",
              "*"
            ]);
          }
          switch (op) {
            case capi.SQLITE_DBCONFIG_ENABLE_FKEY:
            case capi.SQLITE_DBCONFIG_ENABLE_TRIGGER:
            case capi.SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER:
            case capi.SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION:
            case capi.SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE:
            case capi.SQLITE_DBCONFIG_ENABLE_QPSG:
            case capi.SQLITE_DBCONFIG_TRIGGER_EQP:
            case capi.SQLITE_DBCONFIG_RESET_DATABASE:
            case capi.SQLITE_DBCONFIG_DEFENSIVE:
            case capi.SQLITE_DBCONFIG_WRITABLE_SCHEMA:
            case capi.SQLITE_DBCONFIG_LEGACY_ALTER_TABLE:
            case capi.SQLITE_DBCONFIG_DQS_DML:
            case capi.SQLITE_DBCONFIG_DQS_DDL:
            case capi.SQLITE_DBCONFIG_ENABLE_VIEW:
            case capi.SQLITE_DBCONFIG_LEGACY_FILE_FORMAT:
            case capi.SQLITE_DBCONFIG_TRUSTED_SCHEMA:
            case capi.SQLITE_DBCONFIG_STMT_SCANSTATUS:
            case capi.SQLITE_DBCONFIG_REVERSE_SCANORDER:
              return this.ip(pDb2, op, args[0], args[1] || 0);
            case capi.SQLITE_DBCONFIG_LOOKASIDE:
              return this.pii(pDb2, op, args[0], args[1], args[2]);
            case capi.SQLITE_DBCONFIG_MAINDBNAME:
              return this.s(pDb2, op, args[0]);
            default:
              return capi.SQLITE_MISUSE;
          }
        }.bind(/* @__PURE__ */ Object.create(null));
        capi.sqlite3_value_to_js = function(pVal, throwIfCannotConvert = true) {
          let arg;
          const valType = capi.sqlite3_value_type(pVal);
          switch (valType) {
            case capi.SQLITE_INTEGER:
              if (wasm.bigIntEnabled) {
                arg = capi.sqlite3_value_int64(pVal);
                if (util.bigIntFitsDouble(arg))
                  arg = Number(arg);
              } else
                arg = capi.sqlite3_value_double(pVal);
              break;
            case capi.SQLITE_FLOAT:
              arg = capi.sqlite3_value_double(pVal);
              break;
            case capi.SQLITE_TEXT:
              arg = capi.sqlite3_value_text(pVal);
              break;
            case capi.SQLITE_BLOB: {
              const n2 = capi.sqlite3_value_bytes(pVal);
              const pBlob = capi.sqlite3_value_blob(pVal);
              if (n2 && !pBlob)
                sqlite32.WasmAllocError.toss(
                  "Cannot allocate memory for blob argument of",
                  n2,
                  "byte(s)"
                );
              arg = n2 ? wasm.heap8u().slice(pBlob, pBlob + Number(n2)) : null;
              break;
            }
            case capi.SQLITE_NULL:
              arg = null;
              break;
            default:
              if (throwIfCannotConvert) {
                toss3(
                  capi.SQLITE_MISMATCH,
                  "Unhandled sqlite3_value_type():",
                  valType
                );
              }
              arg = void 0;
          }
          return arg;
        };
        capi.sqlite3_values_to_js = function(argc, pArgv, throwIfCannotConvert = true) {
          let i2;
          const tgt = [];
          for (i2 = 0; i2 < argc; ++i2) {
            tgt.push(
              capi.sqlite3_value_to_js(
                wasm.peekPtr(pArgv + wasm.ptrSizeof * i2),
                throwIfCannotConvert
              )
            );
          }
          return tgt;
        };
        capi.sqlite3_result_error_js = function(pCtx, e2) {
          if (e2 instanceof WasmAllocError) {
            capi.sqlite3_result_error_nomem(pCtx);
          } else {
            capi.sqlite3_result_error(pCtx, "" + e2, -1);
          }
        };
        capi.sqlite3_result_js = function(pCtx, val) {
          if (val instanceof Error) {
            capi.sqlite3_result_error_js(pCtx, val);
            return;
          }
          try {
            switch (typeof val) {
              case "undefined":
                break;
              case "boolean":
                capi.sqlite3_result_int(pCtx, val ? 1 : 0);
                break;
              case "bigint":
                if (util.bigIntFits32(val)) {
                  capi.sqlite3_result_int(pCtx, Number(val));
                } else if (util.bigIntFitsDouble(val)) {
                  capi.sqlite3_result_double(pCtx, Number(val));
                } else if (wasm.bigIntEnabled) {
                  if (util.bigIntFits64(val))
                    capi.sqlite3_result_int64(pCtx, val);
                  else
                    toss3(
                      "BigInt value",
                      val.toString(),
                      "is too BigInt for int64."
                    );
                } else {
                  toss3("BigInt value", val.toString(), "is too BigInt.");
                }
                break;
              case "number": {
                let f2;
                if (util.isInt32(val)) {
                  f2 = capi.sqlite3_result_int;
                } else if (wasm.bigIntEnabled && Number.isInteger(val) && util.bigIntFits64(BigInt(val))) {
                  f2 = capi.sqlite3_result_int64;
                } else {
                  f2 = capi.sqlite3_result_double;
                }
                f2(pCtx, val);
                break;
              }
              case "string": {
                const [p3, n2] = wasm.allocCString(val, true);
                capi.sqlite3_result_text(pCtx, p3, n2, capi.SQLITE_WASM_DEALLOC);
                break;
              }
              case "object":
                if (null === val) {
                  capi.sqlite3_result_null(pCtx);
                  break;
                } else if (util.isBindableTypedArray(val)) {
                  const pBlob = wasm.allocFromTypedArray(val);
                  capi.sqlite3_result_blob(
                    pCtx,
                    pBlob,
                    val.byteLength,
                    capi.SQLITE_WASM_DEALLOC
                  );
                  break;
                }
              default:
                toss3(
                  "Don't not how to handle this UDF result value:",
                  typeof val,
                  val
                );
            }
          } catch (e2) {
            capi.sqlite3_result_error_js(pCtx, e2);
          }
        };
        capi.sqlite3_column_js = function(pStmt, iCol, throwIfCannotConvert = true) {
          const v3 = capi.sqlite3_column_value(pStmt, iCol);
          return 0 === v3 ? void 0 : capi.sqlite3_value_to_js(v3, throwIfCannotConvert);
        };
        const __newOldValue = function(pObj, iCol, impl) {
          impl = capi[impl];
          if (!this.ptr)
            this.ptr = wasm.allocPtr();
          else
            wasm.pokePtr(this.ptr, 0);
          const rc = impl(pObj, iCol, this.ptr);
          if (rc)
            return SQLite3Error.toss(
              rc,
              arguments[2] + "() failed with code " + rc
            );
          const pv = wasm.peekPtr(this.ptr);
          return pv ? capi.sqlite3_value_to_js(pv, true) : void 0;
        }.bind(/* @__PURE__ */ Object.create(null));
        capi.sqlite3_preupdate_new_js = (pDb2, iCol) => __newOldValue(pDb2, iCol, "sqlite3_preupdate_new");
        capi.sqlite3_preupdate_old_js = (pDb2, iCol) => __newOldValue(pDb2, iCol, "sqlite3_preupdate_old");
        capi.sqlite3changeset_new_js = (pChangesetIter, iCol) => __newOldValue(pChangesetIter, iCol, "sqlite3changeset_new");
        capi.sqlite3changeset_old_js = (pChangesetIter, iCol) => __newOldValue(pChangesetIter, iCol, "sqlite3changeset_old");
        const sqlite32 = {
          WasmAllocError,
          SQLite3Error,
          capi,
          util,
          wasm,
          config,
          version: /* @__PURE__ */ Object.create(null),
          client: void 0,
          asyncPostInit: async function ff() {
            if (ff.isReady instanceof Promise)
              return ff.isReady;
            let lia = sqlite3ApiBootstrap.initializersAsync;
            delete sqlite3ApiBootstrap.initializersAsync;
            const postInit = async () => {
              if (!sqlite32.__isUnderTest) {
                delete sqlite32.util;
                delete sqlite32.StructBinder;
              }
              return sqlite32;
            };
            const catcher = (e2) => {
              config.error("an async sqlite3 initializer failed:", e2);
              throw e2;
            };
            if (!lia || !lia.length) {
              return ff.isReady = postInit().catch(catcher);
            }
            lia = lia.map((f2) => {
              return f2 instanceof Function ? async (x2) => f2(sqlite32) : f2;
            });
            lia.push(postInit);
            let p3 = Promise.resolve(sqlite32);
            while (lia.length)
              p3 = p3.then(lia.shift());
            return ff.isReady = p3.catch(catcher);
          },
          scriptInfo: void 0
        };
        try {
          sqlite3ApiBootstrap.initializers.forEach((f2) => {
            f2(sqlite32);
          });
        } catch (e2) {
          console.error("sqlite3 bootstrap initializer threw:", e2);
          throw e2;
        }
        delete sqlite3ApiBootstrap.initializers;
        sqlite3ApiBootstrap.sqlite3 = sqlite32;
        return sqlite32;
      };
      globalThis.sqlite3ApiBootstrap.initializers = [];
      globalThis.sqlite3ApiBootstrap.initializersAsync = [];
      globalThis.sqlite3ApiBootstrap.defaultConfig = /* @__PURE__ */ Object.create(null);
      globalThis.sqlite3ApiBootstrap.sqlite3 = void 0;
      globalThis.WhWasmUtilInstaller = function(target) {
        "use strict";
        if (void 0 === target.bigIntEnabled) {
          target.bigIntEnabled = !!globalThis["BigInt64Array"];
        }
        const toss = (...args) => {
          throw new Error(args.join(" "));
        };
        if (!target.exports) {
          Object.defineProperty(target, "exports", {
            enumerable: true,
            configurable: true,
            get: () => target.instance && target.instance.exports
          });
        }
        const ptrIR = target.pointerIR || "i32";
        const ptrSizeof = target.ptrSizeof = "i32" === ptrIR ? 4 : "i64" === ptrIR ? 8 : toss("Unhandled ptrSizeof:", ptrIR);
        const cache = /* @__PURE__ */ Object.create(null);
        cache.heapSize = 0;
        cache.memory = null;
        cache.freeFuncIndexes = [];
        cache.scopedAlloc = [];
        cache.utf8Decoder = new TextDecoder();
        cache.utf8Encoder = new TextEncoder("utf-8");
        target.sizeofIR = (n2) => {
          switch (n2) {
            case "i8":
              return 1;
            case "i16":
              return 2;
            case "i32":
            case "f32":
            case "float":
              return 4;
            case "i64":
            case "f64":
            case "double":
              return 8;
            case "*":
              return ptrSizeof;
            default:
              return ("" + n2).endsWith("*") ? ptrSizeof : void 0;
          }
        };
        const heapWrappers = function() {
          if (!cache.memory) {
            cache.memory = target.memory instanceof WebAssembly.Memory ? target.memory : target.exports.memory;
          } else if (cache.heapSize === cache.memory.buffer.byteLength) {
            return cache;
          }
          const b = cache.memory.buffer;
          cache.HEAP8 = new Int8Array(b);
          cache.HEAP8U = new Uint8Array(b);
          cache.HEAP16 = new Int16Array(b);
          cache.HEAP16U = new Uint16Array(b);
          cache.HEAP32 = new Int32Array(b);
          cache.HEAP32U = new Uint32Array(b);
          if (target.bigIntEnabled) {
            cache.HEAP64 = new BigInt64Array(b);
            cache.HEAP64U = new BigUint64Array(b);
          }
          cache.HEAP32F = new Float32Array(b);
          cache.HEAP64F = new Float64Array(b);
          cache.heapSize = b.byteLength;
          return cache;
        };
        target.heap8 = () => heapWrappers().HEAP8;
        target.heap8u = () => heapWrappers().HEAP8U;
        target.heap16 = () => heapWrappers().HEAP16;
        target.heap16u = () => heapWrappers().HEAP16U;
        target.heap32 = () => heapWrappers().HEAP32;
        target.heap32u = () => heapWrappers().HEAP32U;
        target.heapForSize = function(n2, unsigned = true) {
          let ctor;
          const c3 = cache.memory && cache.heapSize === cache.memory.buffer.byteLength ? cache : heapWrappers();
          switch (n2) {
            case Int8Array:
              return c3.HEAP8;
            case Uint8Array:
              return c3.HEAP8U;
            case Int16Array:
              return c3.HEAP16;
            case Uint16Array:
              return c3.HEAP16U;
            case Int32Array:
              return c3.HEAP32;
            case Uint32Array:
              return c3.HEAP32U;
            case 8:
              return unsigned ? c3.HEAP8U : c3.HEAP8;
            case 16:
              return unsigned ? c3.HEAP16U : c3.HEAP16;
            case 32:
              return unsigned ? c3.HEAP32U : c3.HEAP32;
            case 64:
              if (c3.HEAP64)
                return unsigned ? c3.HEAP64U : c3.HEAP64;
              break;
            default:
              if (target.bigIntEnabled) {
                if (n2 === globalThis["BigUint64Array"])
                  return c3.HEAP64U;
                else if (n2 === globalThis["BigInt64Array"])
                  return c3.HEAP64;
                break;
              }
          }
          toss(
            "Invalid heapForSize() size: expecting 8, 16, 32,",
            "or (if BigInt is enabled) 64."
          );
        };
        target.functionTable = function() {
          return target.exports.__indirect_function_table;
        };
        target.functionEntry = function(fptr) {
          const ft = target.functionTable();
          return fptr < ft.length ? ft.get(fptr) : void 0;
        };
        target.jsFuncToWasm = function f2(func, sig) {
          if (!f2._) {
            f2._ = {
              sigTypes: Object.assign(/* @__PURE__ */ Object.create(null), {
                i: "i32",
                p: "i32",
                P: "i32",
                s: "i32",
                j: "i64",
                f: "f32",
                d: "f64"
              }),
              typeCodes: Object.assign(/* @__PURE__ */ Object.create(null), {
                f64: 124,
                f32: 125,
                i64: 126,
                i32: 127
              }),
              uleb128Encode: function(tgt, method, n2) {
                if (n2 < 128)
                  tgt[method](n2);
                else
                  tgt[method](n2 % 128 | 128, n2 >> 7);
              },
              rxJSig: /^(\w)\((\w*)\)$/,
              sigParams: function(sig2) {
                const m2 = f2._.rxJSig.exec(sig2);
                return m2 ? m2[2] : sig2.substr(1);
              },
              letterType: (x2) => f2._.sigTypes[x2] || toss("Invalid signature letter:", x2),
              pushSigType: (dest, letter) => dest.push(f2._.typeCodes[f2._.letterType(letter)])
            };
          }
          if ("string" === typeof func) {
            const x2 = sig;
            sig = func;
            func = x2;
          }
          const sigParams = f2._.sigParams(sig);
          const wasmCode = [1, 96];
          f2._.uleb128Encode(wasmCode, "push", sigParams.length);
          for (const x2 of sigParams)
            f2._.pushSigType(wasmCode, x2);
          if ("v" === sig[0])
            wasmCode.push(0);
          else {
            wasmCode.push(1);
            f2._.pushSigType(wasmCode, sig[0]);
          }
          f2._.uleb128Encode(wasmCode, "unshift", wasmCode.length);
          wasmCode.unshift(
            0,
            97,
            115,
            109,
            1,
            0,
            0,
            0,
            1
          );
          wasmCode.push(
            2,
            7,
            1,
            1,
            101,
            1,
            102,
            0,
            0,
            7,
            5,
            1,
            1,
            102,
            0,
            0
          );
          return new WebAssembly.Instance(
            new WebAssembly.Module(new Uint8Array(wasmCode)),
            {
              e: { f: func }
            }
          ).exports["f"];
        };
        const __installFunction = function f2(func, sig, scoped) {
          if (scoped && !cache.scopedAlloc.length) {
            toss("No scopedAllocPush() scope is active.");
          }
          if ("string" === typeof func) {
            const x2 = sig;
            sig = func;
            func = x2;
          }
          if ("string" !== typeof sig || !(func instanceof Function)) {
            toss(
              "Invalid arguments: expecting (function,signature) or (signature,function)."
            );
          }
          const ft = target.functionTable();
          const oldLen = ft.length;
          let ptr;
          while (cache.freeFuncIndexes.length) {
            ptr = cache.freeFuncIndexes.pop();
            if (ft.get(ptr)) {
              ptr = null;
              continue;
            } else {
              break;
            }
          }
          if (!ptr) {
            ptr = oldLen;
            ft.grow(1);
          }
          try {
            ft.set(ptr, func);
            if (scoped) {
              cache.scopedAlloc[cache.scopedAlloc.length - 1].push(ptr);
            }
            return ptr;
          } catch (e2) {
            if (!(e2 instanceof TypeError)) {
              if (ptr === oldLen)
                cache.freeFuncIndexes.push(oldLen);
              throw e2;
            }
          }
          try {
            const fptr = target.jsFuncToWasm(func, sig);
            ft.set(ptr, fptr);
            if (scoped) {
              cache.scopedAlloc[cache.scopedAlloc.length - 1].push(ptr);
            }
          } catch (e2) {
            if (ptr === oldLen)
              cache.freeFuncIndexes.push(oldLen);
            throw e2;
          }
          return ptr;
        };
        target.installFunction = (func, sig) => __installFunction(func, sig, false);
        target.scopedInstallFunction = (func, sig) => __installFunction(func, sig, true);
        target.uninstallFunction = function(ptr) {
          if (!ptr && 0 !== ptr)
            return void 0;
          const fi = cache.freeFuncIndexes;
          const ft = target.functionTable();
          fi.push(ptr);
          const rc = ft.get(ptr);
          ft.set(ptr, null);
          return rc;
        };
        target.peek = function f2(ptr, type = "i8") {
          if (type.endsWith("*"))
            type = ptrIR;
          const c3 = cache.memory && cache.heapSize === cache.memory.buffer.byteLength ? cache : heapWrappers();
          const list = Array.isArray(ptr) ? [] : void 0;
          let rc;
          do {
            if (list)
              ptr = arguments[0].shift();
            switch (type) {
              case "i1":
              case "i8":
                rc = c3.HEAP8[ptr >> 0];
                break;
              case "i16":
                rc = c3.HEAP16[ptr >> 1];
                break;
              case "i32":
                rc = c3.HEAP32[ptr >> 2];
                break;
              case "float":
              case "f32":
                rc = c3.HEAP32F[ptr >> 2];
                break;
              case "double":
              case "f64":
                rc = Number(c3.HEAP64F[ptr >> 3]);
                break;
              case "i64":
                if (target.bigIntEnabled) {
                  rc = BigInt(c3.HEAP64[ptr >> 3]);
                  break;
                }
              default:
                toss("Invalid type for peek():", type);
            }
            if (list)
              list.push(rc);
          } while (list && arguments[0].length);
          return list || rc;
        };
        target.poke = function(ptr, value, type = "i8") {
          if (type.endsWith("*"))
            type = ptrIR;
          const c3 = cache.memory && cache.heapSize === cache.memory.buffer.byteLength ? cache : heapWrappers();
          for (const p3 of Array.isArray(ptr) ? ptr : [ptr]) {
            switch (type) {
              case "i1":
              case "i8":
                c3.HEAP8[p3 >> 0] = value;
                continue;
              case "i16":
                c3.HEAP16[p3 >> 1] = value;
                continue;
              case "i32":
                c3.HEAP32[p3 >> 2] = value;
                continue;
              case "float":
              case "f32":
                c3.HEAP32F[p3 >> 2] = value;
                continue;
              case "double":
              case "f64":
                c3.HEAP64F[p3 >> 3] = value;
                continue;
              case "i64":
                if (c3.HEAP64) {
                  c3.HEAP64[p3 >> 3] = BigInt(value);
                  continue;
                }
              default:
                toss("Invalid type for poke(): " + type);
            }
          }
          return this;
        };
        target.peekPtr = (...ptr) => target.peek(1 === ptr.length ? ptr[0] : ptr, ptrIR);
        target.pokePtr = (ptr, value = 0) => target.poke(ptr, value, ptrIR);
        target.peek8 = (...ptr) => target.peek(1 === ptr.length ? ptr[0] : ptr, "i8");
        target.poke8 = (ptr, value) => target.poke(ptr, value, "i8");
        target.peek16 = (...ptr) => target.peek(1 === ptr.length ? ptr[0] : ptr, "i16");
        target.poke16 = (ptr, value) => target.poke(ptr, value, "i16");
        target.peek32 = (...ptr) => target.peek(1 === ptr.length ? ptr[0] : ptr, "i32");
        target.poke32 = (ptr, value) => target.poke(ptr, value, "i32");
        target.peek64 = (...ptr) => target.peek(1 === ptr.length ? ptr[0] : ptr, "i64");
        target.poke64 = (ptr, value) => target.poke(ptr, value, "i64");
        target.peek32f = (...ptr) => target.peek(1 === ptr.length ? ptr[0] : ptr, "f32");
        target.poke32f = (ptr, value) => target.poke(ptr, value, "f32");
        target.peek64f = (...ptr) => target.peek(1 === ptr.length ? ptr[0] : ptr, "f64");
        target.poke64f = (ptr, value) => target.poke(ptr, value, "f64");
        target.getMemValue = target.peek;
        target.getPtrValue = target.peekPtr;
        target.setMemValue = target.poke;
        target.setPtrValue = target.pokePtr;
        target.isPtr32 = (ptr) => "number" === typeof ptr && ptr === (ptr | 0) && ptr >= 0;
        target.isPtr = target.isPtr32;
        target.cstrlen = function(ptr) {
          if (!ptr || !target.isPtr(ptr))
            return null;
          const h2 = heapWrappers().HEAP8U;
          let pos = ptr;
          for (; h2[pos] !== 0; ++pos) {
          }
          return pos - ptr;
        };
        const __SAB = "undefined" === typeof SharedArrayBuffer ? function() {
        } : SharedArrayBuffer;
        const __utf8Decode = function(arrayBuffer, begin, end) {
          return cache.utf8Decoder.decode(
            arrayBuffer.buffer instanceof __SAB ? arrayBuffer.slice(begin, end) : arrayBuffer.subarray(begin, end)
          );
        };
        target.cstrToJs = function(ptr) {
          const n2 = target.cstrlen(ptr);
          return n2 ? __utf8Decode(heapWrappers().HEAP8U, ptr, ptr + n2) : null === n2 ? n2 : "";
        };
        target.jstrlen = function(str) {
          if ("string" !== typeof str)
            return null;
          const n2 = str.length;
          let len = 0;
          for (let i2 = 0; i2 < n2; ++i2) {
            let u3 = str.charCodeAt(i2);
            if (u3 >= 55296 && u3 <= 57343) {
              u3 = 65536 + ((u3 & 1023) << 10) | str.charCodeAt(++i2) & 1023;
            }
            if (u3 <= 127)
              ++len;
            else if (u3 <= 2047)
              len += 2;
            else if (u3 <= 65535)
              len += 3;
            else
              len += 4;
          }
          return len;
        };
        target.jstrcpy = function(jstr, tgt, offset = 0, maxBytes = -1, addNul = true) {
          if (!tgt || !(tgt instanceof Int8Array) && !(tgt instanceof Uint8Array)) {
            toss("jstrcpy() target must be an Int8Array or Uint8Array.");
          }
          if (maxBytes < 0)
            maxBytes = tgt.length - offset;
          if (!(maxBytes > 0) || !(offset >= 0))
            return 0;
          let i2 = 0, max = jstr.length;
          const begin = offset, end = offset + maxBytes - (addNul ? 1 : 0);
          for (; i2 < max && offset < end; ++i2) {
            let u3 = jstr.charCodeAt(i2);
            if (u3 >= 55296 && u3 <= 57343) {
              u3 = 65536 + ((u3 & 1023) << 10) | jstr.charCodeAt(++i2) & 1023;
            }
            if (u3 <= 127) {
              if (offset >= end)
                break;
              tgt[offset++] = u3;
            } else if (u3 <= 2047) {
              if (offset + 1 >= end)
                break;
              tgt[offset++] = 192 | u3 >> 6;
              tgt[offset++] = 128 | u3 & 63;
            } else if (u3 <= 65535) {
              if (offset + 2 >= end)
                break;
              tgt[offset++] = 224 | u3 >> 12;
              tgt[offset++] = 128 | u3 >> 6 & 63;
              tgt[offset++] = 128 | u3 & 63;
            } else {
              if (offset + 3 >= end)
                break;
              tgt[offset++] = 240 | u3 >> 18;
              tgt[offset++] = 128 | u3 >> 12 & 63;
              tgt[offset++] = 128 | u3 >> 6 & 63;
              tgt[offset++] = 128 | u3 & 63;
            }
          }
          if (addNul)
            tgt[offset++] = 0;
          return offset - begin;
        };
        target.cstrncpy = function(tgtPtr, srcPtr, n2) {
          if (!tgtPtr || !srcPtr)
            toss("cstrncpy() does not accept NULL strings.");
          if (n2 < 0)
            n2 = target.cstrlen(strPtr) + 1;
          else if (!(n2 > 0))
            return 0;
          const heap = target.heap8u();
          let i2 = 0, ch;
          for (; i2 < n2 && (ch = heap[srcPtr + i2]); ++i2) {
            heap[tgtPtr + i2] = ch;
          }
          if (i2 < n2)
            heap[tgtPtr + i2++] = 0;
          return i2;
        };
        target.jstrToUintArray = (str, addNul = false) => {
          return cache.utf8Encoder.encode(addNul ? str + "\0" : str);
        };
        const __affirmAlloc = (obj, funcName) => {
          if (!(obj.alloc instanceof Function) || !(obj.dealloc instanceof Function)) {
            toss(
              "Object is missing alloc() and/or dealloc() function(s)",
              "required by",
              funcName + "()."
            );
          }
        };
        const __allocCStr = function(jstr, returnWithLength, allocator, funcName) {
          __affirmAlloc(target, funcName);
          if ("string" !== typeof jstr)
            return null;
          if (0) {
            const n2 = target.jstrlen(jstr), ptr = allocator(n2 + 1);
            target.jstrcpy(jstr, target.heap8u(), ptr, n2 + 1, true);
            return returnWithLength ? [ptr, n2] : ptr;
          } else {
            const u3 = cache.utf8Encoder.encode(jstr), ptr = allocator(u3.length + 1), heap = heapWrappers().HEAP8U;
            heap.set(u3, ptr);
            heap[ptr + u3.length] = 0;
            return returnWithLength ? [ptr, u3.length] : ptr;
          }
        };
        target.allocCString = (jstr, returnWithLength = false) => __allocCStr(jstr, returnWithLength, target.alloc, "allocCString()");
        target.scopedAllocPush = function() {
          __affirmAlloc(target, "scopedAllocPush");
          const a3 = [];
          cache.scopedAlloc.push(a3);
          return a3;
        };
        target.scopedAllocPop = function(state) {
          __affirmAlloc(target, "scopedAllocPop");
          const n2 = arguments.length ? cache.scopedAlloc.indexOf(state) : cache.scopedAlloc.length - 1;
          if (n2 < 0)
            toss("Invalid state object for scopedAllocPop().");
          if (0 === arguments.length)
            state = cache.scopedAlloc[n2];
          cache.scopedAlloc.splice(n2, 1);
          for (let p3; p3 = state.pop(); ) {
            if (target.functionEntry(p3)) {
              target.uninstallFunction(p3);
            } else
              target.dealloc(p3);
          }
        };
        target.scopedAlloc = function(n2) {
          if (!cache.scopedAlloc.length) {
            toss("No scopedAllocPush() scope is active.");
          }
          const p3 = target.alloc(n2);
          cache.scopedAlloc[cache.scopedAlloc.length - 1].push(p3);
          return p3;
        };
        Object.defineProperty(target.scopedAlloc, "level", {
          configurable: false,
          enumerable: false,
          get: () => cache.scopedAlloc.length,
          set: () => toss("The 'active' property is read-only.")
        });
        target.scopedAllocCString = (jstr, returnWithLength = false) => __allocCStr(
          jstr,
          returnWithLength,
          target.scopedAlloc,
          "scopedAllocCString()"
        );
        const __allocMainArgv = function(isScoped, list) {
          const pList = target[isScoped ? "scopedAlloc" : "alloc"](
            (list.length + 1) * target.ptrSizeof
          );
          let i2 = 0;
          list.forEach((e2) => {
            target.pokePtr(
              pList + target.ptrSizeof * i2++,
              target[isScoped ? "scopedAllocCString" : "allocCString"]("" + e2)
            );
          });
          target.pokePtr(pList + target.ptrSizeof * i2, 0);
          return pList;
        };
        target.scopedAllocMainArgv = (list) => __allocMainArgv(true, list);
        target.allocMainArgv = (list) => __allocMainArgv(false, list);
        target.cArgvToJs = (argc, pArgv) => {
          const list = [];
          for (let i2 = 0; i2 < argc; ++i2) {
            const arg = target.peekPtr(pArgv + target.ptrSizeof * i2);
            list.push(arg ? target.cstrToJs(arg) : null);
          }
          return list;
        };
        target.scopedAllocCall = function(func) {
          target.scopedAllocPush();
          try {
            return func();
          } finally {
            target.scopedAllocPop();
          }
        };
        const __allocPtr = function(howMany, safePtrSize, method) {
          __affirmAlloc(target, method);
          const pIr = safePtrSize ? "i64" : ptrIR;
          let m2 = target[method](howMany * (safePtrSize ? 8 : ptrSizeof));
          target.poke(m2, 0, pIr);
          if (1 === howMany) {
            return m2;
          }
          const a3 = [m2];
          for (let i2 = 1; i2 < howMany; ++i2) {
            m2 += safePtrSize ? 8 : ptrSizeof;
            a3[i2] = m2;
            target.poke(m2, 0, pIr);
          }
          return a3;
        };
        target.allocPtr = (howMany = 1, safePtrSize = true) => __allocPtr(howMany, safePtrSize, "alloc");
        target.scopedAllocPtr = (howMany = 1, safePtrSize = true) => __allocPtr(howMany, safePtrSize, "scopedAlloc");
        target.xGet = function(name) {
          return target.exports[name] || toss("Cannot find exported symbol:", name);
        };
        const __argcMismatch = (f2, n2) => toss(f2 + "() requires", n2, "argument(s).");
        target.xCall = function(fname, ...args) {
          const f2 = fname instanceof Function ? fname : target.xGet(fname);
          if (!(f2 instanceof Function))
            toss("Exported symbol", fname, "is not a function.");
          if (f2.length !== args.length)
            __argcMismatch(f2 === fname ? f2.name : fname, f2.length);
          return 2 === arguments.length && Array.isArray(arguments[1]) ? f2.apply(null, arguments[1]) : f2.apply(null, args);
        };
        cache.xWrap = /* @__PURE__ */ Object.create(null);
        cache.xWrap.convert = /* @__PURE__ */ Object.create(null);
        cache.xWrap.convert.arg = /* @__PURE__ */ new Map();
        cache.xWrap.convert.result = /* @__PURE__ */ new Map();
        const xArg = cache.xWrap.convert.arg, xResult = cache.xWrap.convert.result;
        if (target.bigIntEnabled) {
          xArg.set("i64", (i2) => BigInt(i2));
        }
        const __xArgPtr = "i32" === ptrIR ? (i2) => i2 | 0 : (i2) => BigInt(i2) | BigInt(0);
        xArg.set("i32", __xArgPtr).set("i16", (i2) => (i2 | 0) & 65535).set("i8", (i2) => (i2 | 0) & 255).set("f32", (i2) => Number(i2).valueOf()).set("float", xArg.get("f32")).set("f64", xArg.get("f32")).set("double", xArg.get("f64")).set("int", xArg.get("i32")).set("null", (i2) => i2).set(null, xArg.get("null")).set("**", __xArgPtr).set("*", __xArgPtr);
        xResult.set("*", __xArgPtr).set("pointer", __xArgPtr).set("number", (v3) => Number(v3)).set("void", (v3) => void 0).set("null", (v3) => v3).set(null, xResult.get("null"));
        {
          const copyToResult = [
            "i8",
            "i16",
            "i32",
            "int",
            "f32",
            "float",
            "f64",
            "double"
          ];
          if (target.bigIntEnabled)
            copyToResult.push("i64");
          const adaptPtr = xArg.get(ptrIR);
          for (const t2 of copyToResult) {
            xArg.set(t2 + "*", adaptPtr);
            xResult.set(t2 + "*", adaptPtr);
            xResult.set(t2, xArg.get(t2) || toss("Missing arg converter:", t2));
          }
        }
        const __xArgString = function(v3) {
          if ("string" === typeof v3)
            return target.scopedAllocCString(v3);
          return v3 ? __xArgPtr(v3) : null;
        };
        xArg.set("string", __xArgString).set("utf8", __xArgString).set("pointer", __xArgString);
        xResult.set("string", (i2) => target.cstrToJs(i2)).set("utf8", xResult.get("string")).set("string:dealloc", (i2) => {
          try {
            return i2 ? target.cstrToJs(i2) : null;
          } finally {
            target.dealloc(i2);
          }
        }).set("utf8:dealloc", xResult.get("string:dealloc")).set("json", (i2) => JSON.parse(target.cstrToJs(i2))).set("json:dealloc", (i2) => {
          try {
            return i2 ? JSON.parse(target.cstrToJs(i2)) : null;
          } finally {
            target.dealloc(i2);
          }
        });
        const AbstractArgAdapter = class {
          constructor(opt) {
            this.name = opt.name || "unnamed adapter";
          }
          convertArg(v3, argv2, argIndex) {
            toss("AbstractArgAdapter must be subclassed.");
          }
        };
        xArg.FuncPtrAdapter = class FuncPtrAdapter extends AbstractArgAdapter {
          constructor(opt) {
            super(opt);
            if (xArg.FuncPtrAdapter.warnOnUse) {
              console.warn(
                "xArg.FuncPtrAdapter is an internal-only API",
                "and is not intended to be invoked from",
                "client-level code. Invoked with:",
                opt
              );
            }
            this.name = opt.name || "unnamed";
            this.signature = opt.signature;
            if (opt.contextKey instanceof Function) {
              this.contextKey = opt.contextKey;
              if (!opt.bindScope)
                opt.bindScope = "context";
            }
            this.bindScope = opt.bindScope || toss(
              "FuncPtrAdapter options requires a bindScope (explicit or implied)."
            );
            if (FuncPtrAdapter.bindScopes.indexOf(opt.bindScope) < 0) {
              toss(
                "Invalid options.bindScope (" + opt.bindMod + ") for FuncPtrAdapter. Expecting one of: (" + FuncPtrAdapter.bindScopes.join(", ") + ")"
              );
            }
            this.isTransient = "transient" === this.bindScope;
            this.isContext = "context" === this.bindScope;
            this.isPermanent = "permanent" === this.bindScope;
            this.singleton = "singleton" === this.bindScope ? [] : void 0;
            this.callProxy = opt.callProxy instanceof Function ? opt.callProxy : void 0;
          }
          contextKey(argv2, argIndex) {
            return this;
          }
          contextMap(key) {
            const cm = this.__cmap || (this.__cmap = /* @__PURE__ */ new Map());
            let rc = cm.get(key);
            if (void 0 === rc)
              cm.set(key, rc = []);
            return rc;
          }
          convertArg(v3, argv2, argIndex) {
            let pair = this.singleton;
            if (!pair && this.isContext) {
              pair = this.contextMap(this.contextKey(argv2, argIndex));
            }
            if (pair && pair[0] === v3)
              return pair[1];
            if (v3 instanceof Function) {
              if (this.callProxy)
                v3 = this.callProxy(v3);
              const fp = __installFunction(v3, this.signature, this.isTransient);
              if (FuncPtrAdapter.debugFuncInstall) {
                FuncPtrAdapter.debugOut(
                  "FuncPtrAdapter installed",
                  this,
                  this.contextKey(argv2, argIndex),
                  "@" + fp,
                  v3
                );
              }
              if (pair) {
                if (pair[1]) {
                  if (FuncPtrAdapter.debugFuncInstall) {
                    FuncPtrAdapter.debugOut(
                      "FuncPtrAdapter uninstalling",
                      this,
                      this.contextKey(argv2, argIndex),
                      "@" + pair[1],
                      v3
                    );
                  }
                  try {
                    cache.scopedAlloc[cache.scopedAlloc.length - 1].push(
                      pair[1]
                    );
                  } catch (e2) {
                  }
                }
                pair[0] = v3;
                pair[1] = fp;
              }
              return fp;
            } else if (target.isPtr(v3) || null === v3 || void 0 === v3) {
              if (pair && pair[1] && pair[1] !== v3) {
                if (FuncPtrAdapter.debugFuncInstall) {
                  FuncPtrAdapter.debugOut(
                    "FuncPtrAdapter uninstalling",
                    this,
                    this.contextKey(argv2, argIndex),
                    "@" + pair[1],
                    v3
                  );
                }
                try {
                  cache.scopedAlloc[cache.scopedAlloc.length - 1].push(pair[1]);
                } catch (e2) {
                }
                pair[0] = pair[1] = v3 | 0;
              }
              return v3 || 0;
            } else {
              throw new TypeError(
                "Invalid FuncPtrAdapter argument type. Expecting a function pointer or a " + (this.name ? this.name + " " : "") + "function matching signature " + this.signature + "."
              );
            }
          }
        };
        xArg.FuncPtrAdapter.warnOnUse = false;
        xArg.FuncPtrAdapter.debugFuncInstall = false;
        xArg.FuncPtrAdapter.debugOut = console.debug.bind(console);
        xArg.FuncPtrAdapter.bindScopes = [
          "transient",
          "context",
          "singleton",
          "permanent"
        ];
        const __xArgAdapterCheck = (t2) => xArg.get(t2) || toss("Argument adapter not found:", t2);
        const __xResultAdapterCheck = (t2) => xResult.get(t2) || toss("Result adapter not found:", t2);
        cache.xWrap.convertArg = (t2, ...args) => __xArgAdapterCheck(t2)(...args);
        cache.xWrap.convertArgNoCheck = (t2, ...args) => xArg.get(t2)(...args);
        cache.xWrap.convertResult = (t2, v3) => null === t2 ? v3 : t2 ? __xResultAdapterCheck(t2)(v3) : void 0;
        cache.xWrap.convertResultNoCheck = (t2, v3) => null === t2 ? v3 : t2 ? xResult.get(t2)(v3) : void 0;
        target.xWrap = function(fArg, resultType, ...argTypes) {
          if (3 === arguments.length && Array.isArray(arguments[2])) {
            argTypes = arguments[2];
          }
          if (target.isPtr(fArg)) {
            fArg = target.functionEntry(fArg) || toss("Function pointer not found in WASM function table.");
          }
          const fIsFunc = fArg instanceof Function;
          const xf = fIsFunc ? fArg : target.xGet(fArg);
          if (fIsFunc)
            fArg = xf.name || "unnamed function";
          if (argTypes.length !== xf.length)
            __argcMismatch(fArg, xf.length);
          if (null === resultType && 0 === xf.length) {
            return xf;
          }
          if (void 0 !== resultType && null !== resultType)
            __xResultAdapterCheck(resultType);
          for (const t2 of argTypes) {
            if (t2 instanceof AbstractArgAdapter)
              xArg.set(t2, (...args) => t2.convertArg(...args));
            else
              __xArgAdapterCheck(t2);
          }
          const cxw = cache.xWrap;
          if (0 === xf.length) {
            return (...args) => args.length ? __argcMismatch(fArg, xf.length) : cxw.convertResult(resultType, xf.call(null));
          }
          return function(...args) {
            if (args.length !== xf.length)
              __argcMismatch(fArg, xf.length);
            const scope = target.scopedAllocPush();
            try {
              let i2 = 0;
              for (; i2 < args.length; ++i2)
                args[i2] = cxw.convertArgNoCheck(argTypes[i2], args[i2], args, i2);
              return cxw.convertResultNoCheck(resultType, xf.apply(null, args));
            } finally {
              target.scopedAllocPop(scope);
            }
          };
        };
        const __xAdapter = function(func, argc, typeName, adapter, modeName, xcvPart) {
          if ("string" === typeof typeName) {
            if (1 === argc)
              return xcvPart.get(typeName);
            else if (2 === argc) {
              if (!adapter) {
                xcvPart.delete(typeName);
                return func;
              } else if (!(adapter instanceof Function)) {
                toss(modeName, "requires a function argument.");
              }
              xcvPart.set(typeName, adapter);
              return func;
            }
          }
          toss("Invalid arguments to", modeName);
        };
        target.xWrap.resultAdapter = function f2(typeName, adapter) {
          return __xAdapter(
            f2,
            arguments.length,
            typeName,
            adapter,
            "resultAdapter()",
            xResult
          );
        };
        target.xWrap.argAdapter = function f2(typeName, adapter) {
          return __xAdapter(
            f2,
            arguments.length,
            typeName,
            adapter,
            "argAdapter()",
            xArg
          );
        };
        target.xWrap.FuncPtrAdapter = xArg.FuncPtrAdapter;
        target.xCallWrapped = function(fArg, resultType, argTypes, ...args) {
          if (Array.isArray(arguments[3]))
            args = arguments[3];
          return target.xWrap(fArg, resultType, argTypes || []).apply(null, args || []);
        };
        target.xWrap.testConvertArg = cache.xWrap.convertArg;
        target.xWrap.testConvertResult = cache.xWrap.convertResult;
        return target;
      };
      globalThis.WhWasmUtilInstaller.yawl = function(config) {
        const wfetch = () => fetch(config.uri, { credentials: "same-origin" });
        const wui = this;
        const finalThen = function(arg) {
          if (config.wasmUtilTarget) {
            const toss = (...args) => {
              throw new Error(args.join(" "));
            };
            const tgt = config.wasmUtilTarget;
            tgt.module = arg.module;
            tgt.instance = arg.instance;
            if (!tgt.instance.exports.memory) {
              tgt.memory = config.imports && config.imports.env && config.imports.env.memory || toss("Missing 'memory' object!");
            }
            if (!tgt.alloc && arg.instance.exports.malloc) {
              const exports = arg.instance.exports;
              tgt.alloc = function(n2) {
                return exports.malloc(n2) || toss("Allocation of", n2, "bytes failed.");
              };
              tgt.dealloc = function(m2) {
                exports.free(m2);
              };
            }
            wui(tgt);
          }
          if (config.onload)
            config.onload(arg, config);
          return arg;
        };
        const loadWasm = WebAssembly.instantiateStreaming ? function loadWasmStreaming() {
          return WebAssembly.instantiateStreaming(
            wfetch(),
            config.imports || {}
          ).then(finalThen);
        } : function loadWasmOldSchool() {
          return wfetch().then((response) => response.arrayBuffer()).then(
            (bytes) => WebAssembly.instantiate(bytes, config.imports || {})
          ).then(finalThen);
        };
        return loadWasm;
      }.bind(globalThis.WhWasmUtilInstaller);
      "use strict";
      globalThis.Jaccwabyt = function StructBinderFactory(config) {
        const toss = (...args) => {
          throw new Error(args.join(" "));
        };
        if (!(config.heap instanceof WebAssembly.Memory) && !(config.heap instanceof Function)) {
          toss(
            "config.heap must be WebAssembly.Memory instance or a function."
          );
        }
        ["alloc", "dealloc"].forEach(function(k2) {
          config[k2] instanceof Function || toss("Config option '" + k2 + "' must be a function.");
        });
        const SBF = StructBinderFactory;
        const heap = config.heap instanceof Function ? config.heap : () => new Uint8Array(config.heap.buffer), alloc = config.alloc, dealloc = config.dealloc, log2 = config.log || console.log.bind(console), memberPrefix = config.memberPrefix || "", memberSuffix = config.memberSuffix || "", bigIntEnabled = void 0 === config.bigIntEnabled ? !!globalThis["BigInt64Array"] : !!config.bigIntEnabled, BigInt2 = globalThis["BigInt"], BigInt64Array2 = globalThis["BigInt64Array"], ptrSizeof = config.ptrSizeof || 4, ptrIR = config.ptrIR || "i32";
        if (!SBF.debugFlags) {
          SBF.__makeDebugFlags = function(deriveFrom = null) {
            if (deriveFrom && deriveFrom.__flags)
              deriveFrom = deriveFrom.__flags;
            const f2 = function f3(flags) {
              if (0 === arguments.length) {
                return f3.__flags;
              }
              if (flags < 0) {
                delete f3.__flags.getter;
                delete f3.__flags.setter;
                delete f3.__flags.alloc;
                delete f3.__flags.dealloc;
              } else {
                f3.__flags.getter = 0 !== (1 & flags);
                f3.__flags.setter = 0 !== (2 & flags);
                f3.__flags.alloc = 0 !== (4 & flags);
                f3.__flags.dealloc = 0 !== (8 & flags);
              }
              return f3._flags;
            };
            Object.defineProperty(f2, "__flags", {
              iterable: false,
              writable: false,
              value: Object.create(deriveFrom)
            });
            if (!deriveFrom)
              f2(0);
            return f2;
          };
          SBF.debugFlags = SBF.__makeDebugFlags();
        }
        const isLittleEndian = function() {
          const buffer = new ArrayBuffer(2);
          new DataView(buffer).setInt16(0, 256, true);
          return new Int16Array(buffer)[0] === 256;
        }();
        const isFuncSig = (s2) => "(" === s2[1];
        const isPtrSig = (s2) => "p" === s2 || "P" === s2;
        const isAutoPtrSig = (s2) => "P" === s2;
        const sigLetter = (s2) => isFuncSig(s2) ? "p" : s2[0];
        const sigIR = function(s2) {
          switch (sigLetter(s2)) {
            case "c":
            case "C":
              return "i8";
            case "i":
              return "i32";
            case "p":
            case "P":
            case "s":
              return ptrIR;
            case "j":
              return "i64";
            case "f":
              return "float";
            case "d":
              return "double";
          }
          toss("Unhandled signature IR:", s2);
        };
        const affirmBigIntArray = BigInt64Array2 ? () => true : () => toss("BigInt64Array is not available.");
        const sigDVGetter = function(s2) {
          switch (sigLetter(s2)) {
            case "p":
            case "P":
            case "s": {
              switch (ptrSizeof) {
                case 4:
                  return "getInt32";
                case 8:
                  return affirmBigIntArray() && "getBigInt64";
              }
              break;
            }
            case "i":
              return "getInt32";
            case "c":
              return "getInt8";
            case "C":
              return "getUint8";
            case "j":
              return affirmBigIntArray() && "getBigInt64";
            case "f":
              return "getFloat32";
            case "d":
              return "getFloat64";
          }
          toss("Unhandled DataView getter for signature:", s2);
        };
        const sigDVSetter = function(s2) {
          switch (sigLetter(s2)) {
            case "p":
            case "P":
            case "s": {
              switch (ptrSizeof) {
                case 4:
                  return "setInt32";
                case 8:
                  return affirmBigIntArray() && "setBigInt64";
              }
              break;
            }
            case "i":
              return "setInt32";
            case "c":
              return "setInt8";
            case "C":
              return "setUint8";
            case "j":
              return affirmBigIntArray() && "setBigInt64";
            case "f":
              return "setFloat32";
            case "d":
              return "setFloat64";
          }
          toss("Unhandled DataView setter for signature:", s2);
        };
        const sigDVSetWrapper = function(s2) {
          switch (sigLetter(s2)) {
            case "i":
            case "f":
            case "c":
            case "C":
            case "d":
              return Number;
            case "j":
              return affirmBigIntArray() && BigInt2;
            case "p":
            case "P":
            case "s":
              switch (ptrSizeof) {
                case 4:
                  return Number;
                case 8:
                  return affirmBigIntArray() && BigInt2;
              }
              break;
          }
          toss("Unhandled DataView set wrapper for signature:", s2);
        };
        const sPropName = (s2, k2) => s2 + "::" + k2;
        const __propThrowOnSet = function(structName, propName) {
          return () => toss(sPropName(structName, propName), "is read-only.");
        };
        const __instancePointerMap = /* @__PURE__ */ new WeakMap();
        const xPtrPropName = "(pointer-is-external)";
        const __freeStruct = function(ctor, obj, m2) {
          if (!m2)
            m2 = __instancePointerMap.get(obj);
          if (m2) {
            __instancePointerMap.delete(obj);
            if (Array.isArray(obj.ondispose)) {
              let x2;
              while (x2 = obj.ondispose.shift()) {
                try {
                  if (x2 instanceof Function)
                    x2.call(obj);
                  else if (x2 instanceof StructType)
                    x2.dispose();
                  else if ("number" === typeof x2)
                    dealloc(x2);
                } catch (e2) {
                  console.warn(
                    "ondispose() for",
                    ctor.structName,
                    "@",
                    m2,
                    "threw. NOT propagating it.",
                    e2
                  );
                }
              }
            } else if (obj.ondispose instanceof Function) {
              try {
                obj.ondispose();
              } catch (e2) {
                console.warn(
                  "ondispose() for",
                  ctor.structName,
                  "@",
                  m2,
                  "threw. NOT propagating it.",
                  e2
                );
              }
            }
            delete obj.ondispose;
            if (ctor.debugFlags.__flags.dealloc) {
              log2(
                "debug.dealloc:",
                obj[xPtrPropName] ? "EXTERNAL" : "",
                ctor.structName,
                "instance:",
                ctor.structInfo.sizeof,
                "bytes @" + m2
              );
            }
            if (!obj[xPtrPropName])
              dealloc(m2);
          }
        };
        const rop = (v3) => {
          return {
            configurable: false,
            writable: false,
            iterable: false,
            value: v3
          };
        };
        const __allocStruct = function(ctor, obj, m2) {
          let fill = !m2;
          if (m2)
            Object.defineProperty(obj, xPtrPropName, rop(m2));
          else {
            m2 = alloc(ctor.structInfo.sizeof);
            if (!m2)
              toss("Allocation of", ctor.structName, "structure failed.");
          }
          try {
            if (ctor.debugFlags.__flags.alloc) {
              log2(
                "debug.alloc:",
                fill ? "" : "EXTERNAL",
                ctor.structName,
                "instance:",
                ctor.structInfo.sizeof,
                "bytes @" + m2
              );
            }
            if (fill)
              heap().fill(0, m2, m2 + ctor.structInfo.sizeof);
            __instancePointerMap.set(obj, m2);
          } catch (e2) {
            __freeStruct(ctor, obj, m2);
            throw e2;
          }
        };
        const __memoryDump = function() {
          const p3 = this.pointer;
          return p3 ? new Uint8Array(heap().slice(p3, p3 + this.structInfo.sizeof)) : null;
        };
        const __memberKey = (k2) => memberPrefix + k2 + memberSuffix;
        const __memberKeyProp = rop(__memberKey);
        const __lookupMember = function(structInfo, memberName, tossIfNotFound = true) {
          let m2 = structInfo.members[memberName];
          if (!m2 && (memberPrefix || memberSuffix)) {
            for (const v3 of Object.values(structInfo.members)) {
              if (v3.key === memberName) {
                m2 = v3;
                break;
              }
            }
            if (!m2 && tossIfNotFound) {
              toss(
                sPropName(structInfo.name, memberName),
                "is not a mapped struct member."
              );
            }
          }
          return m2;
        };
        const __memberSignature = function f2(obj, memberName, emscriptenFormat = false) {
          if (!f2._)
            f2._ = (x2) => x2.replace(/[^vipPsjrdcC]/g, "").replace(/[pPscC]/g, "i");
          const m2 = __lookupMember(obj.structInfo, memberName, true);
          return emscriptenFormat ? f2._(m2.signature) : m2.signature;
        };
        const __ptrPropDescriptor = {
          configurable: false,
          enumerable: false,
          get: function() {
            return __instancePointerMap.get(this);
          },
          set: () => toss("Cannot assign the 'pointer' property of a struct.")
        };
        const __structMemberKeys = rop(function() {
          const a3 = [];
          for (const k2 of Object.keys(this.structInfo.members)) {
            a3.push(this.memberKey(k2));
          }
          return a3;
        });
        const __utf8Decoder = new TextDecoder("utf-8");
        const __utf8Encoder = new TextEncoder();
        const __SAB = "undefined" === typeof SharedArrayBuffer ? function() {
        } : SharedArrayBuffer;
        const __utf8Decode = function(arrayBuffer, begin, end) {
          return __utf8Decoder.decode(
            arrayBuffer.buffer instanceof __SAB ? arrayBuffer.slice(begin, end) : arrayBuffer.subarray(begin, end)
          );
        };
        const __memberIsString = function(obj, memberName, tossIfNotFound = false) {
          const m2 = __lookupMember(obj.structInfo, memberName, tossIfNotFound);
          return m2 && 1 === m2.signature.length && "s" === m2.signature[0] ? m2 : false;
        };
        const __affirmCStringSignature = function(member) {
          if ("s" === member.signature)
            return;
          toss(
            "Invalid member type signature for C-string value:",
            JSON.stringify(member)
          );
        };
        const __memberToJsString = function f2(obj, memberName) {
          const m2 = __lookupMember(obj.structInfo, memberName, true);
          __affirmCStringSignature(m2);
          const addr = obj[m2.key];
          if (!addr)
            return null;
          let pos = addr;
          const mem = heap();
          for (; mem[pos] !== 0; ++pos) {
          }
          return addr === pos ? "" : __utf8Decode(mem, addr, pos);
        };
        const __addOnDispose = function(obj, ...v3) {
          if (obj.ondispose) {
            if (!Array.isArray(obj.ondispose)) {
              obj.ondispose = [obj.ondispose];
            }
          } else {
            obj.ondispose = [];
          }
          obj.ondispose.push(...v3);
        };
        const __allocCString = function(str) {
          const u3 = __utf8Encoder.encode(str);
          const mem = alloc(u3.length + 1);
          if (!mem)
            toss("Allocation error while duplicating string:", str);
          const h2 = heap();
          h2.set(u3, mem);
          h2[mem + u3.length] = 0;
          return mem;
        };
        const __setMemberCString = function(obj, memberName, str) {
          const m2 = __lookupMember(obj.structInfo, memberName, true);
          __affirmCStringSignature(m2);
          const mem = __allocCString(str);
          obj[m2.key] = mem;
          __addOnDispose(obj, mem);
          return obj;
        };
        const StructType = function ctor(structName, structInfo) {
          if (arguments[2] !== rop) {
            toss(
              "Do not call the StructType constructor",
              "from client-level code."
            );
          }
          Object.defineProperties(this, {
            structName: rop(structName),
            structInfo: rop(structInfo)
          });
        };
        StructType.prototype = Object.create(null, {
          dispose: rop(function() {
            __freeStruct(this.constructor, this);
          }),
          lookupMember: rop(function(memberName, tossIfNotFound = true) {
            return __lookupMember(this.structInfo, memberName, tossIfNotFound);
          }),
          memberToJsString: rop(function(memberName) {
            return __memberToJsString(this, memberName);
          }),
          memberIsString: rop(function(memberName, tossIfNotFound = true) {
            return __memberIsString(this, memberName, tossIfNotFound);
          }),
          memberKey: __memberKeyProp,
          memberKeys: __structMemberKeys,
          memberSignature: rop(function(memberName, emscriptenFormat = false) {
            return __memberSignature(this, memberName, emscriptenFormat);
          }),
          memoryDump: rop(__memoryDump),
          pointer: __ptrPropDescriptor,
          setMemberCString: rop(function(memberName, str) {
            return __setMemberCString(this, memberName, str);
          })
        });
        Object.assign(StructType.prototype, {
          addOnDispose: function(...v3) {
            __addOnDispose(this, ...v3);
            return this;
          }
        });
        Object.defineProperties(StructType, {
          allocCString: rop(__allocCString),
          isA: rop((v3) => v3 instanceof StructType),
          hasExternalPointer: rop(
            (v3) => v3 instanceof StructType && !!v3[xPtrPropName]
          ),
          memberKey: __memberKeyProp
        });
        const isNumericValue = (v3) => Number.isFinite(v3) || v3 instanceof (BigInt2 || Number);
        const makeMemberWrapper = function f2(ctor, name, descr) {
          if (!f2._) {
            f2._ = { getters: {}, setters: {}, sw: {} };
            const a3 = ["i", "c", "C", "p", "P", "s", "f", "d", "v()"];
            if (bigIntEnabled)
              a3.push("j");
            a3.forEach(function(v3) {
              f2._.getters[v3] = sigDVGetter(v3);
              f2._.setters[v3] = sigDVSetter(v3);
              f2._.sw[v3] = sigDVSetWrapper(v3);
            });
            const rxSig1 = /^[ipPsjfdcC]$/, rxSig2 = /^[vipPsjfdcC]\([ipPsjfdcC]*\)$/;
            f2.sigCheck = function(obj, name2, key2, sig) {
              if (Object.prototype.hasOwnProperty.call(obj, key2)) {
                toss(obj.structName, "already has a property named", key2 + ".");
              }
              rxSig1.test(sig) || rxSig2.test(sig) || toss(
                "Malformed signature for",
                sPropName(obj.structName, name2) + ":",
                sig
              );
            };
          }
          const key = ctor.memberKey(name);
          f2.sigCheck(ctor.prototype, name, key, descr.signature);
          descr.key = key;
          descr.name = name;
          const sigGlyph = sigLetter(descr.signature);
          const xPropName = sPropName(ctor.prototype.structName, key);
          const dbg = ctor.prototype.debugFlags.__flags;
          const prop = /* @__PURE__ */ Object.create(null);
          prop.configurable = false;
          prop.enumerable = false;
          prop.get = function() {
            if (dbg.getter) {
              log2(
                "debug.getter:",
                f2._.getters[sigGlyph],
                "for",
                sigIR(sigGlyph),
                xPropName,
                "@",
                this.pointer,
                "+",
                descr.offset,
                "sz",
                descr.sizeof
              );
            }
            let rc = new DataView(
              heap().buffer,
              this.pointer + descr.offset,
              descr.sizeof
            )[f2._.getters[sigGlyph]](0, isLittleEndian);
            if (dbg.getter)
              log2("debug.getter:", xPropName, "result =", rc);
            return rc;
          };
          if (descr.readOnly) {
            prop.set = __propThrowOnSet(ctor.prototype.structName, key);
          } else {
            prop.set = function(v3) {
              if (dbg.setter) {
                log2(
                  "debug.setter:",
                  f2._.setters[sigGlyph],
                  "for",
                  sigIR(sigGlyph),
                  xPropName,
                  "@",
                  this.pointer,
                  "+",
                  descr.offset,
                  "sz",
                  descr.sizeof,
                  v3
                );
              }
              if (!this.pointer) {
                toss("Cannot set struct property on disposed instance.");
              }
              if (null === v3)
                v3 = 0;
              else
                while (!isNumericValue(v3)) {
                  if (isAutoPtrSig(descr.signature) && v3 instanceof StructType) {
                    v3 = v3.pointer || 0;
                    if (dbg.setter)
                      log2("debug.setter:", xPropName, "resolved to", v3);
                    break;
                  }
                  toss("Invalid value for pointer-type", xPropName + ".");
                }
              new DataView(
                heap().buffer,
                this.pointer + descr.offset,
                descr.sizeof
              )[f2._.setters[sigGlyph]](0, f2._.sw[sigGlyph](v3), isLittleEndian);
            };
          }
          Object.defineProperty(ctor.prototype, key, prop);
        };
        const StructBinder = function StructBinder2(structName, structInfo) {
          if (1 === arguments.length) {
            structInfo = structName;
            structName = structInfo.name;
          } else if (!structInfo.name) {
            structInfo.name = structName;
          }
          if (!structName)
            toss("Struct name is required.");
          let lastMember = false;
          Object.keys(structInfo.members).forEach((k2) => {
            const m2 = structInfo.members[k2];
            if (!m2.sizeof)
              toss(structName, "member", k2, "is missing sizeof.");
            else if (m2.sizeof === 1) {
              m2.signature === "c" || m2.signature === "C" || toss(
                "Unexpected sizeof==1 member",
                sPropName(structInfo.name, k2),
                "with signature",
                m2.signature
              );
            } else {
              if (0 !== m2.sizeof % 4) {
                console.warn(
                  "Invalid struct member description =",
                  m2,
                  "from",
                  structInfo
                );
                toss(
                  structName,
                  "member",
                  k2,
                  "sizeof is not aligned. sizeof=" + m2.sizeof
                );
              }
              if (0 !== m2.offset % 4) {
                console.warn(
                  "Invalid struct member description =",
                  m2,
                  "from",
                  structInfo
                );
                toss(
                  structName,
                  "member",
                  k2,
                  "offset is not aligned. offset=" + m2.offset
                );
              }
            }
            if (!lastMember || lastMember.offset < m2.offset)
              lastMember = m2;
          });
          if (!lastMember)
            toss("No member property descriptions found.");
          else if (structInfo.sizeof < lastMember.offset + lastMember.sizeof) {
            toss(
              "Invalid struct config:",
              structName,
              "max member offset (" + lastMember.offset + ") ",
              "extends past end of struct (sizeof=" + structInfo.sizeof + ")."
            );
          }
          const debugFlags = rop(SBF.__makeDebugFlags(StructBinder2.debugFlags));
          const StructCtor = function StructCtor2(externalMemory) {
            if (!(this instanceof StructCtor2)) {
              toss(
                "The",
                structName,
                "constructor may only be called via 'new'."
              );
            } else if (arguments.length) {
              if (externalMemory !== (externalMemory | 0) || externalMemory <= 0) {
                toss("Invalid pointer value for", structName, "constructor.");
              }
              __allocStruct(StructCtor2, this, externalMemory);
            } else {
              __allocStruct(StructCtor2, this);
            }
          };
          Object.defineProperties(StructCtor, {
            debugFlags,
            isA: rop((v3) => v3 instanceof StructCtor),
            memberKey: __memberKeyProp,
            memberKeys: __structMemberKeys,
            methodInfoForKey: rop(function(mKey) {
            }),
            structInfo: rop(structInfo),
            structName: rop(structName)
          });
          StructCtor.prototype = new StructType(structName, structInfo, rop);
          Object.defineProperties(StructCtor.prototype, {
            debugFlags,
            constructor: rop(StructCtor)
          });
          Object.keys(structInfo.members).forEach(
            (name) => makeMemberWrapper(StructCtor, name, structInfo.members[name])
          );
          return StructCtor;
        };
        StructBinder.StructType = StructType;
        StructBinder.config = config;
        StructBinder.allocCString = __allocCString;
        if (!StructBinder.debugFlags) {
          StructBinder.debugFlags = SBF.__makeDebugFlags(SBF.debugFlags);
        }
        return StructBinder;
      };
      globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite32) {
        "use strict";
        const toss = (...args) => {
          throw new Error(args.join(" "));
        };
        const toss3 = sqlite32.SQLite3Error.toss;
        const capi = sqlite32.capi, wasm = sqlite32.wasm, util = sqlite32.util;
        globalThis.WhWasmUtilInstaller(wasm);
        delete globalThis.WhWasmUtilInstaller;
        if (0) {
          const dealloc = wasm.exports[sqlite32.config.deallocExportName];
          const nFunc = wasm.functionTable().length;
          let i2;
          for (i2 = 0; i2 < nFunc; ++i2) {
            const e2 = wasm.functionEntry(i2);
            if (dealloc === e2) {
              capi.SQLITE_WASM_DEALLOC = i2;
              break;
            }
          }
          if (dealloc !== wasm.functionEntry(capi.SQLITE_WASM_DEALLOC)) {
            toss(
              "Internal error: cannot find function pointer for SQLITE_WASM_DEALLOC."
            );
          }
        }
        wasm.bindingSignatures = [
          ["sqlite3_aggregate_context", "void*", "sqlite3_context*", "int"],
          ["sqlite3_bind_double", "int", "sqlite3_stmt*", "int", "f64"],
          ["sqlite3_bind_int", "int", "sqlite3_stmt*", "int", "int"],
          ["sqlite3_bind_null", void 0, "sqlite3_stmt*", "int"],
          ["sqlite3_bind_parameter_count", "int", "sqlite3_stmt*"],
          ["sqlite3_bind_parameter_index", "int", "sqlite3_stmt*", "string"],
          ["sqlite3_bind_parameter_name", "string", "sqlite3_stmt*", "int"],
          [
            "sqlite3_bind_pointer",
            "int",
            "sqlite3_stmt*",
            "int",
            "*",
            "string:static",
            "*"
          ],
          [
            "sqlite3_busy_handler",
            "int",
            [
              "sqlite3*",
              new wasm.xWrap.FuncPtrAdapter({
                signature: "i(pi)",
                contextKey: (argv2, argIndex) => argv2[0]
              }),
              "*"
            ]
          ],
          ["sqlite3_busy_timeout", "int", "sqlite3*", "int"],
          ["sqlite3_changes", "int", "sqlite3*"],
          ["sqlite3_clear_bindings", "int", "sqlite3_stmt*"],
          ["sqlite3_collation_needed", "int", "sqlite3*", "*", "*"],
          ["sqlite3_column_blob", "*", "sqlite3_stmt*", "int"],
          ["sqlite3_column_bytes", "int", "sqlite3_stmt*", "int"],
          ["sqlite3_column_count", "int", "sqlite3_stmt*"],
          ["sqlite3_column_decltype", "string", "sqlite3_stmt*", "int"],
          ["sqlite3_column_double", "f64", "sqlite3_stmt*", "int"],
          ["sqlite3_column_int", "int", "sqlite3_stmt*", "int"],
          ["sqlite3_column_name", "string", "sqlite3_stmt*", "int"],
          ["sqlite3_column_text", "string", "sqlite3_stmt*", "int"],
          ["sqlite3_column_type", "int", "sqlite3_stmt*", "int"],
          ["sqlite3_column_value", "sqlite3_value*", "sqlite3_stmt*", "int"],
          [
            "sqlite3_commit_hook",
            "void*",
            [
              "sqlite3*",
              new wasm.xWrap.FuncPtrAdapter({
                name: "sqlite3_commit_hook",
                signature: "i(p)",
                contextKey: (argv2) => argv2[0]
              }),
              "*"
            ]
          ],
          ["sqlite3_compileoption_get", "string", "int"],
          ["sqlite3_compileoption_used", "int", "string"],
          ["sqlite3_complete", "int", "string:flexible"],
          ["sqlite3_context_db_handle", "sqlite3*", "sqlite3_context*"],
          ["sqlite3_data_count", "int", "sqlite3_stmt*"],
          ["sqlite3_db_filename", "string", "sqlite3*", "string"],
          ["sqlite3_db_handle", "sqlite3*", "sqlite3_stmt*"],
          ["sqlite3_db_name", "string", "sqlite3*", "int"],
          ["sqlite3_db_readonly", "int", "sqlite3*", "string"],
          ["sqlite3_db_status", "int", "sqlite3*", "int", "*", "*", "int"],
          ["sqlite3_errcode", "int", "sqlite3*"],
          ["sqlite3_errmsg", "string", "sqlite3*"],
          ["sqlite3_error_offset", "int", "sqlite3*"],
          ["sqlite3_errstr", "string", "int"],
          [
            "sqlite3_exec",
            "int",
            [
              "sqlite3*",
              "string:flexible",
              new wasm.xWrap.FuncPtrAdapter({
                signature: "i(pipp)",
                bindScope: "transient",
                callProxy: (callback) => {
                  let aNames;
                  return (pVoid, nCols, pColVals, pColNames) => {
                    try {
                      const aVals = wasm.cArgvToJs(nCols, pColVals);
                      if (!aNames)
                        aNames = wasm.cArgvToJs(nCols, pColNames);
                      return callback(aVals, aNames) | 0;
                    } catch (e2) {
                      return e2.resultCode || capi.SQLITE_ERROR;
                    }
                  };
                }
              }),
              "*",
              "**"
            ]
          ],
          ["sqlite3_expanded_sql", "string", "sqlite3_stmt*"],
          ["sqlite3_extended_errcode", "int", "sqlite3*"],
          ["sqlite3_extended_result_codes", "int", "sqlite3*", "int"],
          ["sqlite3_file_control", "int", "sqlite3*", "string", "int", "*"],
          ["sqlite3_finalize", "int", "sqlite3_stmt*"],
          ["sqlite3_free", void 0, "*"],
          ["sqlite3_get_autocommit", "int", "sqlite3*"],
          ["sqlite3_get_auxdata", "*", "sqlite3_context*", "int"],
          ["sqlite3_initialize", void 0],
          ["sqlite3_interrupt", void 0, "sqlite3*"],
          ["sqlite3_is_interrupted", "int", "sqlite3*"],
          ["sqlite3_keyword_count", "int"],
          ["sqlite3_keyword_name", "int", ["int", "**", "*"]],
          ["sqlite3_keyword_check", "int", ["string", "int"]],
          ["sqlite3_libversion", "string"],
          ["sqlite3_libversion_number", "int"],
          ["sqlite3_limit", "int", ["sqlite3*", "int", "int"]],
          ["sqlite3_malloc", "*", "int"],
          ["sqlite3_open", "int", "string", "*"],
          ["sqlite3_open_v2", "int", "string", "*", "int", "string"],
          ["sqlite3_realloc", "*", "*", "int"],
          ["sqlite3_reset", "int", "sqlite3_stmt*"],
          [
            "sqlite3_result_blob",
            void 0,
            "sqlite3_context*",
            "*",
            "int",
            "*"
          ],
          ["sqlite3_result_double", void 0, "sqlite3_context*", "f64"],
          [
            "sqlite3_result_error",
            void 0,
            "sqlite3_context*",
            "string",
            "int"
          ],
          ["sqlite3_result_error_code", void 0, "sqlite3_context*", "int"],
          ["sqlite3_result_error_nomem", void 0, "sqlite3_context*"],
          ["sqlite3_result_error_toobig", void 0, "sqlite3_context*"],
          ["sqlite3_result_int", void 0, "sqlite3_context*", "int"],
          ["sqlite3_result_null", void 0, "sqlite3_context*"],
          [
            "sqlite3_result_pointer",
            void 0,
            "sqlite3_context*",
            "*",
            "string:static",
            "*"
          ],
          ["sqlite3_result_subtype", void 0, "sqlite3_value*", "int"],
          [
            "sqlite3_result_text",
            void 0,
            "sqlite3_context*",
            "string",
            "int",
            "*"
          ],
          ["sqlite3_result_zeroblob", void 0, "sqlite3_context*", "int"],
          [
            "sqlite3_rollback_hook",
            "void*",
            [
              "sqlite3*",
              new wasm.xWrap.FuncPtrAdapter({
                name: "sqlite3_rollback_hook",
                signature: "v(p)",
                contextKey: (argv2) => argv2[0]
              }),
              "*"
            ]
          ],
          [
            "sqlite3_set_auxdata",
            void 0,
            [
              "sqlite3_context*",
              "int",
              "*",
              new wasm.xWrap.FuncPtrAdapter({
                name: "xDestroyAuxData",
                signature: "v(*)",
                contextKey: (argv2, argIndex) => argv2[0]
              })
            ]
          ],
          ["sqlite3_shutdown", void 0],
          ["sqlite3_sourceid", "string"],
          ["sqlite3_sql", "string", "sqlite3_stmt*"],
          ["sqlite3_status", "int", "int", "*", "*", "int"],
          ["sqlite3_step", "int", "sqlite3_stmt*"],
          ["sqlite3_stmt_busy", "int", "sqlite3_stmt*"],
          ["sqlite3_stmt_readonly", "int", "sqlite3_stmt*"],
          ["sqlite3_stmt_status", "int", "sqlite3_stmt*", "int", "int"],
          ["sqlite3_strglob", "int", "string", "string"],
          ["sqlite3_stricmp", "int", "string", "string"],
          ["sqlite3_strlike", "int", "string", "string", "int"],
          ["sqlite3_strnicmp", "int", "string", "string", "int"],
          [
            "sqlite3_table_column_metadata",
            "int",
            "sqlite3*",
            "string",
            "string",
            "string",
            "**",
            "**",
            "*",
            "*",
            "*"
          ],
          ["sqlite3_total_changes", "int", "sqlite3*"],
          [
            "sqlite3_trace_v2",
            "int",
            [
              "sqlite3*",
              "int",
              new wasm.xWrap.FuncPtrAdapter({
                name: "sqlite3_trace_v2::callback",
                signature: "i(ippp)",
                contextKey: (argv2, argIndex) => argv2[0]
              }),
              "*"
            ]
          ],
          ["sqlite3_txn_state", "int", ["sqlite3*", "string"]],
          ["sqlite3_uri_boolean", "int", "sqlite3_filename", "string", "int"],
          ["sqlite3_uri_key", "string", "sqlite3_filename", "int"],
          ["sqlite3_uri_parameter", "string", "sqlite3_filename", "string"],
          ["sqlite3_user_data", "void*", "sqlite3_context*"],
          ["sqlite3_value_blob", "*", "sqlite3_value*"],
          ["sqlite3_value_bytes", "int", "sqlite3_value*"],
          ["sqlite3_value_double", "f64", "sqlite3_value*"],
          ["sqlite3_value_dup", "sqlite3_value*", "sqlite3_value*"],
          ["sqlite3_value_free", void 0, "sqlite3_value*"],
          ["sqlite3_value_frombind", "int", "sqlite3_value*"],
          ["sqlite3_value_int", "int", "sqlite3_value*"],
          ["sqlite3_value_nochange", "int", "sqlite3_value*"],
          ["sqlite3_value_numeric_type", "int", "sqlite3_value*"],
          ["sqlite3_value_pointer", "*", "sqlite3_value*", "string:static"],
          ["sqlite3_value_subtype", "int", "sqlite3_value*"],
          ["sqlite3_value_text", "string", "sqlite3_value*"],
          ["sqlite3_value_type", "int", "sqlite3_value*"],
          ["sqlite3_vfs_find", "*", "string"],
          ["sqlite3_vfs_register", "int", "sqlite3_vfs*", "int"],
          ["sqlite3_vfs_unregister", "int", "sqlite3_vfs*"]
        ];
        if (!!wasm.exports.sqlite3_progress_handler) {
          wasm.bindingSignatures.push([
            "sqlite3_progress_handler",
            void 0,
            [
              "sqlite3*",
              "int",
              new wasm.xWrap.FuncPtrAdapter({
                name: "xProgressHandler",
                signature: "i(p)",
                bindScope: "context",
                contextKey: (argv2, argIndex) => argv2[0]
              }),
              "*"
            ]
          ]);
        }
        if (!!wasm.exports.sqlite3_stmt_explain) {
          wasm.bindingSignatures.push(
            ["sqlite3_stmt_explain", "int", "sqlite3_stmt*", "int"],
            ["sqlite3_stmt_isexplain", "int", "sqlite3_stmt*"]
          );
        }
        if (!!wasm.exports.sqlite3_set_authorizer) {
          wasm.bindingSignatures.push([
            "sqlite3_set_authorizer",
            "int",
            [
              "sqlite3*",
              new wasm.xWrap.FuncPtrAdapter({
                name: "sqlite3_set_authorizer::xAuth",
                signature: "i(pissss)",
                contextKey: (argv2, argIndex) => argv2[0],
                callProxy: (callback) => {
                  return (pV, iCode, s0, s1, s2, s3) => {
                    try {
                      s0 = s0 && wasm.cstrToJs(s0);
                      s1 = s1 && wasm.cstrToJs(s1);
                      s2 = s2 && wasm.cstrToJs(s2);
                      s3 = s3 && wasm.cstrToJs(s3);
                      return callback(pV, iCode, s0, s1, s2, s3) || 0;
                    } catch (e2) {
                      return e2.resultCode || capi.SQLITE_ERROR;
                    }
                  };
                }
              }),
              "*"
            ]
          ]);
        }
        if (false) {
          wasm.bindingSignatures.push([
            "sqlite3_normalized_sql",
            "string",
            "sqlite3_stmt*"
          ]);
        }
        wasm.bindingSignatures.int64 = [
          ["sqlite3_bind_int64", "int", ["sqlite3_stmt*", "int", "i64"]],
          ["sqlite3_changes64", "i64", ["sqlite3*"]],
          ["sqlite3_column_int64", "i64", ["sqlite3_stmt*", "int"]],
          [
            "sqlite3_deserialize",
            "int",
            "sqlite3*",
            "string",
            "*",
            "i64",
            "i64",
            "int"
          ],
          ["sqlite3_last_insert_rowid", "i64", ["sqlite3*"]],
          ["sqlite3_malloc64", "*", "i64"],
          ["sqlite3_msize", "i64", "*"],
          ["sqlite3_overload_function", "int", ["sqlite3*", "string", "int"]],
          ["sqlite3_realloc64", "*", "*", "i64"],
          ["sqlite3_result_int64", void 0, "*", "i64"],
          ["sqlite3_result_zeroblob64", "int", "*", "i64"],
          ["sqlite3_serialize", "*", "sqlite3*", "string", "*", "int"],
          ["sqlite3_set_last_insert_rowid", void 0, ["sqlite3*", "i64"]],
          ["sqlite3_status64", "int", "int", "*", "*", "int"],
          ["sqlite3_total_changes64", "i64", ["sqlite3*"]],
          [
            "sqlite3_update_hook",
            "*",
            [
              "sqlite3*",
              new wasm.xWrap.FuncPtrAdapter({
                name: "sqlite3_update_hook",
                signature: "v(iippj)",
                contextKey: (argv2) => argv2[0],
                callProxy: (callback) => {
                  return (p3, op, z0, z1, rowid) => {
                    callback(
                      p3,
                      op,
                      wasm.cstrToJs(z0),
                      wasm.cstrToJs(z1),
                      rowid
                    );
                  };
                }
              }),
              "*"
            ]
          ],
          ["sqlite3_uri_int64", "i64", ["sqlite3_filename", "string", "i64"]],
          ["sqlite3_value_int64", "i64", "sqlite3_value*"]
        ];
        if (wasm.bigIntEnabled && !!wasm.exports.sqlite3_declare_vtab) {
          wasm.bindingSignatures.int64.push(
            [
              "sqlite3_create_module",
              "int",
              ["sqlite3*", "string", "sqlite3_module*", "*"]
            ],
            [
              "sqlite3_create_module_v2",
              "int",
              ["sqlite3*", "string", "sqlite3_module*", "*", "*"]
            ],
            ["sqlite3_declare_vtab", "int", ["sqlite3*", "string:flexible"]],
            ["sqlite3_drop_modules", "int", ["sqlite3*", "**"]],
            ["sqlite3_vtab_collation", "string", "sqlite3_index_info*", "int"],
            ["sqlite3_vtab_distinct", "int", "sqlite3_index_info*"],
            ["sqlite3_vtab_in", "int", "sqlite3_index_info*", "int", "int"],
            ["sqlite3_vtab_in_first", "int", "sqlite3_value*", "**"],
            ["sqlite3_vtab_in_next", "int", "sqlite3_value*", "**"],
            ["sqlite3_vtab_nochange", "int", "sqlite3_context*"],
            ["sqlite3_vtab_on_conflict", "int", "sqlite3*"],
            [
              "sqlite3_vtab_rhs_value",
              "int",
              "sqlite3_index_info*",
              "int",
              "**"
            ]
          );
        }
        if (wasm.bigIntEnabled && !!wasm.exports.sqlite3_preupdate_hook) {
          wasm.bindingSignatures.int64.push(
            ["sqlite3_preupdate_blobwrite", "int", "sqlite3*"],
            ["sqlite3_preupdate_count", "int", "sqlite3*"],
            ["sqlite3_preupdate_depth", "int", "sqlite3*"],
            [
              "sqlite3_preupdate_hook",
              "*",
              [
                "sqlite3*",
                new wasm.xWrap.FuncPtrAdapter({
                  name: "sqlite3_preupdate_hook",
                  signature: "v(ppippjj)",
                  contextKey: (argv2) => argv2[0],
                  callProxy: (callback) => {
                    return (p3, db, op, zDb, zTbl, iKey1, iKey2) => {
                      callback(
                        p3,
                        db,
                        op,
                        wasm.cstrToJs(zDb),
                        wasm.cstrToJs(zTbl),
                        iKey1,
                        iKey2
                      );
                    };
                  }
                }),
                "*"
              ]
            ],
            ["sqlite3_preupdate_new", "int", ["sqlite3*", "int", "**"]],
            ["sqlite3_preupdate_old", "int", ["sqlite3*", "int", "**"]]
          );
        }
        if (wasm.bigIntEnabled && !!wasm.exports.sqlite3changegroup_add && !!wasm.exports.sqlite3session_create && !!wasm.exports.sqlite3_preupdate_hook) {
          const __ipsProxy = {
            signature: "i(ps)",
            callProxy: (callback) => {
              return (p3, s2) => {
                try {
                  return callback(p3, wasm.cstrToJs(s2)) | 0;
                } catch (e2) {
                  return e2.resultCode || capi.SQLITE_ERROR;
                }
              };
            }
          };
          wasm.bindingSignatures.int64.push(
            ...[
              [
                "sqlite3changegroup_add",
                "int",
                ["sqlite3_changegroup*", "int", "void*"]
              ],
              [
                "sqlite3changegroup_add_strm",
                "int",
                [
                  "sqlite3_changegroup*",
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xInput",
                    signature: "i(ppp)",
                    bindScope: "transient"
                  }),
                  "void*"
                ]
              ],
              [
                "sqlite3changegroup_delete",
                void 0,
                ["sqlite3_changegroup*"]
              ],
              ["sqlite3changegroup_new", "int", ["**"]],
              [
                "sqlite3changegroup_output",
                "int",
                ["sqlite3_changegroup*", "int*", "**"]
              ],
              [
                "sqlite3changegroup_output_strm",
                "int",
                [
                  "sqlite3_changegroup*",
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xOutput",
                    signature: "i(ppi)",
                    bindScope: "transient"
                  }),
                  "void*"
                ]
              ],
              [
                "sqlite3changeset_apply",
                "int",
                [
                  "sqlite3*",
                  "int",
                  "void*",
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xFilter",
                    bindScope: "transient",
                    ...__ipsProxy
                  }),
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xConflict",
                    signature: "i(pip)",
                    bindScope: "transient"
                  }),
                  "void*"
                ]
              ],
              [
                "sqlite3changeset_apply_strm",
                "int",
                [
                  "sqlite3*",
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xInput",
                    signature: "i(ppp)",
                    bindScope: "transient"
                  }),
                  "void*",
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xFilter",
                    bindScope: "transient",
                    ...__ipsProxy
                  }),
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xConflict",
                    signature: "i(pip)",
                    bindScope: "transient"
                  }),
                  "void*"
                ]
              ],
              [
                "sqlite3changeset_apply_v2",
                "int",
                [
                  "sqlite3*",
                  "int",
                  "void*",
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xFilter",
                    bindScope: "transient",
                    ...__ipsProxy
                  }),
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xConflict",
                    signature: "i(pip)",
                    bindScope: "transient"
                  }),
                  "void*",
                  "**",
                  "int*",
                  "int"
                ]
              ],
              [
                "sqlite3changeset_apply_v2_strm",
                "int",
                [
                  "sqlite3*",
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xInput",
                    signature: "i(ppp)",
                    bindScope: "transient"
                  }),
                  "void*",
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xFilter",
                    bindScope: "transient",
                    ...__ipsProxy
                  }),
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xConflict",
                    signature: "i(pip)",
                    bindScope: "transient"
                  }),
                  "void*",
                  "**",
                  "int*",
                  "int"
                ]
              ],
              [
                "sqlite3changeset_concat",
                "int",
                ["int", "void*", "int", "void*", "int*", "**"]
              ],
              [
                "sqlite3changeset_concat_strm",
                "int",
                [
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xInputA",
                    signature: "i(ppp)",
                    bindScope: "transient"
                  }),
                  "void*",
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xInputB",
                    signature: "i(ppp)",
                    bindScope: "transient"
                  }),
                  "void*",
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xOutput",
                    signature: "i(ppi)",
                    bindScope: "transient"
                  }),
                  "void*"
                ]
              ],
              [
                "sqlite3changeset_conflict",
                "int",
                ["sqlite3_changeset_iter*", "int", "**"]
              ],
              ["sqlite3changeset_finalize", "int", ["sqlite3_changeset_iter*"]],
              [
                "sqlite3changeset_fk_conflicts",
                "int",
                ["sqlite3_changeset_iter*", "int*"]
              ],
              [
                "sqlite3changeset_invert",
                "int",
                ["int", "void*", "int*", "**"]
              ],
              [
                "sqlite3changeset_invert_strm",
                "int",
                [
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xInput",
                    signature: "i(ppp)",
                    bindScope: "transient"
                  }),
                  "void*",
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xOutput",
                    signature: "i(ppi)",
                    bindScope: "transient"
                  }),
                  "void*"
                ]
              ],
              [
                "sqlite3changeset_new",
                "int",
                ["sqlite3_changeset_iter*", "int", "**"]
              ],
              ["sqlite3changeset_next", "int", ["sqlite3_changeset_iter*"]],
              [
                "sqlite3changeset_old",
                "int",
                ["sqlite3_changeset_iter*", "int", "**"]
              ],
              [
                "sqlite3changeset_op",
                "int",
                ["sqlite3_changeset_iter*", "**", "int*", "int*", "int*"]
              ],
              [
                "sqlite3changeset_pk",
                "int",
                ["sqlite3_changeset_iter*", "**", "int*"]
              ],
              ["sqlite3changeset_start", "int", ["**", "int", "*"]],
              [
                "sqlite3changeset_start_strm",
                "int",
                [
                  "**",
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xInput",
                    signature: "i(ppp)",
                    bindScope: "transient"
                  }),
                  "void*"
                ]
              ],
              ["sqlite3changeset_start_v2", "int", ["**", "int", "*", "int"]],
              [
                "sqlite3changeset_start_v2_strm",
                "int",
                [
                  "**",
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xInput",
                    signature: "i(ppp)",
                    bindScope: "transient"
                  }),
                  "void*",
                  "int"
                ]
              ],
              ["sqlite3session_attach", "int", ["sqlite3_session*", "string"]],
              [
                "sqlite3session_changeset",
                "int",
                ["sqlite3_session*", "int*", "**"]
              ],
              ["sqlite3session_changeset_size", "i64", ["sqlite3_session*"]],
              [
                "sqlite3session_changeset_strm",
                "int",
                [
                  "sqlite3_session*",
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xOutput",
                    signature: "i(ppp)",
                    bindScope: "transient"
                  }),
                  "void*"
                ]
              ],
              ["sqlite3session_config", "int", ["int", "void*"]],
              ["sqlite3session_create", "int", ["sqlite3*", "string", "**"]],
              [
                "sqlite3session_diff",
                "int",
                ["sqlite3_session*", "string", "string", "**"]
              ],
              ["sqlite3session_enable", "int", ["sqlite3_session*", "int"]],
              ["sqlite3session_indirect", "int", ["sqlite3_session*", "int"]],
              ["sqlite3session_isempty", "int", ["sqlite3_session*"]],
              ["sqlite3session_memory_used", "i64", ["sqlite3_session*"]],
              [
                "sqlite3session_object_config",
                "int",
                ["sqlite3_session*", "int", "void*"]
              ],
              [
                "sqlite3session_patchset",
                "int",
                ["sqlite3_session*", "*", "**"]
              ],
              [
                "sqlite3session_patchset_strm",
                "int",
                [
                  "sqlite3_session*",
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xOutput",
                    signature: "i(ppp)",
                    bindScope: "transient"
                  }),
                  "void*"
                ]
              ],
              [
                "sqlite3session_table_filter",
                void 0,
                [
                  "sqlite3_session*",
                  new wasm.xWrap.FuncPtrAdapter({
                    name: "xFilter",
                    ...__ipsProxy,
                    contextKey: (argv2, argIndex) => argv2[0]
                  }),
                  "*"
                ]
              ]
            ]
          );
        }
        wasm.bindingSignatures.wasmInternal = [
          ["sqlite3__wasm_db_reset", "int", "sqlite3*"],
          ["sqlite3__wasm_db_vfs", "sqlite3_vfs*", "sqlite3*", "string"],
          [
            "sqlite3__wasm_vfs_create_file",
            "int",
            "sqlite3_vfs*",
            "string",
            "*",
            "int"
          ],
          ["sqlite3__wasm_posix_create_file", "int", "string", "*", "int"],
          ["sqlite3__wasm_vfs_unlink", "int", "sqlite3_vfs*", "string"],
          ["sqlite3__wasm_qfmt_token", "string:dealloc", "string", "int"]
        ];
        sqlite32.StructBinder = globalThis.Jaccwabyt({
          heap: 0 ? wasm.memory : wasm.heap8u,
          alloc: wasm.alloc,
          dealloc: wasm.dealloc,
          bigIntEnabled: wasm.bigIntEnabled,
          memberPrefix: "$"
        });
        delete globalThis.Jaccwabyt;
        {
          const __xString = wasm.xWrap.argAdapter("string");
          wasm.xWrap.argAdapter(
            "string:flexible",
            (v3) => __xString(util.flexibleString(v3))
          );
          wasm.xWrap.argAdapter(
            "string:static",
            function(v3) {
              if (wasm.isPtr(v3))
                return v3;
              v3 = "" + v3;
              let rc = this[v3];
              return rc || (this[v3] = wasm.allocCString(v3));
            }.bind(/* @__PURE__ */ Object.create(null))
          );
          const __xArgPtr = wasm.xWrap.argAdapter("*");
          const nilType = function() {
          };
          wasm.xWrap.argAdapter("sqlite3_filename", __xArgPtr)(
            "sqlite3_context*",
            __xArgPtr
          )("sqlite3_value*", __xArgPtr)("void*", __xArgPtr)(
            "sqlite3_changegroup*",
            __xArgPtr
          )("sqlite3_changeset_iter*", __xArgPtr)(
            "sqlite3_session*",
            __xArgPtr
          )(
            "sqlite3_stmt*",
            (v3) => {
              var _a8;
              return __xArgPtr(
                v3 instanceof (((_a8 = sqlite32 == null ? void 0 : sqlite32.oo1) == null ? void 0 : _a8.Stmt) || nilType) ? v3.pointer : v3
              );
            }
          )(
            "sqlite3*",
            (v3) => {
              var _a8;
              return __xArgPtr(
                v3 instanceof (((_a8 = sqlite32 == null ? void 0 : sqlite32.oo1) == null ? void 0 : _a8.DB) || nilType) ? v3.pointer : v3
              );
            }
          )("sqlite3_vfs*", (v3) => {
            if ("string" === typeof v3) {
              return capi.sqlite3_vfs_find(v3) || sqlite32.SQLite3Error.toss(
                capi.SQLITE_NOTFOUND,
                "Unknown sqlite3_vfs name:",
                v3
              );
            }
            return __xArgPtr(
              v3 instanceof (capi.sqlite3_vfs || nilType) ? v3.pointer : v3
            );
          });
          if (wasm.exports.sqlite3_declare_vtab) {
            wasm.xWrap.argAdapter(
              "sqlite3_index_info*",
              (v3) => __xArgPtr(
                v3 instanceof (capi.sqlite3_index_info || nilType) ? v3.pointer : v3
              )
            )(
              "sqlite3_module*",
              (v3) => __xArgPtr(
                v3 instanceof (capi.sqlite3_module || nilType) ? v3.pointer : v3
              )
            );
          }
          const __xRcPtr = wasm.xWrap.resultAdapter("*");
          wasm.xWrap.resultAdapter("sqlite3*", __xRcPtr)(
            "sqlite3_context*",
            __xRcPtr
          )("sqlite3_stmt*", __xRcPtr)("sqlite3_value*", __xRcPtr)(
            "sqlite3_vfs*",
            __xRcPtr
          )("void*", __xRcPtr);
          if (0 === wasm.exports.sqlite3_step.length) {
            wasm.xWrap.doArgcCheck = false;
            sqlite32.config.warn(
              "Disabling sqlite3.wasm.xWrap.doArgcCheck due to environmental quirks."
            );
          }
          for (const e2 of wasm.bindingSignatures) {
            capi[e2[0]] = wasm.xWrap.apply(null, e2);
          }
          for (const e2 of wasm.bindingSignatures.wasmInternal) {
            util[e2[0]] = wasm.xWrap.apply(null, e2);
          }
          const fI64Disabled = function(fname) {
            return () => toss(
              fname + "() is unavailable due to lack",
              "of BigInt support in this build."
            );
          };
          for (const e2 of wasm.bindingSignatures.int64) {
            capi[e2[0]] = wasm.bigIntEnabled ? wasm.xWrap.apply(null, e2) : fI64Disabled(e2[0]);
          }
          delete wasm.bindingSignatures;
          if (wasm.exports.sqlite3__wasm_db_error) {
            const __db_err = wasm.xWrap(
              "sqlite3__wasm_db_error",
              "int",
              "sqlite3*",
              "int",
              "string"
            );
            util.sqlite3__wasm_db_error = function(pDb2, resultCode, message) {
              if (resultCode instanceof sqlite32.WasmAllocError) {
                resultCode = capi.SQLITE_NOMEM;
                message = 0;
              } else if (resultCode instanceof Error) {
                message = message || "" + resultCode;
                resultCode = resultCode.resultCode || capi.SQLITE_ERROR;
              }
              return pDb2 ? __db_err(pDb2, resultCode, message) : resultCode;
            };
          } else {
            util.sqlite3__wasm_db_error = function(pDb2, errCode, msg) {
              console.warn(
                "sqlite3__wasm_db_error() is not exported.",
                arguments
              );
              return errCode;
            };
          }
        }
        {
          const cJson = wasm.xCall("sqlite3__wasm_enum_json");
          if (!cJson) {
            toss(
              "Maintenance required: increase sqlite3__wasm_enum_json()'s",
              "static buffer size!"
            );
          }
          wasm.ctype = JSON.parse(wasm.cstrToJs(cJson));
          const defineGroups = [
            "access",
            "authorizer",
            "blobFinalizers",
            "changeset",
            "config",
            "dataTypes",
            "dbConfig",
            "dbStatus",
            "encodings",
            "fcntl",
            "flock",
            "ioCap",
            "limits",
            "openFlags",
            "prepareFlags",
            "resultCodes",
            "sqlite3Status",
            "stmtStatus",
            "syncFlags",
            "trace",
            "txnState",
            "udfFlags",
            "version"
          ];
          if (wasm.bigIntEnabled) {
            defineGroups.push("serialize", "session", "vtab");
          }
          for (const t2 of defineGroups) {
            for (const e2 of Object.entries(wasm.ctype[t2])) {
              capi[e2[0]] = e2[1];
            }
          }
          if (!wasm.functionEntry(capi.SQLITE_WASM_DEALLOC)) {
            toss(
              "Internal error: cannot resolve exported function",
              "entry SQLITE_WASM_DEALLOC (==" + capi.SQLITE_WASM_DEALLOC + ")."
            );
          }
          const __rcMap = /* @__PURE__ */ Object.create(null);
          for (const t2 of ["resultCodes"]) {
            for (const e2 of Object.entries(wasm.ctype[t2])) {
              __rcMap[e2[1]] = e2[0];
            }
          }
          capi.sqlite3_js_rc_str = (rc) => __rcMap[rc];
          const notThese = Object.assign(/* @__PURE__ */ Object.create(null), {
            WasmTestStruct: true,
            sqlite3_kvvfs_methods: !util.isUIThread(),
            sqlite3_index_info: !wasm.bigIntEnabled,
            sqlite3_index_constraint: !wasm.bigIntEnabled,
            sqlite3_index_orderby: !wasm.bigIntEnabled,
            sqlite3_index_constraint_usage: !wasm.bigIntEnabled
          });
          for (const s2 of wasm.ctype.structs) {
            if (!notThese[s2.name]) {
              capi[s2.name] = sqlite32.StructBinder(s2);
            }
          }
          if (capi.sqlite3_index_info) {
            for (const k2 of [
              "sqlite3_index_constraint",
              "sqlite3_index_orderby",
              "sqlite3_index_constraint_usage"
            ]) {
              capi.sqlite3_index_info[k2] = capi[k2];
              delete capi[k2];
            }
            capi.sqlite3_vtab_config = wasm.xWrap(
              "sqlite3__wasm_vtab_config",
              "int",
              ["sqlite3*", "int", "int"]
            );
          }
        }
        const __dbArgcMismatch = (pDb2, f2, n2) => {
          return util.sqlite3__wasm_db_error(
            pDb2,
            capi.SQLITE_MISUSE,
            f2 + "() requires " + n2 + " argument" + (1 === n2 ? "" : "s") + "."
          );
        };
        const __errEncoding = (pDb2) => {
          return util.sqlite3__wasm_db_error(
            pDb2,
            capi.SQLITE_FORMAT,
            "SQLITE_UTF8 is the only supported encoding."
          );
        };
        const __argPDb = (pDb2) => wasm.xWrap.argAdapter("sqlite3*")(pDb2);
        const __argStr = (str) => wasm.isPtr(str) ? wasm.cstrToJs(str) : str;
        const __dbCleanupMap = function(pDb2, mode) {
          pDb2 = __argPDb(pDb2);
          let m2 = this.dbMap.get(pDb2);
          if (!mode) {
            this.dbMap.delete(pDb2);
            return m2;
          } else if (!m2 && mode > 0) {
            this.dbMap.set(pDb2, m2 = /* @__PURE__ */ Object.create(null));
          }
          return m2;
        }.bind(
          Object.assign(/* @__PURE__ */ Object.create(null), {
            dbMap: /* @__PURE__ */ new Map()
          })
        );
        __dbCleanupMap.addCollation = function(pDb2, name) {
          const m2 = __dbCleanupMap(pDb2, 1);
          if (!m2.collation)
            m2.collation = /* @__PURE__ */ new Set();
          m2.collation.add(__argStr(name).toLowerCase());
        };
        __dbCleanupMap._addUDF = function(pDb2, name, arity, map) {
          name = __argStr(name).toLowerCase();
          let u3 = map.get(name);
          if (!u3)
            map.set(name, u3 = /* @__PURE__ */ new Set());
          u3.add(arity < 0 ? -1 : arity);
        };
        __dbCleanupMap.addFunction = function(pDb2, name, arity) {
          const m2 = __dbCleanupMap(pDb2, 1);
          if (!m2.udf)
            m2.udf = /* @__PURE__ */ new Map();
          this._addUDF(pDb2, name, arity, m2.udf);
        };
        if (wasm.exports.sqlite3_create_window_function) {
          __dbCleanupMap.addWindowFunc = function(pDb2, name, arity) {
            const m2 = __dbCleanupMap(pDb2, 1);
            if (!m2.wudf)
              m2.wudf = /* @__PURE__ */ new Map();
            this._addUDF(pDb2, name, arity, m2.wudf);
          };
        }
        __dbCleanupMap.cleanup = function(pDb2) {
          pDb2 = __argPDb(pDb2);
          const closeArgs = [pDb2];
          for (const name of [
            "sqlite3_busy_handler",
            "sqlite3_commit_hook",
            "sqlite3_preupdate_hook",
            "sqlite3_progress_handler",
            "sqlite3_rollback_hook",
            "sqlite3_set_authorizer",
            "sqlite3_trace_v2",
            "sqlite3_update_hook"
          ]) {
            const x2 = wasm.exports[name];
            if (!x2) {
              continue;
            }
            closeArgs.length = x2.length;
            try {
              capi[name](...closeArgs);
            } catch (e2) {
              sqlite32.config.warn(
                "close-time call of",
                name + "(",
                closeArgs,
                ") threw:",
                e2
              );
            }
          }
          const m2 = __dbCleanupMap(pDb2, 0);
          if (!m2)
            return;
          if (m2.collation) {
            for (const name of m2.collation) {
              try {
                capi.sqlite3_create_collation_v2(
                  pDb2,
                  name,
                  capi.SQLITE_UTF8,
                  0,
                  0,
                  0
                );
              } catch (e2) {
              }
            }
            delete m2.collation;
          }
          let i2;
          for (i2 = 0; i2 < 2; ++i2) {
            const fmap = i2 ? m2.wudf : m2.udf;
            if (!fmap)
              continue;
            const func = i2 ? capi.sqlite3_create_window_function : capi.sqlite3_create_function_v2;
            for (const e2 of fmap) {
              const name = e2[0], arities = e2[1];
              const fargs = [pDb2, name, 0, capi.SQLITE_UTF8, 0, 0, 0, 0, 0];
              if (i2)
                fargs.push(0);
              for (const arity of arities) {
                try {
                  fargs[2] = arity;
                  func.apply(null, fargs);
                } catch (e3) {
                }
              }
              arities.clear();
            }
            fmap.clear();
          }
          delete m2.udf;
          delete m2.wudf;
        };
        {
          const __sqlite3CloseV2 = wasm.xWrap(
            "sqlite3_close_v2",
            "int",
            "sqlite3*"
          );
          capi.sqlite3_close_v2 = function(pDb2) {
            if (1 !== arguments.length)
              return __dbArgcMismatch(pDb2, "sqlite3_close_v2", 1);
            if (pDb2) {
              try {
                __dbCleanupMap.cleanup(pDb2);
              } catch (e2) {
              }
            }
            return __sqlite3CloseV2(pDb2);
          };
        }
        if (capi.sqlite3session_create) {
          const __sqlite3SessionDelete = wasm.xWrap(
            "sqlite3session_delete",
            void 0,
            ["sqlite3_session*"]
          );
          capi.sqlite3session_delete = function(pSession) {
            if (1 !== arguments.length) {
              return __dbArgcMismatch(pDb, "sqlite3session_delete", 1);
            } else if (pSession) {
              capi.sqlite3session_table_filter(pSession, 0, 0);
            }
            __sqlite3SessionDelete(pSession);
          };
        }
        {
          const contextKey = (argv2, argIndex) => {
            return "argv[" + argIndex + "]:" + argv2[0] + ":" + wasm.cstrToJs(argv2[1]).toLowerCase();
          };
          const __sqlite3CreateCollationV2 = wasm.xWrap(
            "sqlite3_create_collation_v2",
            "int",
            [
              "sqlite3*",
              "string",
              "int",
              "*",
              new wasm.xWrap.FuncPtrAdapter({
                name: "xCompare",
                signature: "i(pipip)",
                contextKey
              }),
              new wasm.xWrap.FuncPtrAdapter({
                name: "xDestroy",
                signature: "v(p)",
                contextKey
              })
            ]
          );
          capi.sqlite3_create_collation_v2 = function(pDb2, zName, eTextRep, pArg, xCompare, xDestroy) {
            if (6 !== arguments.length)
              return __dbArgcMismatch(pDb2, "sqlite3_create_collation_v2", 6);
            else if (0 === (eTextRep & 15)) {
              eTextRep |= capi.SQLITE_UTF8;
            } else if (capi.SQLITE_UTF8 !== (eTextRep & 15)) {
              return __errEncoding(pDb2);
            }
            try {
              const rc = __sqlite3CreateCollationV2(
                pDb2,
                zName,
                eTextRep,
                pArg,
                xCompare,
                xDestroy
              );
              if (0 === rc && xCompare instanceof Function) {
                __dbCleanupMap.addCollation(pDb2, zName);
              }
              return rc;
            } catch (e2) {
              return util.sqlite3__wasm_db_error(pDb2, e2);
            }
          };
          capi.sqlite3_create_collation = (pDb2, zName, eTextRep, pArg, xCompare) => {
            return 5 === arguments.length ? capi.sqlite3_create_collation_v2(
              pDb2,
              zName,
              eTextRep,
              pArg,
              xCompare,
              0
            ) : __dbArgcMismatch(pDb2, "sqlite3_create_collation", 5);
          };
        }
        {
          const contextKey = function(argv2, argIndex) {
            return argv2[0] + ":" + (argv2[2] < 0 ? -1 : argv2[2]) + ":" + argIndex + ":" + wasm.cstrToJs(argv2[1]).toLowerCase();
          };
          const __cfProxy = Object.assign(/* @__PURE__ */ Object.create(null), {
            xInverseAndStep: {
              signature: "v(pip)",
              contextKey,
              callProxy: (callback) => {
                return (pCtx, argc, pArgv) => {
                  try {
                    callback(pCtx, ...capi.sqlite3_values_to_js(argc, pArgv));
                  } catch (e2) {
                    capi.sqlite3_result_error_js(pCtx, e2);
                  }
                };
              }
            },
            xFinalAndValue: {
              signature: "v(p)",
              contextKey,
              callProxy: (callback) => {
                return (pCtx) => {
                  try {
                    capi.sqlite3_result_js(pCtx, callback(pCtx));
                  } catch (e2) {
                    capi.sqlite3_result_error_js(pCtx, e2);
                  }
                };
              }
            },
            xFunc: {
              signature: "v(pip)",
              contextKey,
              callProxy: (callback) => {
                return (pCtx, argc, pArgv) => {
                  try {
                    capi.sqlite3_result_js(
                      pCtx,
                      callback(pCtx, ...capi.sqlite3_values_to_js(argc, pArgv))
                    );
                  } catch (e2) {
                    capi.sqlite3_result_error_js(pCtx, e2);
                  }
                };
              }
            },
            xDestroy: {
              signature: "v(p)",
              contextKey,
              callProxy: (callback) => {
                return (pVoid) => {
                  try {
                    callback(pVoid);
                  } catch (e2) {
                    console.error("UDF xDestroy method threw:", e2);
                  }
                };
              }
            }
          });
          const __sqlite3CreateFunction = wasm.xWrap(
            "sqlite3_create_function_v2",
            "int",
            [
              "sqlite3*",
              "string",
              "int",
              "int",
              "*",
              new wasm.xWrap.FuncPtrAdapter({
                name: "xFunc",
                ...__cfProxy.xFunc
              }),
              new wasm.xWrap.FuncPtrAdapter({
                name: "xStep",
                ...__cfProxy.xInverseAndStep
              }),
              new wasm.xWrap.FuncPtrAdapter({
                name: "xFinal",
                ...__cfProxy.xFinalAndValue
              }),
              new wasm.xWrap.FuncPtrAdapter({
                name: "xDestroy",
                ...__cfProxy.xDestroy
              })
            ]
          );
          const __sqlite3CreateWindowFunction = wasm.exports.sqlite3_create_window_function ? wasm.xWrap("sqlite3_create_window_function", "int", [
            "sqlite3*",
            "string",
            "int",
            "int",
            "*",
            new wasm.xWrap.FuncPtrAdapter({
              name: "xStep",
              ...__cfProxy.xInverseAndStep
            }),
            new wasm.xWrap.FuncPtrAdapter({
              name: "xFinal",
              ...__cfProxy.xFinalAndValue
            }),
            new wasm.xWrap.FuncPtrAdapter({
              name: "xValue",
              ...__cfProxy.xFinalAndValue
            }),
            new wasm.xWrap.FuncPtrAdapter({
              name: "xInverse",
              ...__cfProxy.xInverseAndStep
            }),
            new wasm.xWrap.FuncPtrAdapter({
              name: "xDestroy",
              ...__cfProxy.xDestroy
            })
          ]) : void 0;
          capi.sqlite3_create_function_v2 = function f2(pDb2, funcName, nArg, eTextRep, pApp, xFunc, xStep, xFinal, xDestroy) {
            if (f2.length !== arguments.length) {
              return __dbArgcMismatch(
                pDb2,
                "sqlite3_create_function_v2",
                f2.length
              );
            } else if (0 === (eTextRep & 15)) {
              eTextRep |= capi.SQLITE_UTF8;
            } else if (capi.SQLITE_UTF8 !== (eTextRep & 15)) {
              return __errEncoding(pDb2);
            }
            try {
              const rc = __sqlite3CreateFunction(
                pDb2,
                funcName,
                nArg,
                eTextRep,
                pApp,
                xFunc,
                xStep,
                xFinal,
                xDestroy
              );
              if (0 === rc && (xFunc instanceof Function || xStep instanceof Function || xFinal instanceof Function || xDestroy instanceof Function)) {
                __dbCleanupMap.addFunction(pDb2, funcName, nArg);
              }
              return rc;
            } catch (e2) {
              console.error("sqlite3_create_function_v2() setup threw:", e2);
              return util.sqlite3__wasm_db_error(
                pDb2,
                e2,
                "Creation of UDF threw: " + e2
              );
            }
          };
          capi.sqlite3_create_function = function f2(pDb2, funcName, nArg, eTextRep, pApp, xFunc, xStep, xFinal) {
            return f2.length === arguments.length ? capi.sqlite3_create_function_v2(
              pDb2,
              funcName,
              nArg,
              eTextRep,
              pApp,
              xFunc,
              xStep,
              xFinal,
              0
            ) : __dbArgcMismatch(pDb2, "sqlite3_create_function", f2.length);
          };
          if (__sqlite3CreateWindowFunction) {
            capi.sqlite3_create_window_function = function f2(pDb2, funcName, nArg, eTextRep, pApp, xStep, xFinal, xValue, xInverse, xDestroy) {
              if (f2.length !== arguments.length) {
                return __dbArgcMismatch(
                  pDb2,
                  "sqlite3_create_window_function",
                  f2.length
                );
              } else if (0 === (eTextRep & 15)) {
                eTextRep |= capi.SQLITE_UTF8;
              } else if (capi.SQLITE_UTF8 !== (eTextRep & 15)) {
                return __errEncoding(pDb2);
              }
              try {
                const rc = __sqlite3CreateWindowFunction(
                  pDb2,
                  funcName,
                  nArg,
                  eTextRep,
                  pApp,
                  xStep,
                  xFinal,
                  xValue,
                  xInverse,
                  xDestroy
                );
                if (0 === rc && (xStep instanceof Function || xFinal instanceof Function || xValue instanceof Function || xInverse instanceof Function || xDestroy instanceof Function)) {
                  __dbCleanupMap.addWindowFunc(pDb2, funcName, nArg);
                }
                return rc;
              } catch (e2) {
                console.error(
                  "sqlite3_create_window_function() setup threw:",
                  e2
                );
                return util.sqlite3__wasm_db_error(
                  pDb2,
                  e2,
                  "Creation of UDF threw: " + e2
                );
              }
            };
          } else {
            delete capi.sqlite3_create_window_function;
          }
          capi.sqlite3_create_function_v2.udfSetResult = capi.sqlite3_create_function.udfSetResult = capi.sqlite3_result_js;
          if (capi.sqlite3_create_window_function) {
            capi.sqlite3_create_window_function.udfSetResult = capi.sqlite3_result_js;
          }
          capi.sqlite3_create_function_v2.udfConvertArgs = capi.sqlite3_create_function.udfConvertArgs = capi.sqlite3_values_to_js;
          if (capi.sqlite3_create_window_function) {
            capi.sqlite3_create_window_function.udfConvertArgs = capi.sqlite3_values_to_js;
          }
          capi.sqlite3_create_function_v2.udfSetError = capi.sqlite3_create_function.udfSetError = capi.sqlite3_result_error_js;
          if (capi.sqlite3_create_window_function) {
            capi.sqlite3_create_window_function.udfSetError = capi.sqlite3_result_error_js;
          }
        }
        {
          const __flexiString = (v3, n2) => {
            if ("string" === typeof v3) {
              n2 = -1;
            } else if (util.isSQLableTypedArray(v3)) {
              n2 = v3.byteLength;
              v3 = util.typedArrayToString(
                v3 instanceof ArrayBuffer ? new Uint8Array(v3) : v3
              );
            } else if (Array.isArray(v3)) {
              v3 = v3.join("");
              n2 = -1;
            }
            return [v3, n2];
          };
          const __prepare = {
            basic: wasm.xWrap("sqlite3_prepare_v3", "int", [
              "sqlite3*",
              "string",
              "int",
              "int",
              "**",
              "**"
            ]),
            full: wasm.xWrap("sqlite3_prepare_v3", "int", [
              "sqlite3*",
              "*",
              "int",
              "int",
              "**",
              "**"
            ])
          };
          capi.sqlite3_prepare_v3 = function f2(pDb2, sql2, sqlLen, prepFlags, ppStmt, pzTail) {
            if (f2.length !== arguments.length) {
              return __dbArgcMismatch(pDb2, "sqlite3_prepare_v3", f2.length);
            }
            const [xSql, xSqlLen] = __flexiString(sql2, sqlLen);
            switch (typeof xSql) {
              case "string":
                return __prepare.basic(
                  pDb2,
                  xSql,
                  xSqlLen,
                  prepFlags,
                  ppStmt,
                  null
                );
              case "number":
                return __prepare.full(
                  pDb2,
                  xSql,
                  xSqlLen,
                  prepFlags,
                  ppStmt,
                  pzTail
                );
              default:
                return util.sqlite3__wasm_db_error(
                  pDb2,
                  capi.SQLITE_MISUSE,
                  "Invalid SQL argument type for sqlite3_prepare_v2/v3()."
                );
            }
          };
          capi.sqlite3_prepare_v2 = function f2(pDb2, sql2, sqlLen, ppStmt, pzTail) {
            return f2.length === arguments.length ? capi.sqlite3_prepare_v3(pDb2, sql2, sqlLen, 0, ppStmt, pzTail) : __dbArgcMismatch(pDb2, "sqlite3_prepare_v2", f2.length);
          };
        }
        {
          const __bindText = wasm.xWrap("sqlite3_bind_text", "int", [
            "sqlite3_stmt*",
            "int",
            "string",
            "int",
            "*"
          ]);
          const __bindBlob = wasm.xWrap("sqlite3_bind_blob", "int", [
            "sqlite3_stmt*",
            "int",
            "*",
            "int",
            "*"
          ]);
          capi.sqlite3_bind_text = function f2(pStmt, iCol, text, nText, xDestroy) {
            if (f2.length !== arguments.length) {
              return __dbArgcMismatch(
                capi.sqlite3_db_handle(pStmt),
                "sqlite3_bind_text",
                f2.length
              );
            } else if (wasm.isPtr(text) || null === text) {
              return __bindText(pStmt, iCol, text, nText, xDestroy);
            } else if (text instanceof ArrayBuffer) {
              text = new Uint8Array(text);
            } else if (Array.isArray(pMem)) {
              text = pMem.join("");
            }
            let p3, n2;
            try {
              if (util.isSQLableTypedArray(text)) {
                p3 = wasm.allocFromTypedArray(text);
                n2 = text.byteLength;
              } else if ("string" === typeof text) {
                [p3, n2] = wasm.allocCString(text);
              } else {
                return util.sqlite3__wasm_db_error(
                  capi.sqlite3_db_handle(pStmt),
                  capi.SQLITE_MISUSE,
                  "Invalid 3rd argument type for sqlite3_bind_text()."
                );
              }
              return __bindText(pStmt, iCol, p3, n2, capi.SQLITE_WASM_DEALLOC);
            } catch (e2) {
              wasm.dealloc(p3);
              return util.sqlite3__wasm_db_error(
                capi.sqlite3_db_handle(pStmt),
                e2
              );
            }
          };
          capi.sqlite3_bind_blob = function f2(pStmt, iCol, pMem2, nMem, xDestroy) {
            if (f2.length !== arguments.length) {
              return __dbArgcMismatch(
                capi.sqlite3_db_handle(pStmt),
                "sqlite3_bind_blob",
                f2.length
              );
            } else if (wasm.isPtr(pMem2) || null === pMem2) {
              return __bindBlob(pStmt, iCol, pMem2, nMem, xDestroy);
            } else if (pMem2 instanceof ArrayBuffer) {
              pMem2 = new Uint8Array(pMem2);
            } else if (Array.isArray(pMem2)) {
              pMem2 = pMem2.join("");
            }
            let p3, n2;
            try {
              if (util.isBindableTypedArray(pMem2)) {
                p3 = wasm.allocFromTypedArray(pMem2);
                n2 = nMem >= 0 ? nMem : pMem2.byteLength;
              } else if ("string" === typeof pMem2) {
                [p3, n2] = wasm.allocCString(pMem2);
              } else {
                return util.sqlite3__wasm_db_error(
                  capi.sqlite3_db_handle(pStmt),
                  capi.SQLITE_MISUSE,
                  "Invalid 3rd argument type for sqlite3_bind_blob()."
                );
              }
              return __bindBlob(pStmt, iCol, p3, n2, capi.SQLITE_WASM_DEALLOC);
            } catch (e2) {
              wasm.dealloc(p3);
              return util.sqlite3__wasm_db_error(
                capi.sqlite3_db_handle(pStmt),
                e2
              );
            }
          };
        }
        {
          capi.sqlite3_config = function(op, ...args) {
            if (arguments.length < 2)
              return capi.SQLITE_MISUSE;
            switch (op) {
              case capi.SQLITE_CONFIG_COVERING_INDEX_SCAN:
              case capi.SQLITE_CONFIG_MEMSTATUS:
              case capi.SQLITE_CONFIG_SMALL_MALLOC:
              case capi.SQLITE_CONFIG_SORTERREF_SIZE:
              case capi.SQLITE_CONFIG_STMTJRNL_SPILL:
              case capi.SQLITE_CONFIG_URI:
                return wasm.exports.sqlite3__wasm_config_i(op, args[0]);
              case capi.SQLITE_CONFIG_LOOKASIDE:
                return wasm.exports.sqlite3__wasm_config_ii(
                  op,
                  args[0],
                  args[1]
                );
              case capi.SQLITE_CONFIG_MEMDB_MAXSIZE:
                return wasm.exports.sqlite3__wasm_config_j(op, args[0]);
              case capi.SQLITE_CONFIG_GETMALLOC:
              case capi.SQLITE_CONFIG_GETMUTEX:
              case capi.SQLITE_CONFIG_GETPCACHE2:
              case capi.SQLITE_CONFIG_GETPCACHE:
              case capi.SQLITE_CONFIG_HEAP:
              case capi.SQLITE_CONFIG_LOG:
              case capi.SQLITE_CONFIG_MALLOC:
              case capi.SQLITE_CONFIG_MMAP_SIZE:
              case capi.SQLITE_CONFIG_MULTITHREAD:
              case capi.SQLITE_CONFIG_MUTEX:
              case capi.SQLITE_CONFIG_PAGECACHE:
              case capi.SQLITE_CONFIG_PCACHE2:
              case capi.SQLITE_CONFIG_PCACHE:
              case capi.SQLITE_CONFIG_PCACHE_HDRSZ:
              case capi.SQLITE_CONFIG_PMASZ:
              case capi.SQLITE_CONFIG_SERIALIZED:
              case capi.SQLITE_CONFIG_SINGLETHREAD:
              case capi.SQLITE_CONFIG_SQLLOG:
              case capi.SQLITE_CONFIG_WIN32_HEAPSIZE:
              default:
                return capi.SQLITE_NOTFOUND;
            }
          };
        }
        {
          const __autoExtFptr = /* @__PURE__ */ new Set();
          capi.sqlite3_auto_extension = function(fPtr) {
            if (fPtr instanceof Function) {
              fPtr = wasm.installFunction("i(ppp)", fPtr);
            } else if (1 !== arguments.length || !wasm.isPtr(fPtr)) {
              return capi.SQLITE_MISUSE;
            }
            const rc = wasm.exports.sqlite3_auto_extension(fPtr);
            if (fPtr !== arguments[0]) {
              if (0 === rc)
                __autoExtFptr.add(fPtr);
              else
                wasm.uninstallFunction(fPtr);
            }
            return rc;
          };
          capi.sqlite3_cancel_auto_extension = function(fPtr) {
            if (!fPtr || 1 !== arguments.length || !wasm.isPtr(fPtr))
              return 0;
            return wasm.exports.sqlite3_cancel_auto_extension(fPtr);
          };
          capi.sqlite3_reset_auto_extension = function() {
            wasm.exports.sqlite3_reset_auto_extension();
            for (const fp of __autoExtFptr)
              wasm.uninstallFunction(fp);
            __autoExtFptr.clear();
          };
        }
        const pKvvfs = capi.sqlite3_vfs_find("kvvfs");
        if (pKvvfs) {
          if (util.isUIThread()) {
            const kvvfsMethods = new capi.sqlite3_kvvfs_methods(
              wasm.exports.sqlite3__wasm_kvvfs_methods()
            );
            delete capi.sqlite3_kvvfs_methods;
            const kvvfsMakeKey = wasm.exports.sqlite3__wasm_kvvfsMakeKeyOnPstack, pstack = wasm.pstack;
            const kvvfsStorage = (zClass) => 115 === wasm.peek(zClass) ? sessionStorage : localStorage;
            const kvvfsImpls = {
              xRead: (zClass, zKey, zBuf, nBuf) => {
                const stack = pstack.pointer, astack = wasm.scopedAllocPush();
                try {
                  const zXKey = kvvfsMakeKey(zClass, zKey);
                  if (!zXKey)
                    return -3;
                  const jKey = wasm.cstrToJs(zXKey);
                  const jV = kvvfsStorage(zClass).getItem(jKey);
                  if (!jV)
                    return -1;
                  const nV = jV.length;
                  if (nBuf <= 0)
                    return nV;
                  else if (1 === nBuf) {
                    wasm.poke(zBuf, 0);
                    return nV;
                  }
                  const zV = wasm.scopedAllocCString(jV);
                  if (nBuf > nV + 1)
                    nBuf = nV + 1;
                  wasm.heap8u().copyWithin(zBuf, zV, zV + nBuf - 1);
                  wasm.poke(zBuf + nBuf - 1, 0);
                  return nBuf - 1;
                } catch (e2) {
                  console.error("kvstorageRead()", e2);
                  return -2;
                } finally {
                  pstack.restore(stack);
                  wasm.scopedAllocPop(astack);
                }
              },
              xWrite: (zClass, zKey, zData) => {
                const stack = pstack.pointer;
                try {
                  const zXKey = kvvfsMakeKey(zClass, zKey);
                  if (!zXKey)
                    return 1;
                  const jKey = wasm.cstrToJs(zXKey);
                  kvvfsStorage(zClass).setItem(jKey, wasm.cstrToJs(zData));
                  return 0;
                } catch (e2) {
                  console.error("kvstorageWrite()", e2);
                  return capi.SQLITE_IOERR;
                } finally {
                  pstack.restore(stack);
                }
              },
              xDelete: (zClass, zKey) => {
                const stack = pstack.pointer;
                try {
                  const zXKey = kvvfsMakeKey(zClass, zKey);
                  if (!zXKey)
                    return 1;
                  kvvfsStorage(zClass).removeItem(wasm.cstrToJs(zXKey));
                  return 0;
                } catch (e2) {
                  console.error("kvstorageDelete()", e2);
                  return capi.SQLITE_IOERR;
                } finally {
                  pstack.restore(stack);
                }
              }
            };
            for (const k2 of Object.keys(kvvfsImpls)) {
              kvvfsMethods[kvvfsMethods.memberKey(k2)] = wasm.installFunction(
                kvvfsMethods.memberSignature(k2),
                kvvfsImpls[k2]
              );
            }
          } else {
            capi.sqlite3_vfs_unregister(pKvvfs);
          }
        }
        wasm.xWrap.FuncPtrAdapter.warnOnUse = true;
        const StructBinder = sqlite32.StructBinder;
        const installMethod = function callee2(tgt, name, func, applyArgcCheck = callee2.installMethodArgcCheck) {
          if (!(tgt instanceof StructBinder.StructType)) {
            toss("Usage error: target object is-not-a StructType.");
          } else if (!(func instanceof Function) && !wasm.isPtr(func)) {
            toss("Usage errror: expecting a Function or WASM pointer to one.");
          }
          if (1 === arguments.length) {
            return (n2, f2) => callee2(tgt, n2, f2, applyArgcCheck);
          }
          if (!callee2.argcProxy) {
            callee2.argcProxy = function(tgt2, funcName, func2, sig) {
              return function(...args) {
                if (func2.length !== arguments.length) {
                  toss(
                    "Argument mismatch for",
                    tgt2.structInfo.name + "::" + funcName + ": Native signature is:",
                    sig
                  );
                }
                return func2.apply(this, args);
              };
            };
            callee2.removeFuncList = function() {
              if (this.ondispose.__removeFuncList) {
                this.ondispose.__removeFuncList.forEach((v3, ndx) => {
                  if ("number" === typeof v3) {
                    try {
                      wasm.uninstallFunction(v3);
                    } catch (e2) {
                    }
                  }
                });
                delete this.ondispose.__removeFuncList;
              }
            };
          }
          const sigN = tgt.memberSignature(name);
          if (sigN.length < 2) {
            toss(
              "Member",
              name,
              "does not have a function pointer signature:",
              sigN
            );
          }
          const memKey = tgt.memberKey(name);
          const fProxy = applyArgcCheck && !wasm.isPtr(func) ? callee2.argcProxy(tgt, memKey, func, sigN) : func;
          if (wasm.isPtr(fProxy)) {
            if (fProxy && !wasm.functionEntry(fProxy)) {
              toss("Pointer", fProxy, "is not a WASM function table entry.");
            }
            tgt[memKey] = fProxy;
          } else {
            const pFunc = wasm.installFunction(
              fProxy,
              tgt.memberSignature(name, true)
            );
            tgt[memKey] = pFunc;
            if (!tgt.ondispose || !tgt.ondispose.__removeFuncList) {
              tgt.addOnDispose(
                "ondispose.__removeFuncList handler",
                callee2.removeFuncList
              );
              tgt.ondispose.__removeFuncList = [];
            }
            tgt.ondispose.__removeFuncList.push(memKey, pFunc);
          }
          return (n2, f2) => callee2(tgt, n2, f2, applyArgcCheck);
        };
        installMethod.installMethodArgcCheck = false;
        const installMethods = function(structInstance, methods, applyArgcCheck = installMethod.installMethodArgcCheck) {
          const seen = /* @__PURE__ */ new Map();
          for (const k2 of Object.keys(methods)) {
            const m2 = methods[k2];
            const prior = seen.get(m2);
            if (prior) {
              const mkey = structInstance.memberKey(k2);
              structInstance[mkey] = structInstance[structInstance.memberKey(prior)];
            } else {
              installMethod(structInstance, k2, m2, applyArgcCheck);
              seen.set(m2, k2);
            }
          }
          return structInstance;
        };
        StructBinder.StructType.prototype.installMethod = function callee2(name, func, applyArgcCheck = installMethod.installMethodArgcCheck) {
          return arguments.length < 3 && name && "object" === typeof name ? installMethods(this, ...arguments) : installMethod(this, ...arguments);
        };
        StructBinder.StructType.prototype.installMethods = function(methods, applyArgcCheck = installMethod.installMethodArgcCheck) {
          return installMethods(this, methods, applyArgcCheck);
        };
      });
      globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite32) {
        sqlite32.version = {
          libVersion: "3.48.0",
          libVersionNumber: 3048e3,
          sourceId: "2025-01-14 11:05:00 d2fe6b05f38d9d7cd78c5d252e99ac59f1aea071d669830c1ffe4e8966e84010",
          downloadVersion: 348e4
        };
      });
      globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite32) {
        const toss = (...args) => {
          throw new Error(args.join(" "));
        };
        const toss3 = (...args) => {
          throw new sqlite32.SQLite3Error(...args);
        };
        const capi = sqlite32.capi, wasm = sqlite32.wasm, util = sqlite32.util;
        const __ptrMap = /* @__PURE__ */ new WeakMap();
        const __stmtMap = /* @__PURE__ */ new WeakMap();
        const getOwnOption = (opts, p3, dflt) => {
          const d2 = Object.getOwnPropertyDescriptor(opts, p3);
          return d2 ? d2.value : dflt;
        };
        const checkSqlite3Rc = function(dbPtr, sqliteResultCode) {
          if (sqliteResultCode) {
            if (dbPtr instanceof DB)
              dbPtr = dbPtr.pointer;
            toss3(
              sqliteResultCode,
              "sqlite3 result code",
              sqliteResultCode + ":",
              dbPtr ? capi.sqlite3_errmsg(dbPtr) : capi.sqlite3_errstr(sqliteResultCode)
            );
          }
          return arguments[0];
        };
        const __dbTraceToConsole = wasm.installFunction(
          "i(ippp)",
          function(t2, c3, p3, x2) {
            if (capi.SQLITE_TRACE_STMT === t2) {
              console.log(
                "SQL TRACE #" + ++this.counter + " via sqlite3@" + c3 + ":",
                wasm.cstrToJs(x2)
              );
            }
          }.bind({ counter: 0 })
        );
        const __vfsPostOpenCallback = /* @__PURE__ */ Object.create(null);
        const dbCtorHelper = function ctor(...args) {
          if (!ctor._name2vfs) {
            ctor._name2vfs = /* @__PURE__ */ Object.create(null);
            const isWorkerThread = "function" === typeof importScripts ? (n2) => toss3(
              "The VFS for",
              n2,
              "is only available in the main window thread."
            ) : false;
            ctor._name2vfs[":localStorage:"] = {
              vfs: "kvvfs",
              filename: isWorkerThread || (() => "local")
            };
            ctor._name2vfs[":sessionStorage:"] = {
              vfs: "kvvfs",
              filename: isWorkerThread || (() => "session")
            };
          }
          const opt = ctor.normalizeArgs(...args);
          let fn = opt.filename, vfsName = opt.vfs, flagsStr = opt.flags;
          if ("string" !== typeof fn && "number" !== typeof fn || "string" !== typeof flagsStr || vfsName && "string" !== typeof vfsName && "number" !== typeof vfsName) {
            sqlite32.config.error("Invalid DB ctor args", opt, arguments);
            toss3("Invalid arguments for DB constructor.");
          }
          let fnJs = "number" === typeof fn ? wasm.cstrToJs(fn) : fn;
          const vfsCheck = ctor._name2vfs[fnJs];
          if (vfsCheck) {
            vfsName = vfsCheck.vfs;
            fn = fnJs = vfsCheck.filename(fnJs);
          }
          let pDb2, oflags = 0;
          if (flagsStr.indexOf("c") >= 0) {
            oflags |= capi.SQLITE_OPEN_CREATE | capi.SQLITE_OPEN_READWRITE;
          }
          if (flagsStr.indexOf("w") >= 0)
            oflags |= capi.SQLITE_OPEN_READWRITE;
          if (0 === oflags)
            oflags |= capi.SQLITE_OPEN_READONLY;
          oflags |= capi.SQLITE_OPEN_EXRESCODE;
          const stack = wasm.pstack.pointer;
          try {
            const pPtr = wasm.pstack.allocPtr();
            let rc = capi.sqlite3_open_v2(fn, pPtr, oflags, vfsName || 0);
            pDb2 = wasm.peekPtr(pPtr);
            checkSqlite3Rc(pDb2, rc);
            capi.sqlite3_extended_result_codes(pDb2, 1);
            if (flagsStr.indexOf("t") >= 0) {
              capi.sqlite3_trace_v2(
                pDb2,
                capi.SQLITE_TRACE_STMT,
                __dbTraceToConsole,
                pDb2
              );
            }
          } catch (e2) {
            if (pDb2)
              capi.sqlite3_close_v2(pDb2);
            throw e2;
          } finally {
            wasm.pstack.restore(stack);
          }
          this.filename = fnJs;
          __ptrMap.set(this, pDb2);
          __stmtMap.set(this, /* @__PURE__ */ Object.create(null));
          try {
            const pVfs = capi.sqlite3_js_db_vfs(pDb2) || toss3("Internal error: cannot get VFS for new db handle.");
            const postInitSql = __vfsPostOpenCallback[pVfs];
            if (postInitSql) {
              if (postInitSql instanceof Function) {
                postInitSql(this, sqlite32);
              } else {
                checkSqlite3Rc(
                  pDb2,
                  capi.sqlite3_exec(pDb2, postInitSql, 0, 0, 0)
                );
              }
            }
          } catch (e2) {
            this.close();
            throw e2;
          }
        };
        dbCtorHelper.setVfsPostOpenCallback = function(pVfs, callback) {
          if (!(callback instanceof Function)) {
            toss3(
              "dbCtorHelper.setVfsPostOpenCallback() should not be used with a non-function argument.",
              arguments
            );
          }
          __vfsPostOpenCallback[pVfs] = callback;
        };
        dbCtorHelper.normalizeArgs = function(filename = ":memory:", flags = "c", vfs = null) {
          const arg = {};
          if (1 === arguments.length && arguments[0] && "object" === typeof arguments[0]) {
            Object.assign(arg, arguments[0]);
            if (void 0 === arg.flags)
              arg.flags = "c";
            if (void 0 === arg.vfs)
              arg.vfs = null;
            if (void 0 === arg.filename)
              arg.filename = ":memory:";
          } else {
            arg.filename = filename;
            arg.flags = flags;
            arg.vfs = vfs;
          }
          return arg;
        };
        const DB = function(...args) {
          dbCtorHelper.apply(this, args);
        };
        DB.dbCtorHelper = dbCtorHelper;
        const BindTypes = {
          null: 1,
          number: 2,
          string: 3,
          boolean: 4,
          blob: 5
        };
        BindTypes["undefined"] == BindTypes.null;
        if (wasm.bigIntEnabled) {
          BindTypes.bigint = BindTypes.number;
        }
        const Stmt = function() {
          if (BindTypes !== arguments[2]) {
            toss3(
              capi.SQLITE_MISUSE,
              "Do not call the Stmt constructor directly. Use DB.prepare()."
            );
          }
          this.db = arguments[0];
          __ptrMap.set(this, arguments[1]);
          this.parameterCount = capi.sqlite3_bind_parameter_count(this.pointer);
        };
        const affirmDbOpen = function(db) {
          if (!db.pointer)
            toss3("DB has been closed.");
          return db;
        };
        const affirmColIndex = function(stmt, ndx) {
          if (ndx !== (ndx | 0) || ndx < 0 || ndx >= stmt.columnCount) {
            toss3("Column index", ndx, "is out of range.");
          }
          return stmt;
        };
        const parseExecArgs = function(db, args) {
          const out2 = /* @__PURE__ */ Object.create(null);
          out2.opt = /* @__PURE__ */ Object.create(null);
          switch (args.length) {
            case 1:
              if ("string" === typeof args[0] || util.isSQLableTypedArray(args[0])) {
                out2.sql = args[0];
              } else if (Array.isArray(args[0])) {
                out2.sql = args[0];
              } else if (args[0] && "object" === typeof args[0]) {
                out2.opt = args[0];
                out2.sql = out2.opt.sql;
              }
              break;
            case 2:
              out2.sql = args[0];
              out2.opt = args[1];
              break;
            default:
              toss3("Invalid argument count for exec().");
          }
          out2.sql = util.flexibleString(out2.sql);
          if ("string" !== typeof out2.sql) {
            toss3("Missing SQL argument or unsupported SQL value type.");
          }
          const opt = out2.opt;
          switch (opt.returnValue) {
            case "resultRows":
              if (!opt.resultRows)
                opt.resultRows = [];
              out2.returnVal = () => opt.resultRows;
              break;
            case "saveSql":
              if (!opt.saveSql)
                opt.saveSql = [];
              out2.returnVal = () => opt.saveSql;
              break;
            case void 0:
            case "this":
              out2.returnVal = () => db;
              break;
            default:
              toss3("Invalid returnValue value:", opt.returnValue);
          }
          if (!opt.callback && !opt.returnValue && void 0 !== opt.rowMode) {
            if (!opt.resultRows)
              opt.resultRows = [];
            out2.returnVal = () => opt.resultRows;
          }
          if (opt.callback || opt.resultRows) {
            switch (void 0 === opt.rowMode ? "array" : opt.rowMode) {
              case "object":
                out2.cbArg = (stmt, cache) => {
                  if (!cache.columnNames)
                    cache.columnNames = stmt.getColumnNames([]);
                  const row = stmt.get([]);
                  const rv = /* @__PURE__ */ Object.create(null);
                  for (const i2 in cache.columnNames)
                    rv[cache.columnNames[i2]] = row[i2];
                  return rv;
                };
                break;
              case "array":
                out2.cbArg = (stmt) => stmt.get([]);
                break;
              case "stmt":
                if (Array.isArray(opt.resultRows)) {
                  toss3(
                    "exec(): invalid rowMode for a resultRows array: must",
                    "be one of 'array', 'object',",
                    "a result column number, or column name reference."
                  );
                }
                out2.cbArg = (stmt) => stmt;
                break;
              default:
                if (util.isInt32(opt.rowMode)) {
                  out2.cbArg = (stmt) => stmt.get(opt.rowMode);
                  break;
                } else if ("string" === typeof opt.rowMode && opt.rowMode.length > 1 && "$" === opt.rowMode[0]) {
                  const $colName = opt.rowMode.substr(1);
                  out2.cbArg = (stmt) => {
                    const rc = stmt.get(/* @__PURE__ */ Object.create(null))[$colName];
                    return void 0 === rc ? toss3(
                      capi.SQLITE_NOTFOUND,
                      "exec(): unknown result column:",
                      $colName
                    ) : rc;
                  };
                  break;
                }
                toss3("Invalid rowMode:", opt.rowMode);
            }
          }
          return out2;
        };
        const __selectFirstRow = (db, sql2, bind, ...getArgs) => {
          const stmt = db.prepare(sql2);
          try {
            const rc = stmt.bind(bind).step() ? stmt.get(...getArgs) : void 0;
            stmt.reset();
            return rc;
          } finally {
            stmt.finalize();
          }
        };
        const __selectAll = (db, sql2, bind, rowMode) => db.exec({
          sql: sql2,
          bind,
          rowMode,
          returnValue: "resultRows"
        });
        DB.checkRc = (db, resultCode) => checkSqlite3Rc(db, resultCode);
        DB.prototype = {
          isOpen: function() {
            return !!this.pointer;
          },
          affirmOpen: function() {
            return affirmDbOpen(this);
          },
          close: function() {
            if (this.pointer) {
              if (this.onclose && this.onclose.before instanceof Function) {
                try {
                  this.onclose.before(this);
                } catch (e2) {
                }
              }
              const pDb2 = this.pointer;
              Object.keys(__stmtMap.get(this)).forEach((k2, s2) => {
                if (s2 && s2.pointer) {
                  try {
                    s2.finalize();
                  } catch (e2) {
                  }
                }
              });
              __ptrMap.delete(this);
              __stmtMap.delete(this);
              capi.sqlite3_close_v2(pDb2);
              if (this.onclose && this.onclose.after instanceof Function) {
                try {
                  this.onclose.after(this);
                } catch (e2) {
                }
              }
              delete this.filename;
            }
          },
          changes: function(total = false, sixtyFour = false) {
            const p3 = affirmDbOpen(this).pointer;
            if (total) {
              return sixtyFour ? capi.sqlite3_total_changes64(p3) : capi.sqlite3_total_changes(p3);
            } else {
              return sixtyFour ? capi.sqlite3_changes64(p3) : capi.sqlite3_changes(p3);
            }
          },
          dbFilename: function(dbName = "main") {
            return capi.sqlite3_db_filename(affirmDbOpen(this).pointer, dbName);
          },
          dbName: function(dbNumber = 0) {
            return capi.sqlite3_db_name(affirmDbOpen(this).pointer, dbNumber);
          },
          dbVfsName: function(dbName = 0) {
            let rc;
            const pVfs = capi.sqlite3_js_db_vfs(
              affirmDbOpen(this).pointer,
              dbName
            );
            if (pVfs) {
              const v3 = new capi.sqlite3_vfs(pVfs);
              try {
                rc = wasm.cstrToJs(v3.$zName);
              } finally {
                v3.dispose();
              }
            }
            return rc;
          },
          prepare: function(sql2) {
            affirmDbOpen(this);
            const stack = wasm.pstack.pointer;
            let ppStmt, pStmt;
            try {
              ppStmt = wasm.pstack.alloc(8);
              DB.checkRc(
                this,
                capi.sqlite3_prepare_v2(this.pointer, sql2, -1, ppStmt, null)
              );
              pStmt = wasm.peekPtr(ppStmt);
            } finally {
              wasm.pstack.restore(stack);
            }
            if (!pStmt)
              toss3("Cannot prepare empty SQL.");
            const stmt = new Stmt(this, pStmt, BindTypes);
            __stmtMap.get(this)[pStmt] = stmt;
            return stmt;
          },
          exec: function() {
            affirmDbOpen(this);
            const arg = parseExecArgs(this, arguments);
            if (!arg.sql) {
              return toss3("exec() requires an SQL string.");
            }
            const opt = arg.opt;
            const callback = opt.callback;
            const resultRows = Array.isArray(opt.resultRows) ? opt.resultRows : void 0;
            let stmt;
            let bind = opt.bind;
            let evalFirstResult = !!(arg.cbArg || opt.columnNames || resultRows);
            const stack = wasm.scopedAllocPush();
            const saveSql = Array.isArray(opt.saveSql) ? opt.saveSql : void 0;
            try {
              const isTA = util.isSQLableTypedArray(arg.sql);
              let sqlByteLen = isTA ? arg.sql.byteLength : wasm.jstrlen(arg.sql);
              const ppStmt = wasm.scopedAlloc(
                2 * wasm.ptrSizeof + (sqlByteLen + 1)
              );
              const pzTail = ppStmt + wasm.ptrSizeof;
              let pSql = pzTail + wasm.ptrSizeof;
              const pSqlEnd = pSql + sqlByteLen;
              if (isTA)
                wasm.heap8().set(arg.sql, pSql);
              else
                wasm.jstrcpy(arg.sql, wasm.heap8(), pSql, sqlByteLen, false);
              wasm.poke(pSql + sqlByteLen, 0);
              while (pSql && wasm.peek(pSql, "i8")) {
                wasm.pokePtr([ppStmt, pzTail], 0);
                DB.checkRc(
                  this,
                  capi.sqlite3_prepare_v3(
                    this.pointer,
                    pSql,
                    sqlByteLen,
                    0,
                    ppStmt,
                    pzTail
                  )
                );
                const pStmt = wasm.peekPtr(ppStmt);
                pSql = wasm.peekPtr(pzTail);
                sqlByteLen = pSqlEnd - pSql;
                if (!pStmt)
                  continue;
                if (saveSql)
                  saveSql.push(capi.sqlite3_sql(pStmt).trim());
                stmt = new Stmt(this, pStmt, BindTypes);
                if (bind && stmt.parameterCount) {
                  stmt.bind(bind);
                  bind = null;
                }
                if (evalFirstResult && stmt.columnCount) {
                  let gotColNames = Array.isArray(opt.columnNames) ? 0 : 1;
                  evalFirstResult = false;
                  if (arg.cbArg || resultRows) {
                    const cbArgCache = /* @__PURE__ */ Object.create(null);
                    for (; stmt.step(); stmt._lockedByExec = false) {
                      if (0 === gotColNames++) {
                        stmt.getColumnNames(
                          cbArgCache.columnNames = opt.columnNames || []
                        );
                      }
                      stmt._lockedByExec = true;
                      const row = arg.cbArg(stmt, cbArgCache);
                      if (resultRows)
                        resultRows.push(row);
                      if (callback && false === callback.call(opt, row, stmt)) {
                        break;
                      }
                    }
                    stmt._lockedByExec = false;
                  }
                  if (0 === gotColNames) {
                    stmt.getColumnNames(opt.columnNames);
                  }
                } else {
                  stmt.step();
                }
                stmt.reset().finalize();
                stmt = null;
              }
            } finally {
              wasm.scopedAllocPop(stack);
              if (stmt) {
                delete stmt._lockedByExec;
                stmt.finalize();
              }
            }
            return arg.returnVal();
          },
          createFunction: function f2(name, xFunc, opt) {
            const isFunc = (f3) => f3 instanceof Function;
            switch (arguments.length) {
              case 1:
                opt = name;
                name = opt.name;
                xFunc = opt.xFunc || 0;
                break;
              case 2:
                if (!isFunc(xFunc)) {
                  opt = xFunc;
                  xFunc = opt.xFunc || 0;
                }
                break;
              case 3:
                break;
              default:
                break;
            }
            if (!opt)
              opt = {};
            if ("string" !== typeof name) {
              toss3("Invalid arguments: missing function name.");
            }
            let xStep = opt.xStep || 0;
            let xFinal = opt.xFinal || 0;
            const xValue = opt.xValue || 0;
            const xInverse = opt.xInverse || 0;
            let isWindow = void 0;
            if (isFunc(xFunc)) {
              isWindow = false;
              if (isFunc(xStep) || isFunc(xFinal)) {
                toss3("Ambiguous arguments: scalar or aggregate?");
              }
              xStep = xFinal = null;
            } else if (isFunc(xStep)) {
              if (!isFunc(xFinal)) {
                toss3("Missing xFinal() callback for aggregate or window UDF.");
              }
              xFunc = null;
            } else if (isFunc(xFinal)) {
              toss3("Missing xStep() callback for aggregate or window UDF.");
            } else {
              toss3("Missing function-type properties.");
            }
            if (false === isWindow) {
              if (isFunc(xValue) || isFunc(xInverse)) {
                toss3(
                  "xValue and xInverse are not permitted for non-window UDFs."
                );
              }
            } else if (isFunc(xValue)) {
              if (!isFunc(xInverse)) {
                toss3("xInverse must be provided if xValue is.");
              }
              isWindow = true;
            } else if (isFunc(xInverse)) {
              toss3("xValue must be provided if xInverse is.");
            }
            const pApp = opt.pApp;
            if (void 0 !== pApp && null !== pApp && ("number" !== typeof pApp || !util.isInt32(pApp))) {
              toss3(
                "Invalid value for pApp property. Must be a legal WASM pointer value."
              );
            }
            const xDestroy = opt.xDestroy || 0;
            if (xDestroy && !isFunc(xDestroy)) {
              toss3("xDestroy property must be a function.");
            }
            let fFlags = 0;
            if (getOwnOption(opt, "deterministic"))
              fFlags |= capi.SQLITE_DETERMINISTIC;
            if (getOwnOption(opt, "directOnly"))
              fFlags |= capi.SQLITE_DIRECTONLY;
            if (getOwnOption(opt, "innocuous"))
              fFlags |= capi.SQLITE_INNOCUOUS;
            name = name.toLowerCase();
            const xArity = xFunc || xStep;
            const arity = getOwnOption(opt, "arity");
            const arityArg = "number" === typeof arity ? arity : xArity.length ? xArity.length - 1 : 0;
            let rc;
            if (isWindow) {
              rc = capi.sqlite3_create_window_function(
                this.pointer,
                name,
                arityArg,
                capi.SQLITE_UTF8 | fFlags,
                pApp || 0,
                xStep,
                xFinal,
                xValue,
                xInverse,
                xDestroy
              );
            } else {
              rc = capi.sqlite3_create_function_v2(
                this.pointer,
                name,
                arityArg,
                capi.SQLITE_UTF8 | fFlags,
                pApp || 0,
                xFunc,
                xStep,
                xFinal,
                xDestroy
              );
            }
            DB.checkRc(this, rc);
            return this;
          },
          selectValue: function(sql2, bind, asType) {
            return __selectFirstRow(this, sql2, bind, 0, asType);
          },
          selectValues: function(sql2, bind, asType) {
            const stmt = this.prepare(sql2), rc = [];
            try {
              stmt.bind(bind);
              while (stmt.step())
                rc.push(stmt.get(0, asType));
              stmt.reset();
            } finally {
              stmt.finalize();
            }
            return rc;
          },
          selectArray: function(sql2, bind) {
            return __selectFirstRow(this, sql2, bind, []);
          },
          selectObject: function(sql2, bind) {
            return __selectFirstRow(this, sql2, bind, {});
          },
          selectArrays: function(sql2, bind) {
            return __selectAll(this, sql2, bind, "array");
          },
          selectObjects: function(sql2, bind) {
            return __selectAll(this, sql2, bind, "object");
          },
          openStatementCount: function() {
            return this.pointer ? Object.keys(__stmtMap.get(this)).length : 0;
          },
          transaction: function(callback) {
            let opener = "BEGIN";
            if (arguments.length > 1) {
              if (/[^a-zA-Z]/.test(arguments[0])) {
                toss3(
                  capi.SQLITE_MISUSE,
                  "Invalid argument for BEGIN qualifier."
                );
              }
              opener += " " + arguments[0];
              callback = arguments[1];
            }
            affirmDbOpen(this).exec(opener);
            try {
              const rc = callback(this);
              this.exec("COMMIT");
              return rc;
            } catch (e2) {
              this.exec("ROLLBACK");
              throw e2;
            }
          },
          savepoint: function(callback) {
            affirmDbOpen(this).exec("SAVEPOINT oo1");
            try {
              const rc = callback(this);
              this.exec("RELEASE oo1");
              return rc;
            } catch (e2) {
              this.exec("ROLLBACK to SAVEPOINT oo1; RELEASE SAVEPOINT oo1");
              throw e2;
            }
          },
          checkRc: function(resultCode) {
            return checkSqlite3Rc(this, resultCode);
          }
        };
        const affirmStmtOpen = function(stmt) {
          if (!stmt.pointer)
            toss3("Stmt has been closed.");
          return stmt;
        };
        const isSupportedBindType = function(v3) {
          let t2 = BindTypes[null === v3 || void 0 === v3 ? "null" : typeof v3];
          switch (t2) {
            case BindTypes.boolean:
            case BindTypes.null:
            case BindTypes.number:
            case BindTypes.string:
              return t2;
            case BindTypes.bigint:
              if (wasm.bigIntEnabled)
                return t2;
            default:
              return util.isBindableTypedArray(v3) ? BindTypes.blob : void 0;
          }
        };
        const affirmSupportedBindType = function(v3) {
          return isSupportedBindType(v3) || toss3("Unsupported bind() argument type:", typeof v3);
        };
        const affirmParamIndex = function(stmt, key) {
          const n2 = "number" === typeof key ? key : capi.sqlite3_bind_parameter_index(stmt.pointer, key);
          if (0 === n2 || !util.isInt32(n2)) {
            toss3("Invalid bind() parameter name: " + key);
          } else if (n2 < 1 || n2 > stmt.parameterCount)
            toss3("Bind index", key, "is out of range.");
          return n2;
        };
        const affirmNotLockedByExec = function(stmt, currentOpName) {
          if (stmt._lockedByExec) {
            toss3(
              "Operation is illegal when statement is locked:",
              currentOpName
            );
          }
          return stmt;
        };
        const bindOne = function f2(stmt, ndx, bindType, val) {
          affirmNotLockedByExec(affirmStmtOpen(stmt), "bind()");
          if (!f2._) {
            f2._tooBigInt = (v3) => toss3(
              "BigInt value is too big to store without precision loss:",
              v3
            );
            f2._ = {
              string: function(stmt2, ndx2, val2, asBlob) {
                const [pStr, n2] = wasm.allocCString(val2, true);
                const f3 = asBlob ? capi.sqlite3_bind_blob : capi.sqlite3_bind_text;
                return f3(stmt2.pointer, ndx2, pStr, n2, capi.SQLITE_WASM_DEALLOC);
              }
            };
          }
          affirmSupportedBindType(val);
          ndx = affirmParamIndex(stmt, ndx);
          let rc = 0;
          switch (null === val || void 0 === val ? BindTypes.null : bindType) {
            case BindTypes.null:
              rc = capi.sqlite3_bind_null(stmt.pointer, ndx);
              break;
            case BindTypes.string:
              rc = f2._.string(stmt, ndx, val, false);
              break;
            case BindTypes.number: {
              let m2;
              if (util.isInt32(val))
                m2 = capi.sqlite3_bind_int;
              else if ("bigint" === typeof val) {
                if (!util.bigIntFits64(val)) {
                  f2._tooBigInt(val);
                } else if (wasm.bigIntEnabled) {
                  m2 = capi.sqlite3_bind_int64;
                } else if (util.bigIntFitsDouble(val)) {
                  val = Number(val);
                  m2 = capi.sqlite3_bind_double;
                } else {
                  f2._tooBigInt(val);
                }
              } else {
                val = Number(val);
                if (wasm.bigIntEnabled && Number.isInteger(val)) {
                  m2 = capi.sqlite3_bind_int64;
                } else {
                  m2 = capi.sqlite3_bind_double;
                }
              }
              rc = m2(stmt.pointer, ndx, val);
              break;
            }
            case BindTypes.boolean:
              rc = capi.sqlite3_bind_int(stmt.pointer, ndx, val ? 1 : 0);
              break;
            case BindTypes.blob: {
              if ("string" === typeof val) {
                rc = f2._.string(stmt, ndx, val, true);
                break;
              } else if (val instanceof ArrayBuffer) {
                val = new Uint8Array(val);
              } else if (!util.isBindableTypedArray(val)) {
                toss3(
                  "Binding a value as a blob requires",
                  "that it be a string, Uint8Array, Int8Array, or ArrayBuffer."
                );
              }
              const pBlob = wasm.alloc(val.byteLength || 1);
              wasm.heap8().set(val.byteLength ? val : [0], pBlob);
              rc = capi.sqlite3_bind_blob(
                stmt.pointer,
                ndx,
                pBlob,
                val.byteLength,
                capi.SQLITE_WASM_DEALLOC
              );
              break;
            }
            default:
              sqlite32.config.warn("Unsupported bind() argument type:", val);
              toss3("Unsupported bind() argument type: " + typeof val);
          }
          if (rc)
            DB.checkRc(stmt.db.pointer, rc);
          stmt._mayGet = false;
          return stmt;
        };
        Stmt.prototype = {
          finalize: function() {
            if (this.pointer) {
              affirmNotLockedByExec(this, "finalize()");
              const rc = capi.sqlite3_finalize(this.pointer);
              delete __stmtMap.get(this.db)[this.pointer];
              __ptrMap.delete(this);
              delete this._mayGet;
              delete this.parameterCount;
              delete this._lockedByExec;
              delete this.db;
              return rc;
            }
          },
          clearBindings: function() {
            affirmNotLockedByExec(affirmStmtOpen(this), "clearBindings()");
            capi.sqlite3_clear_bindings(this.pointer);
            this._mayGet = false;
            return this;
          },
          reset: function(alsoClearBinds) {
            affirmNotLockedByExec(this, "reset()");
            if (alsoClearBinds)
              this.clearBindings();
            const rc = capi.sqlite3_reset(affirmStmtOpen(this).pointer);
            this._mayGet = false;
            checkSqlite3Rc(this.db, rc);
            return this;
          },
          bind: function() {
            affirmStmtOpen(this);
            let ndx, arg;
            switch (arguments.length) {
              case 1:
                ndx = 1;
                arg = arguments[0];
                break;
              case 2:
                ndx = arguments[0];
                arg = arguments[1];
                break;
              default:
                toss3("Invalid bind() arguments.");
            }
            if (void 0 === arg) {
              return this;
            } else if (!this.parameterCount) {
              toss3("This statement has no bindable parameters.");
            }
            this._mayGet = false;
            if (null === arg) {
              return bindOne(this, ndx, BindTypes.null, arg);
            } else if (Array.isArray(arg)) {
              if (1 !== arguments.length) {
                toss3(
                  "When binding an array, an index argument is not permitted."
                );
              }
              arg.forEach(
                (v3, i2) => bindOne(this, i2 + 1, affirmSupportedBindType(v3), v3)
              );
              return this;
            } else if (arg instanceof ArrayBuffer) {
              arg = new Uint8Array(arg);
            }
            if ("object" === typeof arg && !util.isBindableTypedArray(arg)) {
              if (1 !== arguments.length) {
                toss3(
                  "When binding an object, an index argument is not permitted."
                );
              }
              Object.keys(arg).forEach(
                (k2) => bindOne(this, k2, affirmSupportedBindType(arg[k2]), arg[k2])
              );
              return this;
            } else {
              return bindOne(this, ndx, affirmSupportedBindType(arg), arg);
            }
            toss3("Should not reach this point.");
          },
          bindAsBlob: function(ndx, arg) {
            affirmStmtOpen(this);
            if (1 === arguments.length) {
              arg = ndx;
              ndx = 1;
            }
            const t2 = affirmSupportedBindType(arg);
            if (BindTypes.string !== t2 && BindTypes.blob !== t2 && BindTypes.null !== t2) {
              toss3("Invalid value type for bindAsBlob()");
            }
            return bindOne(this, ndx, BindTypes.blob, arg);
          },
          step: function() {
            affirmNotLockedByExec(this, "step()");
            const rc = capi.sqlite3_step(affirmStmtOpen(this).pointer);
            switch (rc) {
              case capi.SQLITE_DONE:
                return this._mayGet = false;
              case capi.SQLITE_ROW:
                return this._mayGet = true;
              default:
                this._mayGet = false;
                sqlite32.config.warn(
                  "sqlite3_step() rc=",
                  rc,
                  capi.sqlite3_js_rc_str(rc),
                  "SQL =",
                  capi.sqlite3_sql(this.pointer)
                );
                DB.checkRc(this.db.pointer, rc);
            }
          },
          stepReset: function() {
            this.step();
            return this.reset();
          },
          stepFinalize: function() {
            try {
              const rc = this.step();
              this.reset();
              return rc;
            } finally {
              try {
                this.finalize();
              } catch (e2) {
              }
            }
          },
          get: function(ndx, asType) {
            if (!affirmStmtOpen(this)._mayGet) {
              toss3("Stmt.step() has not (recently) returned true.");
            }
            if (Array.isArray(ndx)) {
              let i2 = 0;
              const n2 = this.columnCount;
              while (i2 < n2) {
                ndx[i2] = this.get(i2++);
              }
              return ndx;
            } else if (ndx && "object" === typeof ndx) {
              let i2 = 0;
              const n2 = this.columnCount;
              while (i2 < n2) {
                ndx[capi.sqlite3_column_name(this.pointer, i2)] = this.get(i2++);
              }
              return ndx;
            }
            affirmColIndex(this, ndx);
            switch (void 0 === asType ? capi.sqlite3_column_type(this.pointer, ndx) : asType) {
              case capi.SQLITE_NULL:
                return null;
              case capi.SQLITE_INTEGER: {
                if (wasm.bigIntEnabled) {
                  const rc = capi.sqlite3_column_int64(this.pointer, ndx);
                  if (rc >= Number.MIN_SAFE_INTEGER && rc <= Number.MAX_SAFE_INTEGER) {
                    return Number(rc).valueOf();
                  }
                  return rc;
                } else {
                  const rc = capi.sqlite3_column_double(this.pointer, ndx);
                  if (rc > Number.MAX_SAFE_INTEGER || rc < Number.MIN_SAFE_INTEGER) {
                    toss3(
                      "Integer is out of range for JS integer range: " + rc
                    );
                  }
                  return util.isInt32(rc) ? rc | 0 : rc;
                }
              }
              case capi.SQLITE_FLOAT:
                return capi.sqlite3_column_double(this.pointer, ndx);
              case capi.SQLITE_TEXT:
                return capi.sqlite3_column_text(this.pointer, ndx);
              case capi.SQLITE_BLOB: {
                const n2 = capi.sqlite3_column_bytes(this.pointer, ndx), ptr = capi.sqlite3_column_blob(this.pointer, ndx), rc = new Uint8Array(n2);
                if (n2)
                  rc.set(wasm.heap8u().slice(ptr, ptr + n2), 0);
                if (n2 && this.db._blobXfer instanceof Array) {
                  this.db._blobXfer.push(rc.buffer);
                }
                return rc;
              }
              default:
                toss3(
                  "Don't know how to translate",
                  "type of result column #" + ndx + "."
                );
            }
            toss3("Not reached.");
          },
          getInt: function(ndx) {
            return this.get(ndx, capi.SQLITE_INTEGER);
          },
          getFloat: function(ndx) {
            return this.get(ndx, capi.SQLITE_FLOAT);
          },
          getString: function(ndx) {
            return this.get(ndx, capi.SQLITE_TEXT);
          },
          getBlob: function(ndx) {
            return this.get(ndx, capi.SQLITE_BLOB);
          },
          getJSON: function(ndx) {
            const s2 = this.get(ndx, capi.SQLITE_STRING);
            return null === s2 ? s2 : JSON.parse(s2);
          },
          getColumnName: function(ndx) {
            return capi.sqlite3_column_name(
              affirmColIndex(affirmStmtOpen(this), ndx).pointer,
              ndx
            );
          },
          getColumnNames: function(tgt = []) {
            affirmColIndex(affirmStmtOpen(this), 0);
            const n2 = this.columnCount;
            for (let i2 = 0; i2 < n2; ++i2) {
              tgt.push(capi.sqlite3_column_name(this.pointer, i2));
            }
            return tgt;
          },
          getParamIndex: function(name) {
            return affirmStmtOpen(this).parameterCount ? capi.sqlite3_bind_parameter_index(this.pointer, name) : void 0;
          },
          getParamName: function(ndx) {
            return affirmStmtOpen(this).parameterCount ? capi.sqlite3_bind_parameter_name(this.pointer, ndx) : void 0;
          },
          isBusy: function() {
            return 0 !== capi.sqlite3_stmt_busy(affirmStmtOpen(this));
          },
          isReadOnly: function() {
            return 0 !== capi.sqlite3_stmt_readonly(affirmStmtOpen(this));
          }
        };
        {
          const prop = {
            enumerable: true,
            get: function() {
              return __ptrMap.get(this);
            },
            set: () => toss3("The pointer property is read-only.")
          };
          Object.defineProperty(Stmt.prototype, "pointer", prop);
          Object.defineProperty(DB.prototype, "pointer", prop);
        }
        Object.defineProperty(Stmt.prototype, "columnCount", {
          enumerable: false,
          get: function() {
            return capi.sqlite3_column_count(this.pointer);
          },
          set: () => toss3("The columnCount property is read-only.")
        });
        sqlite32.oo1 = {
          DB,
          Stmt
        };
        if (util.isUIThread()) {
          sqlite32.oo1.JsStorageDb = function(storageName = "session") {
            const opt = dbCtorHelper.normalizeArgs(...arguments);
            storageName = opt.filename;
            if ("session" !== storageName && "local" !== storageName) {
              toss3("JsStorageDb db name must be one of 'session' or 'local'.");
            }
            opt.vfs = "kvvfs";
            dbCtorHelper.call(this, opt);
          };
          const jdb = sqlite32.oo1.JsStorageDb;
          jdb.prototype = Object.create(DB.prototype);
          jdb.clearStorage = capi.sqlite3_js_kvvfs_clear;
          jdb.prototype.clearStorage = function() {
            return jdb.clearStorage(affirmDbOpen(this).filename);
          };
          jdb.storageSize = capi.sqlite3_js_kvvfs_size;
          jdb.prototype.storageSize = function() {
            return jdb.storageSize(affirmDbOpen(this).filename);
          };
        }
      });
      globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite32) {
        const util = sqlite32.util;
        sqlite32.initWorker1API = function() {
          "use strict";
          const toss = (...args) => {
            throw new Error(args.join(" "));
          };
          if (!(globalThis.WorkerGlobalScope instanceof Function)) {
            toss("initWorker1API() must be run from a Worker thread.");
          }
          const sqlite33 = this.sqlite3 || toss("Missing this.sqlite3 object.");
          const DB = sqlite33.oo1.DB;
          const getDbId = function(db) {
            let id = wState.idMap.get(db);
            if (id)
              return id;
            id = "db#" + ++wState.idSeq + "@" + db.pointer;
            wState.idMap.set(db, id);
            return id;
          };
          const wState = {
            dbList: [],
            idSeq: 0,
            idMap: /* @__PURE__ */ new WeakMap(),
            xfer: [],
            open: function(opt) {
              const db = new DB(opt);
              this.dbs[getDbId(db)] = db;
              if (this.dbList.indexOf(db) < 0)
                this.dbList.push(db);
              return db;
            },
            close: function(db, alsoUnlink) {
              if (db) {
                delete this.dbs[getDbId(db)];
                const filename = db.filename;
                const pVfs = util.sqlite3__wasm_db_vfs(db.pointer, 0);
                db.close();
                const ddNdx = this.dbList.indexOf(db);
                if (ddNdx >= 0)
                  this.dbList.splice(ddNdx, 1);
                if (alsoUnlink && filename && pVfs) {
                  util.sqlite3__wasm_vfs_unlink(pVfs, filename);
                }
              }
            },
            post: function(msg, xferList) {
              if (xferList && xferList.length) {
                globalThis.postMessage(msg, Array.from(xferList));
                xferList.length = 0;
              } else {
                globalThis.postMessage(msg);
              }
            },
            dbs: /* @__PURE__ */ Object.create(null),
            getDb: function(id, require2 = true) {
              return this.dbs[id] || (require2 ? toss("Unknown (or closed) DB ID:", id) : void 0);
            }
          };
          const affirmDbOpen = function(db = wState.dbList[0]) {
            return db && db.pointer ? db : toss("DB is not opened.");
          };
          const getMsgDb = function(msgData, affirmExists = true) {
            const db = wState.getDb(msgData.dbId, false) || wState.dbList[0];
            return affirmExists ? affirmDbOpen(db) : db;
          };
          const getDefaultDbId = function() {
            return wState.dbList[0] && getDbId(wState.dbList[0]);
          };
          const isSpecialDbFilename = (n2) => {
            return "" === n2 || ":" === n2[0];
          };
          const wMsgHandler = {
            open: function(ev) {
              const oargs = /* @__PURE__ */ Object.create(null), args = ev.args || /* @__PURE__ */ Object.create(null);
              if (args.simulateError) {
                toss("Throwing because of simulateError flag.");
              }
              const rc = /* @__PURE__ */ Object.create(null);
              oargs.vfs = args.vfs;
              oargs.filename = args.filename || "";
              const db = wState.open(oargs);
              rc.filename = db.filename;
              rc.persistent = !!sqlite33.capi.sqlite3_js_db_uses_vfs(
                db.pointer,
                "opfs"
              );
              rc.dbId = getDbId(db);
              rc.vfs = db.dbVfsName();
              return rc;
            },
            close: function(ev) {
              const db = getMsgDb(ev, false);
              const response = {
                filename: db && db.filename
              };
              if (db) {
                const doUnlink = ev.args && "object" === typeof ev.args ? !!ev.args.unlink : false;
                wState.close(db, doUnlink);
              }
              return response;
            },
            exec: function(ev) {
              const rc = "string" === typeof ev.args ? { sql: ev.args } : ev.args || /* @__PURE__ */ Object.create(null);
              if ("stmt" === rc.rowMode) {
                toss(
                  "Invalid rowMode for 'exec': stmt mode",
                  "does not work in the Worker API."
                );
              } else if (!rc.sql) {
                toss("'exec' requires input SQL.");
              }
              const db = getMsgDb(ev);
              if (rc.callback || Array.isArray(rc.resultRows)) {
                db._blobXfer = wState.xfer;
              }
              const theCallback = rc.callback;
              let rowNumber = 0;
              const hadColNames = !!rc.columnNames;
              if ("string" === typeof theCallback) {
                if (!hadColNames)
                  rc.columnNames = [];
                rc.callback = function(row, stmt) {
                  wState.post(
                    {
                      type: theCallback,
                      columnNames: rc.columnNames,
                      rowNumber: ++rowNumber,
                      row
                    },
                    wState.xfer
                  );
                };
              }
              try {
                const changeCount = !!rc.countChanges ? db.changes(true, 64 === rc.countChanges) : void 0;
                db.exec(rc);
                if (void 0 !== changeCount) {
                  rc.changeCount = db.changes(true, 64 === rc.countChanges) - changeCount;
                }
                if (rc.callback instanceof Function) {
                  rc.callback = theCallback;
                  wState.post({
                    type: theCallback,
                    columnNames: rc.columnNames,
                    rowNumber: null,
                    row: void 0
                  });
                }
              } finally {
                delete db._blobXfer;
                if (rc.callback)
                  rc.callback = theCallback;
              }
              return rc;
            },
            "config-get": function() {
              const rc = /* @__PURE__ */ Object.create(null), src2 = sqlite33.config;
              ["bigIntEnabled"].forEach(function(k2) {
                if (Object.getOwnPropertyDescriptor(src2, k2))
                  rc[k2] = src2[k2];
              });
              rc.version = sqlite33.version;
              rc.vfsList = sqlite33.capi.sqlite3_js_vfs_list();
              return rc;
            },
            export: function(ev) {
              const db = getMsgDb(ev);
              const response = {
                byteArray: sqlite33.capi.sqlite3_js_db_export(db.pointer),
                filename: db.filename,
                mimetype: "application/x-sqlite3"
              };
              wState.xfer.push(response.byteArray.buffer);
              return response;
            },
            toss: function(ev) {
              toss("Testing worker exception");
            }
          };
          globalThis.onmessage = async function(ev) {
            ev = ev.data;
            let result, dbId = ev.dbId, evType = ev.type;
            const arrivalTime = performance.now();
            try {
              if (wMsgHandler.hasOwnProperty(evType) && wMsgHandler[evType] instanceof Function) {
                result = await wMsgHandler[evType](ev);
              } else {
                toss("Unknown db worker message type:", ev.type);
              }
            } catch (err2) {
              evType = "error";
              result = {
                operation: ev.type,
                message: err2.message,
                errorClass: err2.name,
                input: ev
              };
              if (err2.stack) {
                result.stack = "string" === typeof err2.stack ? err2.stack.split(/\n\s*/) : err2.stack;
              }
              if (0)
                sqlite33.config.warn(
                  "Worker is propagating an exception to main thread.",
                  "Reporting it _here_ for the stack trace:",
                  err2,
                  result
                );
            }
            if (!dbId) {
              dbId = result.dbId || getDefaultDbId();
            }
            wState.post(
              {
                type: evType,
                dbId,
                messageId: ev.messageId,
                workerReceivedTime: arrivalTime,
                workerRespondTime: performance.now(),
                departureTime: ev.departureTime,
                result
              },
              wState.xfer
            );
          };
          globalThis.postMessage({
            type: "sqlite3-api",
            result: "worker1-ready"
          });
        }.bind({ sqlite3: sqlite32 });
      });
      "use strict";
      globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite32) {
        const wasm = sqlite32.wasm, capi = sqlite32.capi, toss = sqlite32.util.toss3;
        const vfs = /* @__PURE__ */ Object.create(null);
        sqlite32.vfs = vfs;
        capi.sqlite3_vfs.prototype.registerVfs = function(asDefault = false) {
          if (!(this instanceof sqlite32.capi.sqlite3_vfs)) {
            toss("Expecting a sqlite3_vfs-type argument.");
          }
          const rc = capi.sqlite3_vfs_register(this, asDefault ? 1 : 0);
          if (rc) {
            toss("sqlite3_vfs_register(", this, ") failed with rc", rc);
          }
          if (this.pointer !== capi.sqlite3_vfs_find(this.$zName)) {
            toss(
              "BUG: sqlite3_vfs_find(vfs.$zName) failed for just-installed VFS",
              this
            );
          }
          return this;
        };
        vfs.installVfs = function(opt) {
          let count = 0;
          const propList = ["io", "vfs"];
          for (const key of propList) {
            const o = opt[key];
            if (o) {
              ++count;
              o.struct.installMethods(o.methods, !!o.applyArgcCheck);
              if ("vfs" === key) {
                if (!o.struct.$zName && "string" === typeof o.name) {
                  o.struct.addOnDispose(
                    o.struct.$zName = wasm.allocCString(o.name)
                  );
                }
                o.struct.registerVfs(!!o.asDefault);
              }
            }
          }
          if (!count)
            toss(
              "Misuse: installVfs() options object requires at least",
              "one of:",
              propList
            );
          return this;
        };
      });
      "use strict";
      globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite32) {
        if (!sqlite32.wasm.exports.sqlite3_declare_vtab) {
          return;
        }
        const wasm = sqlite32.wasm, capi = sqlite32.capi, toss = sqlite32.util.toss3;
        const vtab = /* @__PURE__ */ Object.create(null);
        sqlite32.vtab = vtab;
        const sii = capi.sqlite3_index_info;
        sii.prototype.nthConstraint = function(n2, asPtr = false) {
          if (n2 < 0 || n2 >= this.$nConstraint)
            return false;
          const ptr = this.$aConstraint + sii.sqlite3_index_constraint.structInfo.sizeof * n2;
          return asPtr ? ptr : new sii.sqlite3_index_constraint(ptr);
        };
        sii.prototype.nthConstraintUsage = function(n2, asPtr = false) {
          if (n2 < 0 || n2 >= this.$nConstraint)
            return false;
          const ptr = this.$aConstraintUsage + sii.sqlite3_index_constraint_usage.structInfo.sizeof * n2;
          return asPtr ? ptr : new sii.sqlite3_index_constraint_usage(ptr);
        };
        sii.prototype.nthOrderBy = function(n2, asPtr = false) {
          if (n2 < 0 || n2 >= this.$nOrderBy)
            return false;
          const ptr = this.$aOrderBy + sii.sqlite3_index_orderby.structInfo.sizeof * n2;
          return asPtr ? ptr : new sii.sqlite3_index_orderby(ptr);
        };
        const __xWrapFactory = function(methodName, StructType) {
          return function(ptr, removeMapping = false) {
            if (0 === arguments.length)
              ptr = new StructType();
            if (ptr instanceof StructType) {
              this.set(ptr.pointer, ptr);
              return ptr;
            } else if (!wasm.isPtr(ptr)) {
              sqlite32.SQLite3Error.toss(
                "Invalid argument to",
                methodName + "()"
              );
            }
            let rc = this.get(ptr);
            if (removeMapping)
              this.delete(ptr);
            return rc;
          }.bind(/* @__PURE__ */ new Map());
        };
        const StructPtrMapper = function(name, StructType) {
          const __xWrap = __xWrapFactory(name, StructType);
          return Object.assign(/* @__PURE__ */ Object.create(null), {
            StructType,
            create: (ppOut) => {
              const rc = __xWrap();
              wasm.pokePtr(ppOut, rc.pointer);
              return rc;
            },
            get: (pCObj) => __xWrap(pCObj),
            unget: (pCObj) => __xWrap(pCObj, true),
            dispose: (pCObj) => {
              const o = __xWrap(pCObj, true);
              if (o)
                o.dispose();
            }
          });
        };
        vtab.xVtab = StructPtrMapper("xVtab", capi.sqlite3_vtab);
        vtab.xCursor = StructPtrMapper("xCursor", capi.sqlite3_vtab_cursor);
        vtab.xIndexInfo = (pIdxInfo) => new capi.sqlite3_index_info(pIdxInfo);
        vtab.xError = function f2(methodName, err2, defaultRc) {
          if (f2.errorReporter instanceof Function) {
            try {
              f2.errorReporter(
                "sqlite3_module::" + methodName + "(): " + err2.message
              );
            } catch (e2) {
            }
          }
          let rc;
          if (err2 instanceof sqlite32.WasmAllocError)
            rc = capi.SQLITE_NOMEM;
          else if (arguments.length > 2)
            rc = defaultRc;
          else if (err2 instanceof sqlite32.SQLite3Error)
            rc = err2.resultCode;
          return rc || capi.SQLITE_ERROR;
        };
        vtab.xError.errorReporter = 1 ? console.error.bind(console) : false;
        vtab.xRowid = (ppRowid64, value) => wasm.poke(ppRowid64, value, "i64");
        vtab.setupModule = function(opt) {
          let createdMod = false;
          const mod = this instanceof capi.sqlite3_module ? this : opt.struct || (createdMod = new capi.sqlite3_module());
          try {
            const methods = opt.methods || toss("Missing 'methods' object.");
            for (const e2 of Object.entries({
              xConnect: "xCreate",
              xDisconnect: "xDestroy"
            })) {
              const k2 = e2[0], v3 = e2[1];
              if (true === methods[k2])
                methods[k2] = methods[v3];
              else if (true === methods[v3])
                methods[v3] = methods[k2];
            }
            if (opt.catchExceptions) {
              const fwrap = function(methodName, func) {
                if (["xConnect", "xCreate"].indexOf(methodName) >= 0) {
                  return function(pDb2, pAux, argc, argv2, ppVtab, pzErr) {
                    try {
                      return func(...arguments) || 0;
                    } catch (e2) {
                      if (!(e2 instanceof sqlite32.WasmAllocError)) {
                        wasm.dealloc(wasm.peekPtr(pzErr));
                        wasm.pokePtr(pzErr, wasm.allocCString(e2.message));
                      }
                      return vtab.xError(methodName, e2);
                    }
                  };
                } else {
                  return function(...args) {
                    try {
                      return func(...args) || 0;
                    } catch (e2) {
                      return vtab.xError(methodName, e2);
                    }
                  };
                }
              };
              const mnames = [
                "xCreate",
                "xConnect",
                "xBestIndex",
                "xDisconnect",
                "xDestroy",
                "xOpen",
                "xClose",
                "xFilter",
                "xNext",
                "xEof",
                "xColumn",
                "xRowid",
                "xUpdate",
                "xBegin",
                "xSync",
                "xCommit",
                "xRollback",
                "xFindFunction",
                "xRename",
                "xSavepoint",
                "xRelease",
                "xRollbackTo",
                "xShadowName"
              ];
              const remethods = /* @__PURE__ */ Object.create(null);
              for (const k2 of mnames) {
                const m2 = methods[k2];
                if (!(m2 instanceof Function))
                  continue;
                else if ("xConnect" === k2 && methods.xCreate === m2) {
                  remethods[k2] = methods.xCreate;
                } else if ("xCreate" === k2 && methods.xConnect === m2) {
                  remethods[k2] = methods.xConnect;
                } else {
                  remethods[k2] = fwrap(k2, m2);
                }
              }
              mod.installMethods(remethods, false);
            } else {
              mod.installMethods(methods, !!opt.applyArgcCheck);
            }
            if (0 === mod.$iVersion) {
              let v3;
              if ("number" === typeof opt.iVersion)
                v3 = opt.iVersion;
              else if (mod.$xShadowName)
                v3 = 3;
              else if (mod.$xSavePoint || mod.$xRelease || mod.$xRollbackTo)
                v3 = 2;
              else
                v3 = 1;
              mod.$iVersion = v3;
            }
          } catch (e2) {
            if (createdMod)
              createdMod.dispose();
            throw e2;
          }
          return mod;
        };
        capi.sqlite3_module.prototype.setupModule = function(opt) {
          return vtab.setupModule.call(this, opt);
        };
      });
      "use strict";
      globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite32) {
        const installOpfsVfs = function callee2(options) {
          var _a8;
          if (!globalThis.SharedArrayBuffer || !globalThis.Atomics) {
            return Promise.reject(
              new Error(
                "Cannot install OPFS: Missing SharedArrayBuffer and/or Atomics. The server must emit the COOP/COEP response headers to enable those. See https://sqlite.org/wasm/doc/trunk/persistence.md#coop-coep"
              )
            );
          } else if ("undefined" === typeof WorkerGlobalScope) {
            return Promise.reject(
              new Error(
                "The OPFS sqlite3_vfs cannot run in the main thread because it requires Atomics.wait()."
              )
            );
          } else if (!globalThis.FileSystemHandle || !globalThis.FileSystemDirectoryHandle || !globalThis.FileSystemFileHandle || !globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle || !((_a8 = navigator == null ? void 0 : navigator.storage) == null ? void 0 : _a8.getDirectory)) {
            return Promise.reject(new Error("Missing required OPFS APIs."));
          }
          if (!options || "object" !== typeof options) {
            options = /* @__PURE__ */ Object.create(null);
          }
          const urlParams = new URL(globalThis.location.href).searchParams;
          if (urlParams.has("opfs-disable")) {
            return Promise.resolve(sqlite32);
          }
          if (void 0 === options.verbose) {
            options.verbose = urlParams.has("opfs-verbose") ? +urlParams.get("opfs-verbose") || 2 : 1;
          }
          if (void 0 === options.sanityChecks) {
            options.sanityChecks = urlParams.has("opfs-sanity-check");
          }
          if (void 0 === options.proxyUri) {
            options.proxyUri = callee2.defaultProxyUri;
          }
          if ("function" === typeof options.proxyUri) {
            options.proxyUri = options.proxyUri();
          }
          const thePromise = new Promise(function(promiseResolve_, promiseReject_) {
            const loggers = [
              sqlite32.config.error,
              sqlite32.config.warn,
              sqlite32.config.log
            ];
            const logImpl = (level, ...args) => {
              if (options.verbose > level)
                loggers[level]("OPFS syncer:", ...args);
            };
            const log2 = (...args) => logImpl(2, ...args);
            const warn = (...args) => logImpl(1, ...args);
            const error = (...args) => logImpl(0, ...args);
            const toss = sqlite32.util.toss;
            const capi = sqlite32.capi;
            const util = sqlite32.util;
            const wasm = sqlite32.wasm;
            const sqlite3_vfs = capi.sqlite3_vfs;
            const sqlite3_file = capi.sqlite3_file;
            const sqlite3_io_methods = capi.sqlite3_io_methods;
            const opfsUtil = /* @__PURE__ */ Object.create(null);
            const thisThreadHasOPFS = () => {
              var _a9;
              return globalThis.FileSystemHandle && globalThis.FileSystemDirectoryHandle && globalThis.FileSystemFileHandle && globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle && ((_a9 = navigator == null ? void 0 : navigator.storage) == null ? void 0 : _a9.getDirectory);
            };
            opfsUtil.metrics = {
              dump: function() {
                let k2, n2 = 0, t2 = 0, w2 = 0;
                for (k2 in state.opIds) {
                  const m2 = metrics[k2];
                  n2 += m2.count;
                  t2 += m2.time;
                  w2 += m2.wait;
                  m2.avgTime = m2.count && m2.time ? m2.time / m2.count : 0;
                  m2.avgWait = m2.count && m2.wait ? m2.wait / m2.count : 0;
                }
                sqlite32.config.log(
                  globalThis.location.href,
                  "metrics for",
                  globalThis.location.href,
                  ":",
                  metrics,
                  "\nTotal of",
                  n2,
                  "op(s) for",
                  t2,
                  "ms (incl. " + w2 + " ms of waiting on the async side)"
                );
                sqlite32.config.log("Serialization metrics:", metrics.s11n);
                W2.postMessage({ type: "opfs-async-metrics" });
              },
              reset: function() {
                let k2;
                const r3 = (m2) => m2.count = m2.time = m2.wait = 0;
                for (k2 in state.opIds) {
                  r3(metrics[k2] = /* @__PURE__ */ Object.create(null));
                }
                let s2 = metrics.s11n = /* @__PURE__ */ Object.create(null);
                s2 = s2.serialize = /* @__PURE__ */ Object.create(null);
                s2.count = s2.time = 0;
                s2 = metrics.s11n.deserialize = /* @__PURE__ */ Object.create(null);
                s2.count = s2.time = 0;
              }
            };
            const opfsIoMethods = new sqlite3_io_methods();
            const opfsVfs = new sqlite3_vfs().addOnDispose(
              () => opfsIoMethods.dispose()
            );
            let promiseWasRejected = void 0;
            const promiseReject = (err2) => {
              promiseWasRejected = true;
              opfsVfs.dispose();
              return promiseReject_(err2);
            };
            const promiseResolve = () => {
              promiseWasRejected = false;
              return promiseResolve_(sqlite32);
            };
            const W2 = new Worker(
              new URL("sqlite3-opfs-async-proxy.js", import.meta.url)
            );
            setTimeout(() => {
              if (void 0 === promiseWasRejected) {
                promiseReject(
                  new Error(
                    "Timeout while waiting for OPFS async proxy worker."
                  )
                );
              }
            }, 4e3);
            W2._originalOnError = W2.onerror;
            W2.onerror = function(err2) {
              error("Error initializing OPFS asyncer:", err2);
              promiseReject(
                new Error(
                  "Loading OPFS async Worker failed for unknown reasons."
                )
              );
            };
            const pDVfs = capi.sqlite3_vfs_find(null);
            const dVfs = pDVfs ? new sqlite3_vfs(pDVfs) : null;
            opfsIoMethods.$iVersion = 1;
            opfsVfs.$iVersion = 2;
            opfsVfs.$szOsFile = capi.sqlite3_file.structInfo.sizeof;
            opfsVfs.$mxPathname = 1024;
            opfsVfs.$zName = wasm.allocCString("opfs");
            opfsVfs.$xDlOpen = opfsVfs.$xDlError = opfsVfs.$xDlSym = opfsVfs.$xDlClose = null;
            opfsVfs.addOnDispose(
              "$zName",
              opfsVfs.$zName,
              "cleanup default VFS wrapper",
              () => dVfs ? dVfs.dispose() : null
            );
            const state = /* @__PURE__ */ Object.create(null);
            state.verbose = options.verbose;
            state.littleEndian = (() => {
              const buffer = new ArrayBuffer(2);
              new DataView(buffer).setInt16(0, 256, true);
              return new Int16Array(buffer)[0] === 256;
            })();
            state.asyncIdleWaitTime = 150;
            state.asyncS11nExceptions = 1;
            state.fileBufferSize = 1024 * 64;
            state.sabS11nOffset = state.fileBufferSize;
            state.sabS11nSize = opfsVfs.$mxPathname * 2;
            state.sabIO = new SharedArrayBuffer(
              state.fileBufferSize + state.sabS11nSize
            );
            state.opIds = /* @__PURE__ */ Object.create(null);
            const metrics = /* @__PURE__ */ Object.create(null);
            {
              let i2 = 0;
              state.opIds.whichOp = i2++;
              state.opIds.rc = i2++;
              state.opIds.xAccess = i2++;
              state.opIds.xClose = i2++;
              state.opIds.xDelete = i2++;
              state.opIds.xDeleteNoWait = i2++;
              state.opIds.xFileSize = i2++;
              state.opIds.xLock = i2++;
              state.opIds.xOpen = i2++;
              state.opIds.xRead = i2++;
              state.opIds.xSleep = i2++;
              state.opIds.xSync = i2++;
              state.opIds.xTruncate = i2++;
              state.opIds.xUnlock = i2++;
              state.opIds.xWrite = i2++;
              state.opIds.mkdir = i2++;
              state.opIds["opfs-async-metrics"] = i2++;
              state.opIds["opfs-async-shutdown"] = i2++;
              state.opIds.retry = i2++;
              state.sabOP = new SharedArrayBuffer(i2 * 4);
              opfsUtil.metrics.reset();
            }
            state.sq3Codes = /* @__PURE__ */ Object.create(null);
            [
              "SQLITE_ACCESS_EXISTS",
              "SQLITE_ACCESS_READWRITE",
              "SQLITE_BUSY",
              "SQLITE_CANTOPEN",
              "SQLITE_ERROR",
              "SQLITE_IOERR",
              "SQLITE_IOERR_ACCESS",
              "SQLITE_IOERR_CLOSE",
              "SQLITE_IOERR_DELETE",
              "SQLITE_IOERR_FSYNC",
              "SQLITE_IOERR_LOCK",
              "SQLITE_IOERR_READ",
              "SQLITE_IOERR_SHORT_READ",
              "SQLITE_IOERR_TRUNCATE",
              "SQLITE_IOERR_UNLOCK",
              "SQLITE_IOERR_WRITE",
              "SQLITE_LOCK_EXCLUSIVE",
              "SQLITE_LOCK_NONE",
              "SQLITE_LOCK_PENDING",
              "SQLITE_LOCK_RESERVED",
              "SQLITE_LOCK_SHARED",
              "SQLITE_LOCKED",
              "SQLITE_MISUSE",
              "SQLITE_NOTFOUND",
              "SQLITE_OPEN_CREATE",
              "SQLITE_OPEN_DELETEONCLOSE",
              "SQLITE_OPEN_MAIN_DB",
              "SQLITE_OPEN_READONLY"
            ].forEach((k2) => {
              if (void 0 === (state.sq3Codes[k2] = capi[k2])) {
                toss("Maintenance required: not found:", k2);
              }
            });
            state.opfsFlags = Object.assign(/* @__PURE__ */ Object.create(null), {
              OPFS_UNLOCK_ASAP: 1,
              OPFS_UNLINK_BEFORE_OPEN: 2,
              defaultUnlockAsap: false
            });
            const opRun = (op, ...args) => {
              const opNdx = state.opIds[op] || toss("Invalid op ID:", op);
              state.s11n.serialize(...args);
              Atomics.store(state.sabOPView, state.opIds.rc, -1);
              Atomics.store(state.sabOPView, state.opIds.whichOp, opNdx);
              Atomics.notify(state.sabOPView, state.opIds.whichOp);
              const t2 = performance.now();
              while ("not-equal" !== Atomics.wait(state.sabOPView, state.opIds.rc, -1)) {
              }
              const rc = Atomics.load(state.sabOPView, state.opIds.rc);
              metrics[op].wait += performance.now() - t2;
              if (rc && state.asyncS11nExceptions) {
                const err2 = state.s11n.deserialize();
                if (err2)
                  error(op + "() async error:", ...err2);
              }
              return rc;
            };
            opfsUtil.debug = {
              asyncShutdown: () => {
                warn(
                  "Shutting down OPFS async listener. The OPFS VFS will no longer work."
                );
                opRun("opfs-async-shutdown");
              },
              asyncRestart: () => {
                warn(
                  "Attempting to restart OPFS VFS async listener. Might work, might not."
                );
                W2.postMessage({ type: "opfs-async-restart" });
              }
            };
            const initS11n = () => {
              if (state.s11n)
                return state.s11n;
              const textDecoder = new TextDecoder(), textEncoder = new TextEncoder("utf-8"), viewU8 = new Uint8Array(
                state.sabIO,
                state.sabS11nOffset,
                state.sabS11nSize
              ), viewDV = new DataView(
                state.sabIO,
                state.sabS11nOffset,
                state.sabS11nSize
              );
              state.s11n = /* @__PURE__ */ Object.create(null);
              const TypeIds = /* @__PURE__ */ Object.create(null);
              TypeIds.number = {
                id: 1,
                size: 8,
                getter: "getFloat64",
                setter: "setFloat64"
              };
              TypeIds.bigint = {
                id: 2,
                size: 8,
                getter: "getBigInt64",
                setter: "setBigInt64"
              };
              TypeIds.boolean = {
                id: 3,
                size: 4,
                getter: "getInt32",
                setter: "setInt32"
              };
              TypeIds.string = { id: 4 };
              const getTypeId = (v3) => TypeIds[typeof v3] || toss(
                "Maintenance required: this value type cannot be serialized.",
                v3
              );
              const getTypeIdById = (tid) => {
                switch (tid) {
                  case TypeIds.number.id:
                    return TypeIds.number;
                  case TypeIds.bigint.id:
                    return TypeIds.bigint;
                  case TypeIds.boolean.id:
                    return TypeIds.boolean;
                  case TypeIds.string.id:
                    return TypeIds.string;
                  default:
                    toss("Invalid type ID:", tid);
                }
              };
              state.s11n.deserialize = function(clear = false) {
                ++metrics.s11n.deserialize.count;
                const t2 = performance.now();
                const argc = viewU8[0];
                const rc = argc ? [] : null;
                if (argc) {
                  const typeIds = [];
                  let offset = 1, i2, n2, v3;
                  for (i2 = 0; i2 < argc; ++i2, ++offset) {
                    typeIds.push(getTypeIdById(viewU8[offset]));
                  }
                  for (i2 = 0; i2 < argc; ++i2) {
                    const t3 = typeIds[i2];
                    if (t3.getter) {
                      v3 = viewDV[t3.getter](offset, state.littleEndian);
                      offset += t3.size;
                    } else {
                      n2 = viewDV.getInt32(offset, state.littleEndian);
                      offset += 4;
                      v3 = textDecoder.decode(viewU8.slice(offset, offset + n2));
                      offset += n2;
                    }
                    rc.push(v3);
                  }
                }
                if (clear)
                  viewU8[0] = 0;
                metrics.s11n.deserialize.time += performance.now() - t2;
                return rc;
              };
              state.s11n.serialize = function(...args) {
                const t2 = performance.now();
                ++metrics.s11n.serialize.count;
                if (args.length) {
                  const typeIds = [];
                  let i2 = 0, offset = 1;
                  viewU8[0] = args.length & 255;
                  for (; i2 < args.length; ++i2, ++offset) {
                    typeIds.push(getTypeId(args[i2]));
                    viewU8[offset] = typeIds[i2].id;
                  }
                  for (i2 = 0; i2 < args.length; ++i2) {
                    const t3 = typeIds[i2];
                    if (t3.setter) {
                      viewDV[t3.setter](offset, args[i2], state.littleEndian);
                      offset += t3.size;
                    } else {
                      const s2 = textEncoder.encode(args[i2]);
                      viewDV.setInt32(offset, s2.byteLength, state.littleEndian);
                      offset += 4;
                      viewU8.set(s2, offset);
                      offset += s2.byteLength;
                    }
                  }
                } else {
                  viewU8[0] = 0;
                }
                metrics.s11n.serialize.time += performance.now() - t2;
              };
              return state.s11n;
            };
            const randomFilename = function f2(len = 16) {
              if (!f2._chars) {
                f2._chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789";
                f2._n = f2._chars.length;
              }
              const a3 = [];
              let i2 = 0;
              for (; i2 < len; ++i2) {
                const ndx = Math.random() * (f2._n * 64) % f2._n | 0;
                a3[i2] = f2._chars[ndx];
              }
              return a3.join("");
            };
            const __openFiles = /* @__PURE__ */ Object.create(null);
            const opTimer = /* @__PURE__ */ Object.create(null);
            opTimer.op = void 0;
            opTimer.start = void 0;
            const mTimeStart = (op) => {
              opTimer.start = performance.now();
              opTimer.op = op;
              ++metrics[op].count;
            };
            const mTimeEnd = () => metrics[opTimer.op].time += performance.now() - opTimer.start;
            const ioSyncWrappers = {
              xCheckReservedLock: function(pFile, pOut) {
                wasm.poke(pOut, 0, "i32");
                return 0;
              },
              xClose: function(pFile) {
                mTimeStart("xClose");
                let rc = 0;
                const f2 = __openFiles[pFile];
                if (f2) {
                  delete __openFiles[pFile];
                  rc = opRun("xClose", pFile);
                  if (f2.sq3File)
                    f2.sq3File.dispose();
                }
                mTimeEnd();
                return rc;
              },
              xDeviceCharacteristics: function(pFile) {
                return capi.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
              },
              xFileControl: function(pFile, opId, pArg) {
                return capi.SQLITE_NOTFOUND;
              },
              xFileSize: function(pFile, pSz64) {
                mTimeStart("xFileSize");
                let rc = opRun("xFileSize", pFile);
                if (0 == rc) {
                  try {
                    const sz = state.s11n.deserialize()[0];
                    wasm.poke(pSz64, sz, "i64");
                  } catch (e2) {
                    error("Unexpected error reading xFileSize() result:", e2);
                    rc = state.sq3Codes.SQLITE_IOERR;
                  }
                }
                mTimeEnd();
                return rc;
              },
              xLock: function(pFile, lockType) {
                mTimeStart("xLock");
                const f2 = __openFiles[pFile];
                let rc = 0;
                if (!f2.lockType) {
                  rc = opRun("xLock", pFile, lockType);
                  if (0 === rc)
                    f2.lockType = lockType;
                } else {
                  f2.lockType = lockType;
                }
                mTimeEnd();
                return rc;
              },
              xRead: function(pFile, pDest, n2, offset64) {
                mTimeStart("xRead");
                const f2 = __openFiles[pFile];
                let rc;
                try {
                  rc = opRun("xRead", pFile, n2, Number(offset64));
                  if (0 === rc || capi.SQLITE_IOERR_SHORT_READ === rc) {
                    wasm.heap8u().set(f2.sabView.subarray(0, n2), pDest);
                  }
                } catch (e2) {
                  error("xRead(", arguments, ") failed:", e2, f2);
                  rc = capi.SQLITE_IOERR_READ;
                }
                mTimeEnd();
                return rc;
              },
              xSync: function(pFile, flags) {
                mTimeStart("xSync");
                ++metrics.xSync.count;
                const rc = opRun("xSync", pFile, flags);
                mTimeEnd();
                return rc;
              },
              xTruncate: function(pFile, sz64) {
                mTimeStart("xTruncate");
                const rc = opRun("xTruncate", pFile, Number(sz64));
                mTimeEnd();
                return rc;
              },
              xUnlock: function(pFile, lockType) {
                mTimeStart("xUnlock");
                const f2 = __openFiles[pFile];
                let rc = 0;
                if (capi.SQLITE_LOCK_NONE === lockType && f2.lockType) {
                  rc = opRun("xUnlock", pFile, lockType);
                }
                if (0 === rc)
                  f2.lockType = lockType;
                mTimeEnd();
                return rc;
              },
              xWrite: function(pFile, pSrc, n2, offset64) {
                mTimeStart("xWrite");
                const f2 = __openFiles[pFile];
                let rc;
                try {
                  f2.sabView.set(wasm.heap8u().subarray(pSrc, pSrc + n2));
                  rc = opRun("xWrite", pFile, n2, Number(offset64));
                } catch (e2) {
                  error("xWrite(", arguments, ") failed:", e2, f2);
                  rc = capi.SQLITE_IOERR_WRITE;
                }
                mTimeEnd();
                return rc;
              }
            };
            const vfsSyncWrappers = {
              xAccess: function(pVfs, zName, flags, pOut) {
                mTimeStart("xAccess");
                const rc = opRun("xAccess", wasm.cstrToJs(zName));
                wasm.poke(pOut, rc ? 0 : 1, "i32");
                mTimeEnd();
                return 0;
              },
              xCurrentTime: function(pVfs, pOut) {
                wasm.poke(
                  pOut,
                  24405875e-1 + (/* @__PURE__ */ new Date()).getTime() / 864e5,
                  "double"
                );
                return 0;
              },
              xCurrentTimeInt64: function(pVfs, pOut) {
                wasm.poke(
                  pOut,
                  24405875e-1 * 864e5 + (/* @__PURE__ */ new Date()).getTime(),
                  "i64"
                );
                return 0;
              },
              xDelete: function(pVfs, zName, doSyncDir) {
                mTimeStart("xDelete");
                const rc = opRun(
                  "xDelete",
                  wasm.cstrToJs(zName),
                  doSyncDir,
                  false
                );
                mTimeEnd();
                return rc;
              },
              xFullPathname: function(pVfs, zName, nOut, pOut) {
                const i2 = wasm.cstrncpy(pOut, zName, nOut);
                return i2 < nOut ? 0 : capi.SQLITE_CANTOPEN;
              },
              xGetLastError: function(pVfs, nOut, pOut) {
                warn("OPFS xGetLastError() has nothing sensible to return.");
                return 0;
              },
              xOpen: function f2(pVfs, zName, pFile, flags, pOutFlags) {
                mTimeStart("xOpen");
                let opfsFlags = 0;
                if (0 === zName) {
                  zName = randomFilename();
                } else if (wasm.isPtr(zName)) {
                  if (capi.sqlite3_uri_boolean(zName, "opfs-unlock-asap", 0)) {
                    opfsFlags |= state.opfsFlags.OPFS_UNLOCK_ASAP;
                  }
                  if (capi.sqlite3_uri_boolean(zName, "delete-before-open", 0)) {
                    opfsFlags |= state.opfsFlags.OPFS_UNLINK_BEFORE_OPEN;
                  }
                  zName = wasm.cstrToJs(zName);
                }
                const fh = /* @__PURE__ */ Object.create(null);
                fh.fid = pFile;
                fh.filename = zName;
                fh.sab = new SharedArrayBuffer(state.fileBufferSize);
                fh.flags = flags;
                fh.readOnly = !(sqlite32.SQLITE_OPEN_CREATE & flags) && !!(flags & capi.SQLITE_OPEN_READONLY);
                const rc = opRun("xOpen", pFile, zName, flags, opfsFlags);
                if (!rc) {
                  if (fh.readOnly) {
                    wasm.poke(pOutFlags, capi.SQLITE_OPEN_READONLY, "i32");
                  }
                  __openFiles[pFile] = fh;
                  fh.sabView = state.sabFileBufView;
                  fh.sq3File = new sqlite3_file(pFile);
                  fh.sq3File.$pMethods = opfsIoMethods.pointer;
                  fh.lockType = capi.SQLITE_LOCK_NONE;
                }
                mTimeEnd();
                return rc;
              }
            };
            if (dVfs) {
              opfsVfs.$xRandomness = dVfs.$xRandomness;
              opfsVfs.$xSleep = dVfs.$xSleep;
            }
            if (!opfsVfs.$xRandomness) {
              vfsSyncWrappers.xRandomness = function(pVfs, nOut, pOut) {
                const heap = wasm.heap8u();
                let i2 = 0;
                for (; i2 < nOut; ++i2)
                  heap[pOut + i2] = Math.random() * 255e3 & 255;
                return i2;
              };
            }
            if (!opfsVfs.$xSleep) {
              vfsSyncWrappers.xSleep = function(pVfs, ms) {
                Atomics.wait(state.sabOPView, state.opIds.xSleep, 0, ms);
                return 0;
              };
            }
            opfsUtil.getResolvedPath = function(filename, splitIt) {
              const p3 = new URL(filename, "file://irrelevant").pathname;
              return splitIt ? p3.split("/").filter((v3) => !!v3) : p3;
            };
            opfsUtil.getDirForFilename = async function f2(absFilename, createDirs = false) {
              const path2 = opfsUtil.getResolvedPath(absFilename, true);
              const filename = path2.pop();
              let dh = opfsUtil.rootDirectory;
              for (const dirName of path2) {
                if (dirName) {
                  dh = await dh.getDirectoryHandle(dirName, {
                    create: !!createDirs
                  });
                }
              }
              return [dh, filename];
            };
            opfsUtil.mkdir = async function(absDirName) {
              try {
                await opfsUtil.getDirForFilename(
                  absDirName + "/filepart",
                  true
                );
                return true;
              } catch (e2) {
                return false;
              }
            };
            opfsUtil.entryExists = async function(fsEntryName) {
              try {
                const [dh, fn] = await opfsUtil.getDirForFilename(fsEntryName);
                await dh.getFileHandle(fn);
                return true;
              } catch (e2) {
                return false;
              }
            };
            opfsUtil.randomFilename = randomFilename;
            opfsUtil.treeList = async function() {
              const doDir = async function callee3(dirHandle, tgt) {
                tgt.name = dirHandle.name;
                tgt.dirs = [];
                tgt.files = [];
                for await (const handle of dirHandle.values()) {
                  if ("directory" === handle.kind) {
                    const subDir = /* @__PURE__ */ Object.create(null);
                    tgt.dirs.push(subDir);
                    await callee3(handle, subDir);
                  } else {
                    tgt.files.push(handle.name);
                  }
                }
              };
              const root = /* @__PURE__ */ Object.create(null);
              await doDir(opfsUtil.rootDirectory, root);
              return root;
            };
            opfsUtil.rmfr = async function() {
              const dir = opfsUtil.rootDirectory, opt = { recurse: true };
              for await (const handle of dir.values()) {
                dir.removeEntry(handle.name, opt);
              }
            };
            opfsUtil.unlink = async function(fsEntryName, recursive = false, throwOnError = false) {
              try {
                const [hDir, filenamePart] = await opfsUtil.getDirForFilename(
                  fsEntryName,
                  false
                );
                await hDir.removeEntry(filenamePart, { recursive });
                return true;
              } catch (e2) {
                if (throwOnError) {
                  throw new Error(
                    "unlink(",
                    arguments[0],
                    ") failed: " + e2.message,
                    {
                      cause: e2
                    }
                  );
                }
                return false;
              }
            };
            opfsUtil.traverse = async function(opt) {
              const defaultOpt = {
                recursive: true,
                directory: opfsUtil.rootDirectory
              };
              if ("function" === typeof opt) {
                opt = { callback: opt };
              }
              opt = Object.assign(defaultOpt, opt || {});
              const doDir = async function callee3(dirHandle, depth) {
                for await (const handle of dirHandle.values()) {
                  if (false === opt.callback(handle, dirHandle, depth))
                    return false;
                  else if (opt.recursive && "directory" === handle.kind) {
                    if (false === await callee3(handle, depth + 1))
                      break;
                  }
                }
              };
              doDir(opt.directory, 0);
            };
            const importDbChunked = async function(filename, callback) {
              const [hDir, fnamePart] = await opfsUtil.getDirForFilename(
                filename,
                true
              );
              const hFile = await hDir.getFileHandle(fnamePart, {
                create: true
              });
              let sah = await hFile.createSyncAccessHandle();
              let nWrote = 0, chunk, checkedHeader = false, err2 = false;
              try {
                sah.truncate(0);
                while (void 0 !== (chunk = await callback())) {
                  if (chunk instanceof ArrayBuffer)
                    chunk = new Uint8Array(chunk);
                  if (0 === nWrote && chunk.byteLength >= 15) {
                    util.affirmDbHeader(chunk);
                    checkedHeader = true;
                  }
                  sah.write(chunk, { at: nWrote });
                  nWrote += chunk.byteLength;
                }
                if (nWrote < 512 || 0 !== nWrote % 512) {
                  toss(
                    "Input size",
                    nWrote,
                    "is not correct for an SQLite database."
                  );
                }
                if (!checkedHeader) {
                  const header = new Uint8Array(20);
                  sah.read(header, { at: 0 });
                  util.affirmDbHeader(header);
                }
                sah.write(new Uint8Array([1, 1]), { at: 18 });
                return nWrote;
              } catch (e2) {
                await sah.close();
                sah = void 0;
                await hDir.removeEntry(fnamePart).catch(() => {
                });
                throw e2;
              } finally {
                if (sah)
                  await sah.close();
              }
            };
            opfsUtil.importDb = async function(filename, bytes) {
              if (bytes instanceof Function) {
                return importDbChunked(filename, bytes);
              }
              if (bytes instanceof ArrayBuffer)
                bytes = new Uint8Array(bytes);
              util.affirmIsDb(bytes);
              const n2 = bytes.byteLength;
              const [hDir, fnamePart] = await opfsUtil.getDirForFilename(
                filename,
                true
              );
              let sah, err2, nWrote = 0;
              try {
                const hFile = await hDir.getFileHandle(fnamePart, {
                  create: true
                });
                sah = await hFile.createSyncAccessHandle();
                sah.truncate(0);
                nWrote = sah.write(bytes, { at: 0 });
                if (nWrote != n2) {
                  toss(
                    "Expected to write " + n2 + " bytes but wrote " + nWrote + "."
                  );
                }
                sah.write(new Uint8Array([1, 1]), { at: 18 });
                return nWrote;
              } catch (e2) {
                if (sah) {
                  await sah.close();
                  sah = void 0;
                }
                await hDir.removeEntry(fnamePart).catch(() => {
                });
                throw e2;
              } finally {
                if (sah)
                  await sah.close();
              }
            };
            if (sqlite32.oo1) {
              const OpfsDb = function(...args) {
                const opt = sqlite32.oo1.DB.dbCtorHelper.normalizeArgs(...args);
                opt.vfs = opfsVfs.$zName;
                sqlite32.oo1.DB.dbCtorHelper.call(this, opt);
              };
              OpfsDb.prototype = Object.create(sqlite32.oo1.DB.prototype);
              sqlite32.oo1.OpfsDb = OpfsDb;
              OpfsDb.importDb = opfsUtil.importDb;
              sqlite32.oo1.DB.dbCtorHelper.setVfsPostOpenCallback(
                opfsVfs.pointer,
                function(oo1Db, sqlite33) {
                  sqlite33.capi.sqlite3_busy_timeout(oo1Db, 1e4);
                }
              );
            }
            const sanityCheck = function() {
              const scope = wasm.scopedAllocPush();
              const sq3File = new sqlite3_file();
              try {
                const fid = sq3File.pointer;
                const openFlags = capi.SQLITE_OPEN_CREATE | capi.SQLITE_OPEN_READWRITE | capi.SQLITE_OPEN_MAIN_DB;
                const pOut = wasm.scopedAlloc(8);
                const dbFile = "/sanity/check/file" + randomFilename(8);
                const zDbFile = wasm.scopedAllocCString(dbFile);
                let rc;
                state.s11n.serialize("This is \xE4 string.");
                rc = state.s11n.deserialize();
                log2("deserialize() says:", rc);
                if ("This is \xE4 string." !== rc[0])
                  toss("String d13n error.");
                vfsSyncWrappers.xAccess(opfsVfs.pointer, zDbFile, 0, pOut);
                rc = wasm.peek(pOut, "i32");
                log2("xAccess(", dbFile, ") exists ?=", rc);
                rc = vfsSyncWrappers.xOpen(
                  opfsVfs.pointer,
                  zDbFile,
                  fid,
                  openFlags,
                  pOut
                );
                log2(
                  "open rc =",
                  rc,
                  "state.sabOPView[xOpen] =",
                  state.sabOPView[state.opIds.xOpen]
                );
                if (0 !== rc) {
                  error("open failed with code", rc);
                  return;
                }
                vfsSyncWrappers.xAccess(opfsVfs.pointer, zDbFile, 0, pOut);
                rc = wasm.peek(pOut, "i32");
                if (!rc)
                  toss("xAccess() failed to detect file.");
                rc = ioSyncWrappers.xSync(sq3File.pointer, 0);
                if (rc)
                  toss("sync failed w/ rc", rc);
                rc = ioSyncWrappers.xTruncate(sq3File.pointer, 1024);
                if (rc)
                  toss("truncate failed w/ rc", rc);
                wasm.poke(pOut, 0, "i64");
                rc = ioSyncWrappers.xFileSize(sq3File.pointer, pOut);
                if (rc)
                  toss("xFileSize failed w/ rc", rc);
                log2("xFileSize says:", wasm.peek(pOut, "i64"));
                rc = ioSyncWrappers.xWrite(sq3File.pointer, zDbFile, 10, 1);
                if (rc)
                  toss("xWrite() failed!");
                const readBuf = wasm.scopedAlloc(16);
                rc = ioSyncWrappers.xRead(sq3File.pointer, readBuf, 6, 2);
                wasm.poke(readBuf + 6, 0);
                let jRead = wasm.cstrToJs(readBuf);
                log2("xRead() got:", jRead);
                if ("sanity" !== jRead)
                  toss("Unexpected xRead() value.");
                if (vfsSyncWrappers.xSleep) {
                  log2("xSleep()ing before close()ing...");
                  vfsSyncWrappers.xSleep(opfsVfs.pointer, 2e3);
                  log2("waking up from xSleep()");
                }
                rc = ioSyncWrappers.xClose(fid);
                log2("xClose rc =", rc, "sabOPView =", state.sabOPView);
                log2("Deleting file:", dbFile);
                vfsSyncWrappers.xDelete(opfsVfs.pointer, zDbFile, 4660);
                vfsSyncWrappers.xAccess(opfsVfs.pointer, zDbFile, 0, pOut);
                rc = wasm.peek(pOut, "i32");
                if (rc)
                  toss(
                    "Expecting 0 from xAccess(",
                    dbFile,
                    ") after xDelete()."
                  );
                warn("End of OPFS sanity checks.");
              } finally {
                sq3File.dispose();
                wasm.scopedAllocPop(scope);
              }
            };
            W2.onmessage = function({ data }) {
              switch (data.type) {
                case "opfs-unavailable":
                  promiseReject(new Error(data.payload.join(" ")));
                  break;
                case "opfs-async-loaded":
                  W2.postMessage({ type: "opfs-async-init", args: state });
                  break;
                case "opfs-async-inited": {
                  if (true === promiseWasRejected) {
                    break;
                  }
                  try {
                    sqlite32.vfs.installVfs({
                      io: { struct: opfsIoMethods, methods: ioSyncWrappers },
                      vfs: { struct: opfsVfs, methods: vfsSyncWrappers }
                    });
                    state.sabOPView = new Int32Array(state.sabOP);
                    state.sabFileBufView = new Uint8Array(
                      state.sabIO,
                      0,
                      state.fileBufferSize
                    );
                    state.sabS11nView = new Uint8Array(
                      state.sabIO,
                      state.sabS11nOffset,
                      state.sabS11nSize
                    );
                    initS11n();
                    if (options.sanityChecks) {
                      warn(
                        "Running sanity checks because of opfs-sanity-check URL arg..."
                      );
                      sanityCheck();
                    }
                    if (thisThreadHasOPFS()) {
                      navigator.storage.getDirectory().then((d2) => {
                        W2.onerror = W2._originalOnError;
                        delete W2._originalOnError;
                        sqlite32.opfs = opfsUtil;
                        opfsUtil.rootDirectory = d2;
                        log2("End of OPFS sqlite3_vfs setup.", opfsVfs);
                        promiseResolve();
                      }).catch(promiseReject);
                    } else {
                      promiseResolve();
                    }
                  } catch (e2) {
                    error(e2);
                    promiseReject(e2);
                  }
                  break;
                }
                default: {
                  const errMsg = "Unexpected message from the OPFS async worker: " + JSON.stringify(data);
                  error(errMsg);
                  promiseReject(new Error(errMsg));
                  break;
                }
              }
            };
          });
          return thePromise;
        };
        installOpfsVfs.defaultProxyUri = "sqlite3-opfs-async-proxy.js";
        globalThis.sqlite3ApiBootstrap.initializersAsync.push(
          async (sqlite33) => {
            try {
              let proxyJs = installOpfsVfs.defaultProxyUri;
              if (sqlite33.scriptInfo.sqlite3Dir) {
                installOpfsVfs.defaultProxyUri = sqlite33.scriptInfo.sqlite3Dir + proxyJs;
              }
              return installOpfsVfs().catch((e2) => {
                sqlite33.config.warn(
                  "Ignoring inability to install OPFS sqlite3_vfs:",
                  e2.message
                );
              });
            } catch (e2) {
              sqlite33.config.error("installOpfsVfs() exception:", e2);
              return Promise.reject(e2);
            }
          }
        );
      });
      globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite32) {
        "use strict";
        const toss = sqlite32.util.toss;
        const toss3 = sqlite32.util.toss3;
        const initPromises = /* @__PURE__ */ Object.create(null);
        const capi = sqlite32.capi;
        const util = sqlite32.util;
        const wasm = sqlite32.wasm;
        const SECTOR_SIZE = 4096;
        const HEADER_MAX_PATH_SIZE = 512;
        const HEADER_FLAGS_SIZE = 4;
        const HEADER_DIGEST_SIZE = 8;
        const HEADER_CORPUS_SIZE = HEADER_MAX_PATH_SIZE + HEADER_FLAGS_SIZE;
        const HEADER_OFFSET_FLAGS = HEADER_MAX_PATH_SIZE;
        const HEADER_OFFSET_DIGEST = HEADER_CORPUS_SIZE;
        const HEADER_OFFSET_DATA = SECTOR_SIZE;
        const PERSISTENT_FILE_TYPES = capi.SQLITE_OPEN_MAIN_DB | capi.SQLITE_OPEN_MAIN_JOURNAL | capi.SQLITE_OPEN_SUPER_JOURNAL | capi.SQLITE_OPEN_WAL;
        const OPAQUE_DIR_NAME = ".opaque";
        const getRandomName = () => Math.random().toString(36).slice(2);
        const textDecoder = new TextDecoder();
        const textEncoder = new TextEncoder();
        const optionDefaults = Object.assign(/* @__PURE__ */ Object.create(null), {
          name: "opfs-sahpool",
          directory: void 0,
          initialCapacity: 6,
          clearOnInit: false,
          verbosity: 2,
          forceReinitIfPreviouslyFailed: false
        });
        const loggers = [
          sqlite32.config.error,
          sqlite32.config.warn,
          sqlite32.config.log
        ];
        const log2 = sqlite32.config.log;
        const warn = sqlite32.config.warn;
        const error = sqlite32.config.error;
        const __mapVfsToPool = /* @__PURE__ */ new Map();
        const getPoolForVfs = (pVfs) => __mapVfsToPool.get(pVfs);
        const setPoolForVfs = (pVfs, pool) => {
          if (pool)
            __mapVfsToPool.set(pVfs, pool);
          else
            __mapVfsToPool.delete(pVfs);
        };
        const __mapSqlite3File = /* @__PURE__ */ new Map();
        const getPoolForPFile = (pFile) => __mapSqlite3File.get(pFile);
        const setPoolForPFile = (pFile, pool) => {
          if (pool)
            __mapSqlite3File.set(pFile, pool);
          else
            __mapSqlite3File.delete(pFile);
        };
        const ioMethods = {
          xCheckReservedLock: function(pFile, pOut) {
            const pool = getPoolForPFile(pFile);
            pool.log("xCheckReservedLock");
            pool.storeErr();
            wasm.poke32(pOut, 1);
            return 0;
          },
          xClose: function(pFile) {
            const pool = getPoolForPFile(pFile);
            pool.storeErr();
            const file = pool.getOFileForS3File(pFile);
            if (file) {
              try {
                pool.log(`xClose ${file.path}`);
                pool.mapS3FileToOFile(pFile, false);
                file.sah.flush();
                if (file.flags & capi.SQLITE_OPEN_DELETEONCLOSE) {
                  pool.deletePath(file.path);
                }
              } catch (e2) {
                return pool.storeErr(e2, capi.SQLITE_IOERR);
              }
            }
            return 0;
          },
          xDeviceCharacteristics: function(pFile) {
            return capi.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
          },
          xFileControl: function(pFile, opId, pArg) {
            return capi.SQLITE_NOTFOUND;
          },
          xFileSize: function(pFile, pSz64) {
            const pool = getPoolForPFile(pFile);
            pool.log(`xFileSize`);
            const file = pool.getOFileForS3File(pFile);
            const size = file.sah.getSize() - HEADER_OFFSET_DATA;
            wasm.poke64(pSz64, BigInt(size));
            return 0;
          },
          xLock: function(pFile, lockType) {
            const pool = getPoolForPFile(pFile);
            pool.log(`xLock ${lockType}`);
            pool.storeErr();
            const file = pool.getOFileForS3File(pFile);
            file.lockType = lockType;
            return 0;
          },
          xRead: function(pFile, pDest, n2, offset64) {
            const pool = getPoolForPFile(pFile);
            pool.storeErr();
            const file = pool.getOFileForS3File(pFile);
            pool.log(`xRead ${file.path} ${n2} @ ${offset64}`);
            try {
              const nRead = file.sah.read(
                wasm.heap8u().subarray(pDest, pDest + n2),
                { at: HEADER_OFFSET_DATA + Number(offset64) }
              );
              if (nRead < n2) {
                wasm.heap8u().fill(0, pDest + nRead, pDest + n2);
                return capi.SQLITE_IOERR_SHORT_READ;
              }
              return 0;
            } catch (e2) {
              return pool.storeErr(e2, capi.SQLITE_IOERR);
            }
          },
          xSectorSize: function(pFile) {
            return SECTOR_SIZE;
          },
          xSync: function(pFile, flags) {
            const pool = getPoolForPFile(pFile);
            pool.log(`xSync ${flags}`);
            pool.storeErr();
            const file = pool.getOFileForS3File(pFile);
            try {
              file.sah.flush();
              return 0;
            } catch (e2) {
              return pool.storeErr(e2, capi.SQLITE_IOERR);
            }
          },
          xTruncate: function(pFile, sz64) {
            const pool = getPoolForPFile(pFile);
            pool.log(`xTruncate ${sz64}`);
            pool.storeErr();
            const file = pool.getOFileForS3File(pFile);
            try {
              file.sah.truncate(HEADER_OFFSET_DATA + Number(sz64));
              return 0;
            } catch (e2) {
              return pool.storeErr(e2, capi.SQLITE_IOERR);
            }
          },
          xUnlock: function(pFile, lockType) {
            const pool = getPoolForPFile(pFile);
            pool.log("xUnlock");
            const file = pool.getOFileForS3File(pFile);
            file.lockType = lockType;
            return 0;
          },
          xWrite: function(pFile, pSrc, n2, offset64) {
            const pool = getPoolForPFile(pFile);
            pool.storeErr();
            const file = pool.getOFileForS3File(pFile);
            pool.log(`xWrite ${file.path} ${n2} ${offset64}`);
            try {
              const nBytes = file.sah.write(
                wasm.heap8u().subarray(pSrc, pSrc + n2),
                { at: HEADER_OFFSET_DATA + Number(offset64) }
              );
              return n2 === nBytes ? 0 : toss("Unknown write() failure.");
            } catch (e2) {
              return pool.storeErr(e2, capi.SQLITE_IOERR);
            }
          }
        };
        const opfsIoMethods = new capi.sqlite3_io_methods();
        opfsIoMethods.$iVersion = 1;
        sqlite32.vfs.installVfs({
          io: { struct: opfsIoMethods, methods: ioMethods }
        });
        const vfsMethods = {
          xAccess: function(pVfs, zName, flags, pOut) {
            const pool = getPoolForVfs(pVfs);
            pool.storeErr();
            try {
              const name = pool.getPath(zName);
              wasm.poke32(pOut, pool.hasFilename(name) ? 1 : 0);
            } catch (e2) {
              wasm.poke32(pOut, 0);
            }
            return 0;
          },
          xCurrentTime: function(pVfs, pOut) {
            wasm.poke(
              pOut,
              24405875e-1 + (/* @__PURE__ */ new Date()).getTime() / 864e5,
              "double"
            );
            return 0;
          },
          xCurrentTimeInt64: function(pVfs, pOut) {
            wasm.poke(pOut, 24405875e-1 * 864e5 + (/* @__PURE__ */ new Date()).getTime(), "i64");
            return 0;
          },
          xDelete: function(pVfs, zName, doSyncDir) {
            const pool = getPoolForVfs(pVfs);
            pool.log(`xDelete ${wasm.cstrToJs(zName)}`);
            pool.storeErr();
            try {
              pool.deletePath(pool.getPath(zName));
              return 0;
            } catch (e2) {
              pool.storeErr(e2);
              return capi.SQLITE_IOERR_DELETE;
            }
          },
          xFullPathname: function(pVfs, zName, nOut, pOut) {
            const i2 = wasm.cstrncpy(pOut, zName, nOut);
            return i2 < nOut ? 0 : capi.SQLITE_CANTOPEN;
          },
          xGetLastError: function(pVfs, nOut, pOut) {
            const pool = getPoolForVfs(pVfs);
            const e2 = pool.popErr();
            pool.log(`xGetLastError ${nOut} e =`, e2);
            if (e2) {
              const scope = wasm.scopedAllocPush();
              try {
                const [cMsg, n2] = wasm.scopedAllocCString(e2.message, true);
                wasm.cstrncpy(pOut, cMsg, nOut);
                if (n2 > nOut)
                  wasm.poke8(pOut + nOut - 1, 0);
              } catch (e3) {
                return capi.SQLITE_NOMEM;
              } finally {
                wasm.scopedAllocPop(scope);
              }
            }
            return e2 ? e2.sqlite3Rc || capi.SQLITE_IOERR : 0;
          },
          xOpen: function f2(pVfs, zName, pFile, flags, pOutFlags) {
            const pool = getPoolForVfs(pVfs);
            try {
              pool.log(`xOpen ${wasm.cstrToJs(zName)} ${flags}`);
              const path2 = zName && wasm.peek8(zName) ? pool.getPath(zName) : getRandomName();
              let sah = pool.getSAHForPath(path2);
              if (!sah && flags & capi.SQLITE_OPEN_CREATE) {
                if (pool.getFileCount() < pool.getCapacity()) {
                  sah = pool.nextAvailableSAH();
                  pool.setAssociatedPath(sah, path2, flags);
                } else {
                  toss("SAH pool is full. Cannot create file", path2);
                }
              }
              if (!sah) {
                toss("file not found:", path2);
              }
              const file = { path: path2, flags, sah };
              pool.mapS3FileToOFile(pFile, file);
              file.lockType = capi.SQLITE_LOCK_NONE;
              const sq3File = new capi.sqlite3_file(pFile);
              sq3File.$pMethods = opfsIoMethods.pointer;
              sq3File.dispose();
              wasm.poke32(pOutFlags, flags);
              return 0;
            } catch (e2) {
              pool.storeErr(e2);
              return capi.SQLITE_CANTOPEN;
            }
          }
        };
        const createOpfsVfs = function(vfsName) {
          if (sqlite32.capi.sqlite3_vfs_find(vfsName)) {
            toss3("VFS name is already registered:", vfsName);
          }
          const opfsVfs = new capi.sqlite3_vfs();
          const pDVfs = capi.sqlite3_vfs_find(null);
          const dVfs = pDVfs ? new capi.sqlite3_vfs(pDVfs) : null;
          opfsVfs.$iVersion = 2;
          opfsVfs.$szOsFile = capi.sqlite3_file.structInfo.sizeof;
          opfsVfs.$mxPathname = HEADER_MAX_PATH_SIZE;
          opfsVfs.addOnDispose(
            opfsVfs.$zName = wasm.allocCString(vfsName),
            () => setPoolForVfs(opfsVfs.pointer, 0)
          );
          if (dVfs) {
            opfsVfs.$xRandomness = dVfs.$xRandomness;
            opfsVfs.$xSleep = dVfs.$xSleep;
            dVfs.dispose();
          }
          if (!opfsVfs.$xRandomness && !vfsMethods.xRandomness) {
            vfsMethods.xRandomness = function(pVfs, nOut, pOut) {
              const heap = wasm.heap8u();
              let i2 = 0;
              for (; i2 < nOut; ++i2)
                heap[pOut + i2] = Math.random() * 255e3 & 255;
              return i2;
            };
          }
          if (!opfsVfs.$xSleep && !vfsMethods.xSleep) {
            vfsMethods.xSleep = (pVfs, ms) => 0;
          }
          sqlite32.vfs.installVfs({
            vfs: { struct: opfsVfs, methods: vfsMethods }
          });
          return opfsVfs;
        };
        class OpfsSAHPool {
          vfsDir;
          #dhVfsRoot;
          #dhOpaque;
          #dhVfsParent;
          #mapSAHToName = /* @__PURE__ */ new Map();
          #mapFilenameToSAH = /* @__PURE__ */ new Map();
          #availableSAH = /* @__PURE__ */ new Set();
          #mapS3FileToOFile_ = /* @__PURE__ */ new Map();
          #apBody = new Uint8Array(HEADER_CORPUS_SIZE);
          #dvBody;
          #cVfs;
          #verbosity;
          constructor(options = /* @__PURE__ */ Object.create(null)) {
            this.#verbosity = options.verbosity ?? optionDefaults.verbosity;
            this.vfsName = options.name || optionDefaults.name;
            this.#cVfs = createOpfsVfs(this.vfsName);
            setPoolForVfs(this.#cVfs.pointer, this);
            this.vfsDir = options.directory || "." + this.vfsName;
            this.#dvBody = new DataView(
              this.#apBody.buffer,
              this.#apBody.byteOffset
            );
            this.isReady = this.reset(
              !!(options.clearOnInit ?? optionDefaults.clearOnInit)
            ).then(() => {
              if (this.$error)
                throw this.$error;
              return this.getCapacity() ? Promise.resolve(void 0) : this.addCapacity(
                options.initialCapacity || optionDefaults.initialCapacity
              );
            });
          }
          #logImpl(level, ...args) {
            if (this.#verbosity > level)
              loggers[level](this.vfsName + ":", ...args);
          }
          log(...args) {
            this.#logImpl(2, ...args);
          }
          warn(...args) {
            this.#logImpl(1, ...args);
          }
          error(...args) {
            this.#logImpl(0, ...args);
          }
          getVfs() {
            return this.#cVfs;
          }
          getCapacity() {
            return this.#mapSAHToName.size;
          }
          getFileCount() {
            return this.#mapFilenameToSAH.size;
          }
          getFileNames() {
            const rc = [];
            const iter = this.#mapFilenameToSAH.keys();
            for (const n2 of iter)
              rc.push(n2);
            return rc;
          }
          async addCapacity(n2) {
            for (let i2 = 0; i2 < n2; ++i2) {
              const name = getRandomName();
              const h2 = await this.#dhOpaque.getFileHandle(name, {
                create: true
              });
              const ah = await h2.createSyncAccessHandle();
              this.#mapSAHToName.set(ah, name);
              this.setAssociatedPath(ah, "", 0);
            }
            return this.getCapacity();
          }
          async reduceCapacity(n2) {
            let nRm = 0;
            for (const ah of Array.from(this.#availableSAH)) {
              if (nRm === n2 || this.getFileCount() === this.getCapacity()) {
                break;
              }
              const name = this.#mapSAHToName.get(ah);
              ah.close();
              await this.#dhOpaque.removeEntry(name);
              this.#mapSAHToName.delete(ah);
              this.#availableSAH.delete(ah);
              ++nRm;
            }
            return nRm;
          }
          releaseAccessHandles() {
            for (const ah of this.#mapSAHToName.keys())
              ah.close();
            this.#mapSAHToName.clear();
            this.#mapFilenameToSAH.clear();
            this.#availableSAH.clear();
          }
          async acquireAccessHandles(clearFiles) {
            const files = [];
            for await (const [name, h2] of this.#dhOpaque) {
              if ("file" === h2.kind) {
                files.push([name, h2]);
              }
            }
            return Promise.all(
              files.map(async ([name, h2]) => {
                try {
                  const ah = await h2.createSyncAccessHandle();
                  this.#mapSAHToName.set(ah, name);
                  if (clearFiles) {
                    ah.truncate(HEADER_OFFSET_DATA);
                    this.setAssociatedPath(ah, "", 0);
                  } else {
                    const path2 = this.getAssociatedPath(ah);
                    if (path2) {
                      this.#mapFilenameToSAH.set(path2, ah);
                    } else {
                      this.#availableSAH.add(ah);
                    }
                  }
                } catch (e2) {
                  this.storeErr(e2);
                  this.releaseAccessHandles();
                  throw e2;
                }
              })
            );
          }
          getAssociatedPath(sah) {
            sah.read(this.#apBody, { at: 0 });
            const flags = this.#dvBody.getUint32(HEADER_OFFSET_FLAGS);
            if (this.#apBody[0] && (flags & capi.SQLITE_OPEN_DELETEONCLOSE || (flags & PERSISTENT_FILE_TYPES) === 0)) {
              warn(
                `Removing file with unexpected flags ${flags.toString(16)}`,
                this.#apBody
              );
              this.setAssociatedPath(sah, "", 0);
              return "";
            }
            const fileDigest = new Uint32Array(HEADER_DIGEST_SIZE / 4);
            sah.read(fileDigest, { at: HEADER_OFFSET_DIGEST });
            const compDigest = this.computeDigest(this.#apBody);
            if (fileDigest.every((v3, i2) => v3 === compDigest[i2])) {
              const pathBytes = this.#apBody.findIndex((v3) => 0 === v3);
              if (0 === pathBytes) {
                sah.truncate(HEADER_OFFSET_DATA);
              }
              return pathBytes ? textDecoder.decode(this.#apBody.subarray(0, pathBytes)) : "";
            } else {
              warn("Disassociating file with bad digest.");
              this.setAssociatedPath(sah, "", 0);
              return "";
            }
          }
          setAssociatedPath(sah, path2, flags) {
            const enc = textEncoder.encodeInto(path2, this.#apBody);
            if (HEADER_MAX_PATH_SIZE <= enc.written + 1) {
              toss("Path too long:", path2);
            }
            this.#apBody.fill(0, enc.written, HEADER_MAX_PATH_SIZE);
            this.#dvBody.setUint32(HEADER_OFFSET_FLAGS, flags);
            const digest = this.computeDigest(this.#apBody);
            sah.write(this.#apBody, { at: 0 });
            sah.write(digest, { at: HEADER_OFFSET_DIGEST });
            sah.flush();
            if (path2) {
              this.#mapFilenameToSAH.set(path2, sah);
              this.#availableSAH.delete(sah);
            } else {
              sah.truncate(HEADER_OFFSET_DATA);
              this.#availableSAH.add(sah);
            }
          }
          computeDigest(byteArray) {
            let h1 = 3735928559;
            let h2 = 1103547991;
            for (const v3 of byteArray) {
              h1 = 31 * h1 + v3 * 307;
              h2 = 31 * h2 + v3 * 307;
            }
            return new Uint32Array([h1 >>> 0, h2 >>> 0]);
          }
          async reset(clearFiles) {
            await this.isReady;
            let h2 = await navigator.storage.getDirectory();
            let prev, prevName;
            for (const d2 of this.vfsDir.split("/")) {
              if (d2) {
                prev = h2;
                h2 = await h2.getDirectoryHandle(d2, { create: true });
              }
            }
            this.#dhVfsRoot = h2;
            this.#dhVfsParent = prev;
            this.#dhOpaque = await this.#dhVfsRoot.getDirectoryHandle(
              OPAQUE_DIR_NAME,
              { create: true }
            );
            this.releaseAccessHandles();
            return this.acquireAccessHandles(clearFiles);
          }
          getPath(arg) {
            if (wasm.isPtr(arg))
              arg = wasm.cstrToJs(arg);
            return (arg instanceof URL ? arg : new URL(arg, "file://localhost/")).pathname;
          }
          deletePath(path2) {
            const sah = this.#mapFilenameToSAH.get(path2);
            if (sah) {
              this.#mapFilenameToSAH.delete(path2);
              this.setAssociatedPath(sah, "", 0);
            }
            return !!sah;
          }
          storeErr(e2, code) {
            if (e2) {
              e2.sqlite3Rc = code || capi.SQLITE_IOERR;
              this.error(e2);
            }
            this.$error = e2;
            return code;
          }
          popErr() {
            const rc = this.$error;
            this.$error = void 0;
            return rc;
          }
          nextAvailableSAH() {
            const [rc] = this.#availableSAH.keys();
            return rc;
          }
          getOFileForS3File(pFile) {
            return this.#mapS3FileToOFile_.get(pFile);
          }
          mapS3FileToOFile(pFile, file) {
            if (file) {
              this.#mapS3FileToOFile_.set(pFile, file);
              setPoolForPFile(pFile, this);
            } else {
              this.#mapS3FileToOFile_.delete(pFile);
              setPoolForPFile(pFile, false);
            }
          }
          hasFilename(name) {
            return this.#mapFilenameToSAH.has(name);
          }
          getSAHForPath(path2) {
            return this.#mapFilenameToSAH.get(path2);
          }
          async removeVfs() {
            if (!this.#cVfs.pointer || !this.#dhOpaque)
              return false;
            capi.sqlite3_vfs_unregister(this.#cVfs.pointer);
            this.#cVfs.dispose();
            delete initPromises[this.vfsName];
            try {
              this.releaseAccessHandles();
              await this.#dhVfsRoot.removeEntry(OPAQUE_DIR_NAME, {
                recursive: true
              });
              this.#dhOpaque = void 0;
              await this.#dhVfsParent.removeEntry(this.#dhVfsRoot.name, {
                recursive: true
              });
              this.#dhVfsRoot = this.#dhVfsParent = void 0;
            } catch (e2) {
              sqlite32.config.error(this.vfsName, "removeVfs() failed:", e2);
            }
            return true;
          }
          exportFile(name) {
            const sah = this.#mapFilenameToSAH.get(name) || toss("File not found:", name);
            const n2 = sah.getSize() - HEADER_OFFSET_DATA;
            const b = new Uint8Array(n2 > 0 ? n2 : 0);
            if (n2 > 0) {
              const nRead = sah.read(b, { at: HEADER_OFFSET_DATA });
              if (nRead != n2) {
                toss(
                  "Expected to read " + n2 + " bytes but read " + nRead + "."
                );
              }
            }
            return b;
          }
          async importDbChunked(name, callback) {
            const sah = this.#mapFilenameToSAH.get(name) || this.nextAvailableSAH() || toss("No available handles to import to.");
            sah.truncate(0);
            let nWrote = 0, chunk, checkedHeader = false, err2 = false;
            try {
              while (void 0 !== (chunk = await callback())) {
                if (chunk instanceof ArrayBuffer)
                  chunk = new Uint8Array(chunk);
                if (0 === nWrote && chunk.byteLength >= 15) {
                  util.affirmDbHeader(chunk);
                  checkedHeader = true;
                }
                sah.write(chunk, { at: HEADER_OFFSET_DATA + nWrote });
                nWrote += chunk.byteLength;
              }
              if (nWrote < 512 || 0 !== nWrote % 512) {
                toss(
                  "Input size",
                  nWrote,
                  "is not correct for an SQLite database."
                );
              }
              if (!checkedHeader) {
                const header = new Uint8Array(20);
                sah.read(header, { at: 0 });
                util.affirmDbHeader(header);
              }
              sah.write(new Uint8Array([1, 1]), {
                at: HEADER_OFFSET_DATA + 18
              });
            } catch (e2) {
              this.setAssociatedPath(sah, "", 0);
              throw e2;
            }
            this.setAssociatedPath(sah, name, capi.SQLITE_OPEN_MAIN_DB);
            return nWrote;
          }
          importDb(name, bytes) {
            if (bytes instanceof ArrayBuffer)
              bytes = new Uint8Array(bytes);
            else if (bytes instanceof Function)
              return this.importDbChunked(name, bytes);
            const sah = this.#mapFilenameToSAH.get(name) || this.nextAvailableSAH() || toss("No available handles to import to.");
            const n2 = bytes.byteLength;
            if (n2 < 512 || n2 % 512 != 0) {
              toss("Byte array size is invalid for an SQLite db.");
            }
            const header = "SQLite format 3";
            for (let i2 = 0; i2 < header.length; ++i2) {
              if (header.charCodeAt(i2) !== bytes[i2]) {
                toss("Input does not contain an SQLite database header.");
              }
            }
            const nWrote = sah.write(bytes, { at: HEADER_OFFSET_DATA });
            if (nWrote != n2) {
              this.setAssociatedPath(sah, "", 0);
              toss(
                "Expected to write " + n2 + " bytes but wrote " + nWrote + "."
              );
            } else {
              sah.write(new Uint8Array([1, 1]), {
                at: HEADER_OFFSET_DATA + 18
              });
              this.setAssociatedPath(sah, name, capi.SQLITE_OPEN_MAIN_DB);
            }
            return nWrote;
          }
        }
        class OpfsSAHPoolUtil {
          #p;
          constructor(sahPool) {
            this.#p = sahPool;
            this.vfsName = sahPool.vfsName;
          }
          async addCapacity(n2) {
            return this.#p.addCapacity(n2);
          }
          async reduceCapacity(n2) {
            return this.#p.reduceCapacity(n2);
          }
          getCapacity() {
            return this.#p.getCapacity(this.#p);
          }
          getFileCount() {
            return this.#p.getFileCount();
          }
          getFileNames() {
            return this.#p.getFileNames();
          }
          async reserveMinimumCapacity(min) {
            const c3 = this.#p.getCapacity();
            return c3 < min ? this.#p.addCapacity(min - c3) : c3;
          }
          exportFile(name) {
            return this.#p.exportFile(name);
          }
          importDb(name, bytes) {
            return this.#p.importDb(name, bytes);
          }
          async wipeFiles() {
            return this.#p.reset(true);
          }
          unlink(filename) {
            return this.#p.deletePath(filename);
          }
          async removeVfs() {
            return this.#p.removeVfs();
          }
        }
        const apiVersionCheck = async () => {
          const dh = await navigator.storage.getDirectory();
          const fn = ".opfs-sahpool-sync-check-" + getRandomName();
          const fh = await dh.getFileHandle(fn, { create: true });
          const ah = await fh.createSyncAccessHandle();
          const close = ah.close();
          await close;
          await dh.removeEntry(fn);
          if (close == null ? void 0 : close.then) {
            toss(
              "The local OPFS API is too old for opfs-sahpool:",
              "it has an async FileSystemSyncAccessHandle.close() method."
            );
          }
          return true;
        };
        sqlite32.installOpfsSAHPoolVfs = async function(options = /* @__PURE__ */ Object.create(null)) {
          var _a8;
          options = Object.assign(
            /* @__PURE__ */ Object.create(null),
            optionDefaults,
            options || {}
          );
          const vfsName = options.name;
          if (options.$testThrowPhase1) {
            throw options.$testThrowPhase1;
          }
          if (initPromises[vfsName]) {
            try {
              const p3 = await initPromises[vfsName];
              return p3;
            } catch (e2) {
              if (options.forceReinitIfPreviouslyFailed) {
                delete initPromises[vfsName];
              } else {
                throw e2;
              }
            }
          }
          if (!globalThis.FileSystemHandle || !globalThis.FileSystemDirectoryHandle || !globalThis.FileSystemFileHandle || !globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle || !((_a8 = navigator == null ? void 0 : navigator.storage) == null ? void 0 : _a8.getDirectory)) {
            return initPromises[vfsName] = Promise.reject(
              new Error("Missing required OPFS APIs.")
            );
          }
          return initPromises[vfsName] = apiVersionCheck().then(async function() {
            if (options.$testThrowPhase2) {
              throw options.$testThrowPhase2;
            }
            const thePool = new OpfsSAHPool(options);
            return thePool.isReady.then(async () => {
              const poolUtil = new OpfsSAHPoolUtil(thePool);
              if (sqlite32.oo1) {
                const oo1 = sqlite32.oo1;
                const theVfs = thePool.getVfs();
                const OpfsSAHPoolDb = function(...args) {
                  const opt = oo1.DB.dbCtorHelper.normalizeArgs(...args);
                  opt.vfs = theVfs.$zName;
                  oo1.DB.dbCtorHelper.call(this, opt);
                };
                OpfsSAHPoolDb.prototype = Object.create(oo1.DB.prototype);
                poolUtil.OpfsSAHPoolDb = OpfsSAHPoolDb;
              }
              thePool.log("VFS initialized.");
              return poolUtil;
            }).catch(async (e2) => {
              await thePool.removeVfs().catch(() => {
              });
              throw e2;
            });
          }).catch((err2) => {
            return initPromises[vfsName] = Promise.reject(err2);
          });
        };
      });
      "use strict";
      if ("undefined" !== typeof Module2) {
        const SABC = Object.assign(
          /* @__PURE__ */ Object.create(null),
          {
            exports: "undefined" === typeof wasmExports ? Module2["asm"] : wasmExports,
            memory: Module2.wasmMemory
          },
          globalThis.sqlite3ApiConfig || {}
        );
        globalThis.sqlite3ApiConfig = SABC;
        let sqlite32;
        try {
          sqlite32 = globalThis.sqlite3ApiBootstrap();
        } catch (e2) {
          console.error("sqlite3ApiBootstrap() error:", e2);
          throw e2;
        } finally {
          delete globalThis.sqlite3ApiBootstrap;
          delete globalThis.sqlite3ApiConfig;
        }
        Module2.sqlite3 = sqlite32;
      } else {
        console.warn(
          "This is not running in an Emscripten module context, so",
          "globalThis.sqlite3ApiBootstrap() is _not_ being called due to lack",
          "of config info for the WASM environment.",
          "It must be called manually."
        );
      }
    });
    moduleRtn = readyPromise;
    return moduleRtn;
  };
})();
var toExportForESM = function() {
  var _a8, _b5;
  const originalInit = sqlite3InitModule;
  if (!originalInit) {
    throw new Error(
      "Expecting globalThis.sqlite3InitModule to be defined by the Emscripten build."
    );
  }
  const initModuleState = globalThis.sqlite3InitModuleState = Object.assign(
    /* @__PURE__ */ Object.create(null),
    {
      moduleScript: (_a8 = globalThis == null ? void 0 : globalThis.document) == null ? void 0 : _a8.currentScript,
      isWorker: "undefined" !== typeof WorkerGlobalScope,
      location: globalThis.location,
      urlParams: ((_b5 = globalThis == null ? void 0 : globalThis.location) == null ? void 0 : _b5.href) ? new URL(globalThis.location.href).searchParams : new URLSearchParams()
    }
  );
  initModuleState.debugModule = initModuleState.urlParams.has(
    "sqlite3.debugModule"
  ) ? (...args) => console.warn("sqlite3.debugModule:", ...args) : () => {
  };
  if (initModuleState.urlParams.has("sqlite3.dir")) {
    initModuleState.sqlite3Dir = initModuleState.urlParams.get("sqlite3.dir") + "/";
  } else if (initModuleState.moduleScript) {
    const li = initModuleState.moduleScript.src.split("/");
    li.pop();
    initModuleState.sqlite3Dir = li.join("/") + "/";
  }
  globalThis.sqlite3InitModule = function ff(...args) {
    return originalInit(...args).then((EmscriptenModule) => {
      const s2 = EmscriptenModule.sqlite3;
      s2.scriptInfo = initModuleState;
      if (ff.__isUnderTest)
        s2.__isUnderTest = true;
      const f2 = s2.asyncPostInit;
      delete s2.asyncPostInit;
      return f2();
    }).catch((e2) => {
      console.error("Exception loading sqlite3 module:", e2);
      throw e2;
    });
  };
  globalThis.sqlite3InitModule.ready = originalInit.ready;
  if (globalThis.sqlite3InitModuleState.moduleScript) {
    const sim = globalThis.sqlite3InitModuleState;
    let src2 = sim.moduleScript.src.split("/");
    src2.pop();
    sim.scriptDir = src2.join("/") + "/";
  }
  initModuleState.debugModule("sqlite3InitModuleState =", initModuleState);
  if (0) {
    console.warn("Replaced sqlite3InitModule()");
    console.warn("globalThis.location.href =", globalThis.location.href);
    if ("undefined" !== typeof document) {
      console.warn(
        "document.currentScript.src =",
        (_c = document == null ? void 0 : document.currentScript) == null ? void 0 : _c.src
      );
    }
  }
  return globalThis.sqlite3InitModule;
}();
sqlite3InitModule = toExportForESM;
var sqlite3_bundler_friendly_default = sqlite3InitModule;

// ../../node_modules/.pnpm/@sqlite.org+sqlite-wasm@3.48.0-build4/node_modules/@sqlite.org/sqlite-wasm/sqlite-wasm/jswasm/sqlite3-worker1-promiser.mjs
init_define_ENV_DEFINED_IN_BUILD_STEP();
globalThis.sqlite3Worker1Promiser = function callee(config = callee.defaultConfig) {
  if (1 === arguments.length && "function" === typeof arguments[0]) {
    const f2 = config;
    config = Object.assign(/* @__PURE__ */ Object.create(null), callee.defaultConfig);
    config.onready = f2;
  } else {
    config = Object.assign(/* @__PURE__ */ Object.create(null), callee.defaultConfig, config);
  }
  const handlerMap = /* @__PURE__ */ Object.create(null);
  const noop2 = function() {
  };
  const err = config.onerror || noop2;
  const debug = config.debug || noop2;
  const idTypeMap = config.generateMessageId ? void 0 : /* @__PURE__ */ Object.create(null);
  const genMsgId = config.generateMessageId || function(msg) {
    return msg.type + "#" + (idTypeMap[msg.type] = (idTypeMap[msg.type] || 0) + 1);
  };
  const toss = (...args) => {
    throw new Error(args.join(" "));
  };
  if (!config.worker)
    config.worker = callee.defaultConfig.worker;
  if ("function" === typeof config.worker)
    config.worker = config.worker();
  let dbId;
  let promiserFunc;
  config.worker.onmessage = function(ev) {
    ev = ev.data;
    debug("worker1.onmessage", ev);
    let msgHandler = handlerMap[ev.messageId];
    if (!msgHandler) {
      if (ev && "sqlite3-api" === ev.type && "worker1-ready" === ev.result) {
        if (config.onready)
          config.onready(promiserFunc);
        return;
      }
      msgHandler = handlerMap[ev.type];
      if (msgHandler && msgHandler.onrow) {
        msgHandler.onrow(ev);
        return;
      }
      if (config.onunhandled)
        config.onunhandled(arguments[0]);
      else
        err("sqlite3Worker1Promiser() unhandled worker message:", ev);
      return;
    }
    delete handlerMap[ev.messageId];
    switch (ev.type) {
      case "error":
        msgHandler.reject(ev);
        return;
      case "open":
        if (!dbId)
          dbId = ev.dbId;
        break;
      case "close":
        if (ev.dbId === dbId)
          dbId = void 0;
        break;
      default:
        break;
    }
    try {
      msgHandler.resolve(ev);
    } catch (e2) {
      msgHandler.reject(e2);
    }
  };
  return promiserFunc = function() {
    let msg;
    if (1 === arguments.length) {
      msg = arguments[0];
    } else if (2 === arguments.length) {
      msg = /* @__PURE__ */ Object.create(null);
      msg.type = arguments[0];
      msg.args = arguments[1];
      msg.dbId = msg.args.dbId;
    } else {
      toss("Invalid arguments for sqlite3Worker1Promiser()-created factory.");
    }
    if (!msg.dbId && msg.type !== "open")
      msg.dbId = dbId;
    msg.messageId = genMsgId(msg);
    msg.departureTime = performance.now();
    const proxy = /* @__PURE__ */ Object.create(null);
    proxy.message = msg;
    let rowCallbackId;
    if ("exec" === msg.type && msg.args) {
      if ("function" === typeof msg.args.callback) {
        rowCallbackId = msg.messageId + ":row";
        proxy.onrow = msg.args.callback;
        msg.args.callback = rowCallbackId;
        handlerMap[rowCallbackId] = proxy;
      } else if ("string" === typeof msg.args.callback) {
        toss(
          "exec callback may not be a string when using the Promise interface."
        );
      }
    }
    let p3 = new Promise(function(resolve2, reject) {
      proxy.resolve = resolve2;
      proxy.reject = reject;
      handlerMap[msg.messageId] = proxy;
      debug(
        "Posting",
        msg.type,
        "message to Worker dbId=" + (dbId || "default") + ":",
        msg
      );
      config.worker.postMessage(msg);
    });
    if (rowCallbackId)
      p3 = p3.finally(() => delete handlerMap[rowCallbackId]);
    return p3;
  };
};
globalThis.sqlite3Worker1Promiser.defaultConfig = {
  worker: function() {
    return new Worker(
      new URL("sqlite3-worker1-bundler-friendly.mjs", import.meta.url),
      {
        type: "module"
      }
    );
  },
  onerror: (...args) => console.error("worker1 promiser error", ...args)
};
sqlite3Worker1Promiser.v2 = function(config) {
  let oldFunc;
  if ("function" == typeof config) {
    oldFunc = config;
    config = {};
  } else if ("function" === typeof (config == null ? void 0 : config.onready)) {
    oldFunc = config.onready;
    delete config.onready;
  }
  const promiseProxy = /* @__PURE__ */ Object.create(null);
  config = Object.assign(config || /* @__PURE__ */ Object.create(null), {
    onready: async function(func) {
      try {
        if (oldFunc)
          await oldFunc(func);
        promiseProxy.resolve(func);
      } catch (e2) {
        promiseProxy.reject(e2);
      }
    }
  });
  const p3 = new Promise(function(resolve2, reject) {
    promiseProxy.resolve = resolve2;
    promiseProxy.reject = reject;
  });
  try {
    this.original(config);
  } catch (e2) {
    promiseProxy.reject(e2);
  }
  return p3;
}.bind({
  original: sqlite3Worker1Promiser
});
var sqlite3_worker1_promiser_default = sqlite3Worker1Promiser.v2;

// ../../node_modules/.pnpm/@sqlite.org+sqlite-wasm@3.48.0-build4/node_modules/@sqlite.org/sqlite-wasm/index.mjs
var sqlite3Worker1Promiser2 = globalThis.sqlite3Worker1Promiser;
var sqlite_wasm_default = sqlite3_bundler_friendly_default;

// ../../node_modules/.pnpm/sqlite-wasm-kysely@0.3.0_kysely@0.28.14/node_modules/sqlite-wasm-kysely/dist/util/sqliteWasmBinary.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function base64ToArrayBuffer(base64) {
  var binaryString = atob(base64);
  var bytes = new Uint8Array(binaryString.length);
  for (var i2 = 0; i2 < binaryString.length; i2++) {
    bytes[i2] = binaryString.charCodeAt(i2);
  }
  return bytes.buffer;
}
var sqliteWasmBase64 = " ";
var wasmBinary = base64ToArrayBuffer(sqliteWasmBase64);

// ../../node_modules/.pnpm/sqlite-wasm-kysely@0.3.0_kysely@0.28.14/node_modules/sqlite-wasm-kysely/dist/util/createInMemoryDatabase.js
globalThis.sqlite3ApiConfig = {
  warn: (message, details) => {
    if (message === "Ignoring inability to install OPFS sqlite3_vfs:") {
      return;
    }
    console.log(message + " " + details);
  }
};
var sqlite3;
var createInMemoryDatabase = async ({ readOnly = false }) => {
  if (sqlite3 === void 0) {
    sqlite3 = await sqlite_wasm_default({
      // @ts-expect-error
      wasmBinary,
      // https://github.com/opral/inlang-sdk/issues/170#issuecomment-2334768193
      locateFile: () => "sqlite3.wasm"
    });
  }
  const flags = [
    readOnly ? "r" : "cw",
    // read and write
    ""
    // non verbose
  ].join("");
  const db = new sqlite3.oo1.DB(":memory:", flags);
  db.sqlite3 = sqlite3;
  return db;
};

// ../../node_modules/.pnpm/sqlite-wasm-kysely@0.3.0_kysely@0.28.14/node_modules/sqlite-wasm-kysely/dist/util/importDatabase.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var importDatabase = ({ db, content, schema = "main", readOnly = false }) => {
  const deserializeFlag = readOnly ? db.sqlite3.capi.SQLITE_DESERIALIZE_READONLY : db.sqlite3.capi.SQLITE_DESERIALIZE_FREEONCLOSE | db.sqlite3.capi.SQLITE_DESERIALIZE_RESIZEABLE;
  const contentPointer = db.sqlite3.wasm.allocFromTypedArray(content);
  const deserializeReturnCode = db.sqlite3.capi.sqlite3_deserialize(
    db.pointer,
    schema,
    contentPointer,
    content.byteLength,
    // db size
    content.byteLength,
    // content size
    deserializeFlag
  );
  db.checkRc(deserializeReturnCode);
  return db;
};

// ../../node_modules/.pnpm/sqlite-wasm-kysely@0.3.0_kysely@0.28.14/node_modules/sqlite-wasm-kysely/dist/util/loadDatabaseInMemory.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/sqlite-wasm-kysely@0.3.0_kysely@0.28.14/node_modules/sqlite-wasm-kysely/dist/dialect.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/sqlite-wasm-kysely@0.3.0_kysely@0.28.14/node_modules/sqlite-wasm-kysely/dist/kysely/SqliteWasmDriver.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/sqlite-wasm-kysely@0.3.0_kysely@0.28.14/node_modules/sqlite-wasm-kysely/dist/kysely/ConnectionMutex.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var __classPrivateFieldGet = function(receiver, state, kind, f2) {
  if (kind === "a" && !f2)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver);
};
var __classPrivateFieldSet = function(receiver, state, value, kind, f2) {
  if (kind === "m")
    throw new TypeError("Private method is not writable");
  if (kind === "a" && !f2)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f2.call(receiver, value) : f2 ? f2.value = value : state.set(receiver, value), value;
};
var _ConnectionMutex_promise;
var _ConnectionMutex_resolve;
var ConnectionMutex = class {
  constructor() {
    _ConnectionMutex_promise.set(this, void 0);
    _ConnectionMutex_resolve.set(this, void 0);
  }
  async lock() {
    while (__classPrivateFieldGet(this, _ConnectionMutex_promise, "f")) {
      await __classPrivateFieldGet(this, _ConnectionMutex_promise, "f");
    }
    __classPrivateFieldSet(this, _ConnectionMutex_promise, new Promise((resolve2) => {
      __classPrivateFieldSet(this, _ConnectionMutex_resolve, resolve2, "f");
    }), "f");
  }
  unlock() {
    const resolve2 = __classPrivateFieldGet(this, _ConnectionMutex_resolve, "f");
    __classPrivateFieldSet(this, _ConnectionMutex_promise, void 0, "f");
    __classPrivateFieldSet(this, _ConnectionMutex_resolve, void 0, "f");
    resolve2 == null ? void 0 : resolve2();
  }
};
_ConnectionMutex_promise = /* @__PURE__ */ new WeakMap(), _ConnectionMutex_resolve = /* @__PURE__ */ new WeakMap();

// ../../node_modules/.pnpm/sqlite-wasm-kysely@0.3.0_kysely@0.28.14/node_modules/sqlite-wasm-kysely/dist/kysely/SqliteWasmConnection.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var __classPrivateFieldSet2 = function(receiver, state, value, kind, f2) {
  if (kind === "m")
    throw new TypeError("Private method is not writable");
  if (kind === "a" && !f2)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f2.call(receiver, value) : f2 ? f2.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet2 = function(receiver, state, kind, f2) {
  if (kind === "a" && !f2)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver);
};
var _SqliteWasmConnection_db;
var SqliteWasmConnection = class {
  constructor(db) {
    _SqliteWasmConnection_db.set(this, void 0);
    __classPrivateFieldSet2(this, _SqliteWasmConnection_db, db, "f");
  }
  executeQuery(compiledQuery) {
    const { sql: sql2, parameters } = compiledQuery;
    const statementData = {
      rows: [],
      columns: []
    };
    const totalChangesBefore = __classPrivateFieldGet2(this, _SqliteWasmConnection_db, "f").changes(true);
    const rows = __classPrivateFieldGet2(this, _SqliteWasmConnection_db, "f").exec({
      sql: sql2,
      bind: parameters,
      returnValue: "resultRows",
      rowMode: "object",
      columnNames: statementData.columns
    });
    const lastInsertId = __classPrivateFieldGet2(this, _SqliteWasmConnection_db, "f").sqlite3.capi.sqlite3_last_insert_rowid(__classPrivateFieldGet2(this, _SqliteWasmConnection_db, "f"));
    const changes = totalChangesBefore === __classPrivateFieldGet2(this, _SqliteWasmConnection_db, "f").changes(true) ? 0 : __classPrivateFieldGet2(this, _SqliteWasmConnection_db, "f").changes();
    return Promise.resolve({
      numAffectedRows: changes,
      insertId: lastInsertId,
      // queries with result
      rows
    });
  }
  // eslint-disable-next-line require-yield
  async *streamQuery() {
    throw new Error("not supported for wasm driver yet");
  }
};
_SqliteWasmConnection_db = /* @__PURE__ */ new WeakMap();

// ../../node_modules/.pnpm/sqlite-wasm-kysely@0.3.0_kysely@0.28.14/node_modules/sqlite-wasm-kysely/dist/kysely/SqliteWasmDriver.js
var __classPrivateFieldSet3 = function(receiver, state, value, kind, f2) {
  if (kind === "m")
    throw new TypeError("Private method is not writable");
  if (kind === "a" && !f2)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f2.call(receiver, value) : f2 ? f2.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet3 = function(receiver, state, kind, f2) {
  if (kind === "a" && !f2)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver);
};
var _SqliteWasmDriver_config;
var _SqliteWasmDriver_connectionMutex;
var _SqliteWasmDriver_db;
var _SqliteWasmDriver_connection;
var SqliteWasmDriver = class {
  constructor(config) {
    _SqliteWasmDriver_config.set(this, void 0);
    _SqliteWasmDriver_connectionMutex.set(this, new ConnectionMutex());
    _SqliteWasmDriver_db.set(this, void 0);
    _SqliteWasmDriver_connection.set(this, void 0);
    __classPrivateFieldSet3(this, _SqliteWasmDriver_config, { ...config }, "f");
  }
  async init() {
    __classPrivateFieldSet3(this, _SqliteWasmDriver_db, typeof __classPrivateFieldGet3(this, _SqliteWasmDriver_config, "f").database === "function" ? await __classPrivateFieldGet3(this, _SqliteWasmDriver_config, "f").database() : __classPrivateFieldGet3(this, _SqliteWasmDriver_config, "f").database, "f");
    __classPrivateFieldSet3(this, _SqliteWasmDriver_connection, new SqliteWasmConnection(__classPrivateFieldGet3(this, _SqliteWasmDriver_db, "f")), "f");
    if (__classPrivateFieldGet3(this, _SqliteWasmDriver_config, "f").onCreateConnection) {
      await __classPrivateFieldGet3(this, _SqliteWasmDriver_config, "f").onCreateConnection(__classPrivateFieldGet3(this, _SqliteWasmDriver_connection, "f"));
    }
  }
  async acquireConnection() {
    await __classPrivateFieldGet3(this, _SqliteWasmDriver_connectionMutex, "f").lock();
    return __classPrivateFieldGet3(this, _SqliteWasmDriver_connection, "f");
  }
  async beginTransaction(connection) {
    await connection.executeQuery(CompiledQuery.raw("begin"));
  }
  async commitTransaction(connection) {
    await connection.executeQuery(CompiledQuery.raw("commit"));
  }
  async rollbackTransaction(connection) {
    await connection.executeQuery(CompiledQuery.raw("rollback"));
  }
  async releaseConnection() {
    __classPrivateFieldGet3(this, _SqliteWasmDriver_connectionMutex, "f").unlock();
  }
  async destroy() {
    var _a8;
    (_a8 = __classPrivateFieldGet3(this, _SqliteWasmDriver_db, "f")) == null ? void 0 : _a8.close();
  }
};
_SqliteWasmDriver_config = /* @__PURE__ */ new WeakMap(), _SqliteWasmDriver_connectionMutex = /* @__PURE__ */ new WeakMap(), _SqliteWasmDriver_db = /* @__PURE__ */ new WeakMap(), _SqliteWasmDriver_connection = /* @__PURE__ */ new WeakMap();

// ../../node_modules/.pnpm/sqlite-wasm-kysely@0.3.0_kysely@0.28.14/node_modules/sqlite-wasm-kysely/dist/dialect.js
var createDialect = (args) => {
  return {
    createAdapter: () => new SqliteAdapter(),
    createDriver: () => new SqliteWasmDriver({
      database: args.database
    }),
    createIntrospector: (db) => new SqliteIntrospector(db),
    createQueryCompiler: () => new SqliteQueryCompiler()
  };
};

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/database/init-db.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/uuid@14.0.0/node_modules/uuid/dist-node/index.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/uuid@14.0.0/node_modules/uuid/dist-node/stringify.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var byteToHex = [];
for (let i2 = 0; i2 < 256; ++i2) {
  byteToHex.push((i2 + 256).toString(16).slice(1));
}
function unsafeStringify(arr, offset = 0) {
  return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
}

// ../../node_modules/.pnpm/uuid@14.0.0/node_modules/uuid/dist-node/rng.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var rnds8 = new Uint8Array(16);
function rng() {
  return crypto.getRandomValues(rnds8);
}

// ../../node_modules/.pnpm/uuid@14.0.0/node_modules/uuid/dist-node/v4.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function v4(options, buf, offset) {
  if (!buf && !options && crypto.randomUUID) {
    return crypto.randomUUID();
  }
  return _v4(options, buf, offset);
}
function _v4(options, buf, offset) {
  var _a8;
  options = options || {};
  const rnds = options.random ?? ((_a8 = options.rng) == null ? void 0 : _a8.call(options)) ?? rng();
  if (rnds.length < 16) {
    throw new Error("Random bytes length must be >= 16");
  }
  rnds[6] = rnds[6] & 15 | 64;
  rnds[8] = rnds[8] & 63 | 128;
  if (buf) {
    offset = offset || 0;
    if (offset < 0 || offset + 16 > buf.length) {
      throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
    }
    for (let i2 = 0; i2 < 16; ++i2) {
      buf[offset + i2] = rnds[i2];
    }
    return buf;
  }
  return unsafeStringify(rnds);
}
var v4_default = v4;

// ../../node_modules/.pnpm/uuid@14.0.0/node_modules/uuid/dist-node/v7.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var _state = {};
function v7(options, buf, offset) {
  var _a8;
  let bytes;
  if (options) {
    bytes = v7Bytes(options.random ?? ((_a8 = options.rng) == null ? void 0 : _a8.call(options)) ?? rng(), options.msecs, options.seq, buf, offset);
  } else {
    const now = Date.now();
    const rnds = rng();
    updateV7State(_state, now, rnds);
    bytes = v7Bytes(rnds, _state.msecs, _state.seq, buf, offset);
  }
  return buf ?? unsafeStringify(bytes);
}
function updateV7State(state, now, rnds) {
  state.msecs ??= -Infinity;
  state.seq ??= 0;
  if (now > state.msecs) {
    state.seq = rnds[6] << 23 | rnds[7] << 16 | rnds[8] << 8 | rnds[9];
    state.msecs = now;
  } else {
    state.seq = state.seq + 1 | 0;
    if (state.seq === 0) {
      state.msecs++;
    }
  }
  return state;
}
function v7Bytes(rnds, msecs, seq, buf, offset = 0) {
  if (rnds.length < 16) {
    throw new Error("Random bytes length must be >= 16");
  }
  if (!buf) {
    buf = new Uint8Array(16);
    offset = 0;
  } else {
    if (offset < 0 || offset + 16 > buf.length) {
      throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
    }
  }
  msecs ??= Date.now();
  seq ??= rnds[6] * 127 << 24 | rnds[7] << 16 | rnds[8] << 8 | rnds[9];
  buf[offset++] = msecs / 1099511627776 & 255;
  buf[offset++] = msecs / 4294967296 & 255;
  buf[offset++] = msecs / 16777216 & 255;
  buf[offset++] = msecs / 65536 & 255;
  buf[offset++] = msecs / 256 & 255;
  buf[offset++] = msecs & 255;
  buf[offset++] = 112 | seq >>> 28 & 15;
  buf[offset++] = seq >>> 20 & 255;
  buf[offset++] = 128 | seq >>> 14 & 63;
  buf[offset++] = seq >>> 6 & 255;
  buf[offset++] = seq << 2 & 255 | rnds[10] & 3;
  buf[offset++] = rnds[11];
  buf[offset++] = rnds[12];
  buf[offset++] = rnds[13];
  buf[offset++] = rnds[14];
  buf[offset++] = rnds[15];
  return buf;
}
var v7_default = v7;

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/database/apply-schema.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/database/mutation-log/database-schema.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var tablesByDepencies = [
  // no dependencies
  "snapshot",
  "label",
  "version",
  "account",
  "file",
  "change_set",
  "key_value",
  // Depends on: snapshot
  "change",
  // Depends on: file
  "file_queue",
  // Depends on: change
  "change_author",
  // Depends on: change
  "change_edge",
  // Depends on: change_set
  "change_conflict",
  // Depends on: change_conflict, change
  "change_conflict_resolution",
  // Depends on: change_set, change
  "change_set_element",
  // Depends on: label, change_set
  "change_set_label",
  //Depends on: change_set
  "discussion",
  // Depends on: account, discussion, comment
  "comment",
  // Depends on: version, change
  "version_change",
  // Depends on: version, change_conflict
  "version_change_conflict",
  // Depends on: version
  "current_version"
];
var tableIdColumns = {
  // file - File is not synced. Is construcuted from the change table. (see https://github.com/opral/monorepo/pull/3242#discussion_r1863981413)
  change: ["id"],
  snapshot: ["id"],
  change_conflict: ["id"],
  change_edge: ["parent_id", "child_id"],
  change_conflict_resolution: ["change_conflict_id", "resolved_change_id"],
  version_change_conflict: ["version_id", "change_conflict_id"]
  // version_change: ["version_id", "change_id"],
};
function applyMutationLogDatabaseSchema(sqlite2) {
  sqlite2.exec`
  -- vector clock
  CREATE TABLE IF NOT EXISTS mutation_log (
    row_id BLOB,
    table_name TEXT,
    -- TODO SYNC - we might not need the operation as long as we don't expect a delete operation since we utilize upsert queries anyway
    operation TEXT,
    session TEXT NOT NULL DEFAULT (lix_session()),
    session_time INTEGER NOT NULL DEFAULT (lix_session_clock_tick()),
    wall_clock INTEGER DEFAULT (strftime('%s', 'now') * 1000 + (strftime('%f', 'now') - strftime('%S', 'now')) * 1000)
  ) STRICT;
   
  CREATE TRIGGER IF NOT EXISTS ignore_mutation_during_sync
  BEFORE INSERT ON mutation_log
  FOR EACH ROW
  WHEN EXISTS (SELECT 1 FROM mutation_log WHERE table_name = 'mutation_log')
  BEGIN
    SELECT RAISE(IGNORE);
  END;
 
  `;
  for (const [tableName, idColumns] of Object.entries(tableIdColumns)) {
    if (idColumns.length === 0) {
      throw new Error("at least one id required");
    }
    sqlite2.exec(`
      -- Trigger for INSERT operations
      CREATE TRIGGER IF NOT EXISTS ${tableName}_after_insert_log
      AFTER INSERT ON ${tableName}
      BEGIN
          INSERT INTO mutation_log (row_id, table_name, operation)
          VALUES (JSONB(${toSqliteJson(idColumns)}), '${tableName}', 'INSERT');
      END;
  
      -- Trigger for UPDATE operations
      CREATE TRIGGER IF NOT EXISTS ${tableName}_after_update_log
      AFTER UPDATE ON ${tableName}
      BEGIN
          INSERT INTO mutation_log (row_id, table_name, operation)
          VALUES (JSONB(${toSqliteJson(idColumns)}), '${tableName}', 'UPDATE');
      END;
    `);
  }
}
function toSqliteJson(keyColumns) {
  if (keyColumns.length === 0) {
    throw new Error("Key columns array cannot be empty.");
  }
  const jsonObjectArgs = keyColumns.map((keyColumnName) => `'${keyColumnName}', NEW.${keyColumnName}`);
  const jsonObjectExpression = "json_object(" + jsonObjectArgs.join(", ") + ")";
  return jsonObjectExpression;
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/database/apply-schema.js
function applySchema(args) {
  applyAccountDatabaseSchema(args.sqlite);
  applyKeyValueDatabaseSchema(args.sqlite);
  args.sqlite.exec`

  PRAGMA foreign_keys = ON;
  PRAGMA auto_vacuum = 2; -- incremental https://www.sqlite.org/pragma.html#pragma_auto_vacuum
 
  -- file

  CREATE TABLE IF NOT EXISTS file (
    id TEXT PRIMARY KEY DEFAULT (nano_id(10)),
    path TEXT NOT NULL UNIQUE,
    data BLOB NOT NULL,
    metadata BLOB,
    

    CHECK (is_valid_file_path(path))
  ) STRICT;

  CREATE TABLE IF NOT EXISTS file_queue (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    file_id TEXT NOT NULL,
    data_before BLOB,
    data_after BLOB,
    path_before TEXT,
    path_after TEXT,
    metadata_before BLOB,
    metadata_after BLOB
  ) STRICT;

  CREATE TRIGGER IF NOT EXISTS file_insert BEFORE INSERT ON file
  BEGIN
    INSERT INTO file_queue(
      file_id, path_after, data_after, metadata_after
    )
    VALUES (
      NEW.id, NEW.path, NEW.data, NEW.metadata
    );
    SELECT triggerFileQueue();
  END;

  CREATE TRIGGER IF NOT EXISTS file_update BEFORE UPDATE ON file
  BEGIN
    INSERT INTO file_queue(
      file_id, 
      path_before, data_before, metadata_before, 
      path_after, data_after, metadata_after
    )

    VALUES (
      NEW.id, 
      OLD.path, OLD.data, OLD.metadata,
      NEW.path, NEW.data, NEW.metadata
    );

    SELECT triggerFileQueue();
  END;

  CREATE TRIGGER IF NOT EXISTS file_delete BEFORE DELETE ON file
  BEGIN
    INSERT INTO file_queue(file_id)
    VALUES (OLD.id);
    SELECT triggerFileQueue();
  END;

  CREATE TABLE IF NOT EXISTS change (
    id TEXT PRIMARY KEY DEFAULT (uuid_v7()),
    entity_id TEXT NOT NULL,
    schema_key TEXT NOT NULL,
    file_id TEXT NOT NULL,
    plugin_key TEXT NOT NULL,
    snapshot_id TEXT NOT NULL,
    created_at TEXT DEFAULT CURRENT_TIMESTAMP NOT NULL,

    UNIQUE (id, entity_id, file_id, schema_key),
    FOREIGN KEY(snapshot_id) REFERENCES snapshot(id)
  ) STRICT;

  CREATE TABLE IF NOT EXISTS change_author (
    change_id TEXT NOT NULL,
    account_id TEXT NOT NULL,

    PRIMARY KEY (change_id, account_id),
    FOREIGN KEY(change_id) REFERENCES change(id),
    FOREIGN KEY(account_id) REFERENCES account(id)
  ) strict;

  CREATE TABLE IF NOT EXISTS change_edge (
    parent_id TEXT NOT NULL,
    child_id TEXT NOT NULL,
    
    PRIMARY KEY (parent_id, child_id),
    FOREIGN KEY(parent_id) REFERENCES change(id),
    FOREIGN KEY(child_id) REFERENCES change(id),
    -- Prevent self referencing edges
    CHECK (parent_id != child_id)
  ) STRICT;

  CREATE TABLE IF NOT EXISTS snapshot (
    id TEXT GENERATED ALWAYS AS (json_sha256(content)) STORED UNIQUE,
    content BLOB
  ) STRICT;

  -- Create the default 'no-content' snapshot
  -- to avoid foreign key constraint violations in tests
  INSERT OR IGNORE INTO snapshot (content) VALUES (NULL);

  -- conflicts

  CREATE INDEX IF NOT EXISTS idx_content_hash ON snapshot (id);

  CREATE TABLE IF NOT EXISTS change_conflict (
    id TEXT PRIMARY KEY DEFAULT (uuid_v7()),
    
    key TEXT NOT NULL,
    change_set_id TEXT NOT NULL,
    FOREIGN KEY(change_set_id) REFERENCES change_set(id)
  ) STRICT;

  CREATE TABLE IF NOT EXISTS change_conflict_resolution (
    change_conflict_id TEXT NOT NULL,
    resolved_change_id TEXT NOT NULL,
    
    -- potential future columns
    -- resolved_by <account_id>
    -- resolved_at <timestamp>

    PRIMARY KEY(change_conflict_id, resolved_change_id),
    FOREIGN KEY(change_conflict_id) REFERENCES change_conflict(id),
    FOREIGN KEY(resolved_change_id) REFERENCES change(id)
  ) STRICT;

  -- change sets

  CREATE TABLE IF NOT EXISTS change_set (
    id TEXT PRIMARY KEY DEFAULT (nano_id(16))
  ) STRICT;

  CREATE TABLE IF NOT EXISTS change_set_element (
    
    change_set_id TEXT NOT NULL,
    change_id TEXT NOT NULL,

    PRIMARY KEY(change_set_id, change_id),
    FOREIGN KEY(change_set_id) REFERENCES change_set(id),    
    FOREIGN KEY(change_id) REFERENCES change(id)
  ) STRICT;

  CREATE TABLE IF NOT EXISTS change_set_label (
    label_id TEXT NOT NULL,
    change_set_id TEXT NOT NULL,
    PRIMARY KEY(label_id, change_set_id),
    FOREIGN KEY(label_id) REFERENCES label(id),
    FOREIGN KEY(change_set_id) REFERENCES change_set(id)
  ) STRICT;

  -- discussions 

  CREATE TABLE IF NOT EXISTS discussion (
    id TEXT PRIMARY KEY DEFAULT (nano_id(12)),
    change_set_id TEXT NOT NULL,

    FOREIGN KEY(change_set_id) REFERENCES change_set(id)
  ) STRICT;

  CREATE TABLE IF NOT EXISTS comment (
    id TEXT PRIMARY KEY DEFAULT (nano_id(14)),
    parent_id TEXT,
    discussion_id TEXT NULL,
    content TEXT NOT NULL,
    
    FOREIGN KEY(discussion_id) REFERENCES discussion(id),
    FOREIGN KEY(parent_id) REFERENCES comment(id)
  ) STRICT;

  -- labels
  
  CREATE TABLE IF NOT EXISTS label (
    id TEXT PRIMARY KEY DEFAULT (nano_id(8)),
    
    name TEXT NOT NULL UNIQUE  -- e.g., 'checkpoint', 'reviewed'
    
  ) STRICT;

  INSERT OR IGNORE INTO label (name) VALUES ('checkpoint');
  INSERT OR IGNORE INTO label (name) VALUES ('grouped');

  -- versions

  CREATE TABLE IF NOT EXISTS version (
    id TEXT PRIMARY KEY DEFAULT (uuid_v7()),

    name TEXT NOT NULL UNIQUE DEFAULT (human_id())
  ) STRICT;

  CREATE TABLE IF NOT EXISTS version_change (
    version_id TEXT NOT NULL,
    change_id TEXT NOT NULL,

    entity_id TEXT NOT NULL,
    schema_key TEXT NOT NULL,
    file_id TEXT NOT NULL,

    PRIMARY KEY (version_id, change_id),
    FOREIGN KEY (version_id) REFERENCES version(id) ON DELETE CASCADE,
    FOREIGN KEY (change_id, entity_id, schema_key, file_id) REFERENCES change(id, entity_id, schema_key, file_id) ON DELETE CASCADE,

    UNIQUE (version_id, entity_id, schema_key, file_id)
  ) STRICT;

  CREATE TABLE IF NOT EXISTS version_change_conflict (
    version_id TEXT NOT NULL,
    change_conflict_id TEXT NOT NULL,

    PRIMARY KEY (version_id, change_conflict_id),
    FOREIGN KEY (version_id) REFERENCES version(id),
    FOREIGN KEY (change_conflict_id) REFERENCES change_conflict(id)
  ) STRICT;

  -- only one version can be active at a time
  -- hence, the table has only one row
  CREATE TABLE IF NOT EXISTS current_version (
    id TEXT NOT NULL PRIMARY KEY,

    FOREIGN KEY(id) REFERENCES version(id)
  ) STRICT;

  -- Insert the default version if missing
  -- (this is a workaround for not having a separata creation and migration schema's)

  INSERT INTO version (id, name)
  SELECT '019328cc-ccb0-7f51-96e8-524df4597ac6', 'main'
  WHERE NOT EXISTS (SELECT 1 FROM version);

  -- Set the default current version to 'main' if both tables are empty
  -- (this is a workaround for not having a separata creation and migration schema's)
  INSERT INTO current_version (id)
  SELECT '019328cc-ccb0-7f51-96e8-524df4597ac6'
  WHERE NOT EXISTS (SELECT 1 FROM current_version);


  CREATE TEMP TRIGGER IF NOT EXISTS insert_account_if_not_exists_on_change_author
  BEFORE INSERT ON change_author
  FOR EACH ROW
  WHEN NEW.account_id NOT IN (SELECT id FROM account) AND NEW.account_id IN (SELECT id FROM temp.active_account)
  BEGIN
    INSERT OR IGNORE INTO account
      SELECT 
      *
      FROM active_account 
      WHERE id = NEW.account_id;
  END;
  
  `;
  applyMutationLogDatabaseSchema(args.sqlite);
  return args.sqlite;
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/snapshot/json-sha-256.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var import_js_sha256 = __toESM(require_sha256(), 1);
function jsonSha256(content) {
  const sortedContent = deepSortObject(content);
  return (0, import_js_sha256.sha256)(JSON.stringify(sortedContent));
}
function deepSortObject(obj) {
  if (Array.isArray(obj)) {
    return obj.map((item) => typeof item === "object" && item !== null ? deepSortObject(item) : item);
  } else if (typeof obj === "object" && obj !== null) {
    return Object.keys(obj).sort().reduce((acc, key) => {
      acc[key] = deepSortObject(obj[key]);
      return acc;
    }, {});
  }
  return obj;
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/database/kysely-plugin/parse-jsonb-plugin-v1.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var sqlite;
function ParseJsonBPluginV1(jsonbColumns) {
  const jsonColumnNames = Object.keys(jsonbColumns).flatMap((key) => jsonbColumns[key]);
  return {
    transformResult: async (args) => {
      if (!sqlite) {
        sqlite = await createInMemoryDatabase({});
      }
      for (const row of args.result.rows) {
        for (const col of jsonColumnNames) {
          if (!row[col]) {
            continue;
          }
          try {
            const json = sqlite.exec("SELECT json(?)", {
              bind: [row[col]],
              returnValue: "resultRows"
            })[0][0];
            row[col] = JSON.parse(json);
          } catch {
            continue;
          }
        }
      }
      return args.result;
    },
    transformQuery: (args) => args.node
  };
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/database/kysely-plugin/serialize-jsonb-plugin.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function SerializeJsonBPlugin() {
  const parseJsonTransformer = new SerializeJsonbTransformer();
  return {
    transformResult: async (args) => args.result,
    transformQuery(args) {
      if (args.node.kind === "InsertQueryNode" || args.node.kind === "UpdateQueryNode") {
        const result = parseJsonTransformer.transformNode(args.node);
        return result;
      }
      return args.node;
    }
  };
}
var SerializeJsonbTransformer = class extends OperationNodeTransformer {
  transformOnConflict(node) {
    var _a8;
    return super.transformOnConflict({
      ...node,
      updates: (_a8 = node.updates) == null ? void 0 : _a8.map((updateItem) => {
        if (updateItem.kind !== "ColumnUpdateNode") {
          return updateItem;
        }
        return {
          kind: "ColumnUpdateNode",
          column: updateItem.column,
          value: this.transformValue(
            // @ts-expect-error - type mismatch
            updateItem.value
          )
        };
      })
    });
  }
  transformValue(node) {
    const { value } = node;
    const serializedValue = maybeSerializeJson(value);
    if (value === serializedValue) {
      return node;
    }
    return sql`jsonb(${serializedValue})`.toOperationNode();
  }
  /**
   * Transforms the value list node by replacing all JSON objects with `jsonb` function calls.
   */
  transformValueList(node) {
    return super.transformValueList({
      ...node,
      values: node.values.map((listNodeItem) => {
        if (listNodeItem.kind !== "ValueNode") {
          return listNodeItem;
        }
        const { value } = listNodeItem;
        const serializedValue = maybeSerializeJson(value);
        if (value === serializedValue) {
          return listNodeItem;
        }
        return sql`jsonb(${serializedValue})`.toOperationNode();
      })
    });
  }
  /**
   * changes PrimitiveValueListNode to ValueListNode to allow kysely to process objects
   */
  transformValues(node) {
    return super.transformValues({
      ...node,
      values: node.values.map((valueItemNode) => {
        if (valueItemNode.kind !== "PrimitiveValueListNode") {
          return valueItemNode;
        }
        return {
          kind: "ValueListNode",
          values: valueItemNode.values.map((value) => ({
            kind: "ValueNode",
            value
          }))
        };
      })
    });
  }
};
function maybeSerializeJson(value) {
  if (
    // binary data
    value instanceof ArrayBuffer || // uint8array, etc
    ArrayBuffer.isView(value) || value === null || value === void 0
  ) {
    return value;
  } else if (typeof value === "object" || Array.isArray(value)) {
    return JSON.stringify(value);
  }
  return value;
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/database/mutation-log/lix-session.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function createSession() {
  const sessionId = v4_default();
  let time = 0;
  return {
    /**
     * Returns the current lix session id.
     */
    id: () => {
      return sessionId;
    },
    sessionClockTick: () => {
      time += 1;
      return time;
    }
  };
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/own-change-control/database-triggers.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function applyOwnChangeControlTriggers(sqlite2, db) {
  const tableInfos = {};
  for (const table of Object.keys(changeControlledTableIds)) {
    tableInfos[table] = sqlite2.exec({
      sql: `PRAGMA table_info(${table});`,
      returnValue: "resultRows",
      rowMode: "object"
    });
  }
  sqlite2.createFunction({
    name: "handle_lix_own_change_control",
    arity: -1,
    // @ts-expect-error - dynamic function
    xFunc: (_ctx, tableName, operation, ...value) => {
      return handleLixOwnEntityChange(db, sqlite2, tableName, tableInfos, operation, ...value);
    }
  });
  for (const table of Object.keys(changeControlledTableIds)) {
    const tableInfo = tableInfos[table];
    const sql2 = `
      CREATE TEMP TRIGGER IF NOT EXISTS ${table}_change_control_insert
      AFTER INSERT ON ${table}
      BEGIN
        SELECT handle_lix_own_change_control('${table}', 'insert', ${tableInfo.map((c3) => "NEW." + c3.name).join(", ")});
      END;
      
      CREATE TEMP TRIGGER IF NOT EXISTS ${table}_change_control_update
      AFTER UPDATE ON ${table}
			${// ignore update trigger if the change controlled properties
    // did not change (a plugin likely called apply changes on the file.data)
    table === "file" ? `
			WHEN (
				OLD.id IS NOT NEW.id OR
				OLD.path IS NOT NEW.path OR
				OLD.metadata IS NOT NEW.metadata
			)` : ""}
      BEGIN
        SELECT handle_lix_own_change_control('${table}', 'update', ${tableInfo.map((c3) => "NEW." + c3.name).join(", ")});
      END;

      CREATE TEMP TRIGGER IF NOT EXISTS ${table}_change_control_delete
      AFTER DELETE ON ${table}
      BEGIN
        SELECT handle_lix_own_change_control('${table}', 'delete', ${tableInfo.map((c3) => "OLD." + c3.name).join(", ")});
      END;
      `;
    sqlite2.exec(sql2);
  }
}
function handleLixOwnEntityChange(db, sqlite2, tableName, tableInfos, operation, ...values) {
  var _a8;
  const lix = { db, sqlite: sqlite2 };
  if (tableName === "key_value" && values[2]) {
    return;
  }
  const shouldSkip = ((_a8 = executeSync({
    lix,
    query: db.selectFrom("key_value").where("key", "=", "lix_skip_own_change_control").select("value")
  })[0]) == null ? void 0 : _a8.value) === "true";
  if (shouldSkip) {
    return;
  }
  const change = executeSync({
    lix,
    query: db.selectFrom("change").where("id", "=", values[0]).select("plugin_key")
  })[0];
  if ((change == null ? void 0 : change.plugin_key) === "lix_own_change_control") {
    return;
  }
  const currentVersion = executeSync({
    lix,
    query: db.selectFrom("current_version").innerJoin("version", "current_version.id", "version.id").selectAll("version")
  })[0];
  const authors = executeSync({
    lix,
    query: db.selectFrom("active_account").selectAll()
  });
  if (authors.length === 0) {
    console.error(tableName, change);
    throw new Error("At least one author is required");
  }
  let snapshotContent;
  if (operation === "delete") {
    snapshotContent = null;
  } else {
    snapshotContent = {};
    for (const [index, column] of tableInfos[tableName].entries()) {
      snapshotContent[column.name] = values[index];
    }
  }
  if (tableName === "file" && snapshotContent) {
    const json = sqlite2.exec("SELECT json(?)", {
      bind: [snapshotContent.metadata],
      returnValue: "resultRows"
    })[0][0];
    snapshotContent["metadata"] = JSON.parse(json);
    delete snapshotContent.data;
  }
  const entityId = entityIdForRow(tableName, ...values);
  createChange({
    lix,
    authors,
    version: currentVersion,
    entityId,
    fileId: "lix_own_change_control",
    pluginKey: "lix_own_change_control",
    schemaKey: `lix_${tableName}_table`,
    snapshotContent
  }, {
    updateVersionChanges: tableName === "version_change" ? false : true
  });
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/database/init-db.js
var import_human_id2 = __toESM(require_dist(), 1);

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/database/nano-id.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var insecureRandom = (array) => {
  for (let i2 = 0; i2 < array.length; i2++) {
    array[i2] = Math.floor(Math.random() * 256);
  }
  return array;
};
var random = (bytes) => {
  const array = new Uint8Array(bytes);
  if (typeof crypto !== "undefined" && crypto.getRandomValues) {
    return crypto.getRandomValues(array);
  }
  return insecureRandom(array);
};
var customRandom = (alphabet, defaultSize, getRandom) => {
  const mask = (2 << Math.log2(alphabet.length - 1)) - 1;
  const step = -~(1.6 * mask * defaultSize / alphabet.length);
  return (size = defaultSize) => {
    let id = "";
    while (true) {
      const bytes = getRandom(step);
      let j2 = step | 0;
      while (j2--) {
        id += alphabet[bytes[j2] & mask] || "";
        if (id.length >= size)
          return id;
      }
    }
  };
};
var customAlphabet = (alphabet, size = 21) => customRandom(alphabet, size | 0, random);
var _nanoIdAlphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var nanoid = customAlphabet(_nanoIdAlphabet);

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/database/init-db.js
function initDb(args) {
  initFunctions({ sqlite: args.sqlite });
  applySchema({ sqlite: args.sqlite });
  const db = new Kysely({
    dialect: createDialect({
      database: args.sqlite
    }),
    plugins: [
      ParseJsonBPluginV1({
        // jsonb columns
        file: ["metadata"],
        file_queue: ["metadata_before", "metadata_after"],
        snapshot: ["content"],
        mutation_log: ["row_id"]
      }),
      SerializeJsonBPlugin()
    ]
  });
  applyOwnChangeControlTriggers(args.sqlite, db);
  return db;
}
function initFunctions(args) {
  args.sqlite.createFunction({
    name: "uuid_v7",
    arity: 0,
    xFunc: () => v7_default()
  });
  args.sqlite.createFunction({
    name: "uuid_v4",
    arity: 0,
    xFunc: () => v4_default()
  });
  args.sqlite.createFunction({
    name: "json_sha256",
    arity: 1,
    xFunc: (_ctx, value) => {
      if (!value) {
        return "no-content";
      }
      const json = args.sqlite.exec("SELECT json(?)", {
        bind: [value],
        returnValue: "resultRows"
      })[0][0];
      const parsed = JSON.parse(json);
      return jsonSha256(parsed);
    },
    deterministic: true
  });
  args.sqlite.createFunction({
    name: "is_valid_file_path",
    arity: 1,
    xFunc: (_ctx, value) => {
      return validateFilePath(value);
    },
    deterministic: true
  });
  const lixSession = createSession();
  args.sqlite.createFunction({
    name: "lix_session",
    arity: 0,
    xFunc: () => lixSession.id()
  });
  args.sqlite.createFunction({
    name: "lix_session_clock_tick",
    arity: 0,
    xFunc: () => lixSession.sessionClockTick()
  });
  args.sqlite.createFunction({
    name: "human_id",
    arity: 0,
    xFunc: () => (0, import_human_id2.humanId)({ separator: "-", capitalize: false })
  });
  args.sqlite.createFunction({
    name: "nano_id",
    arity: 1,
    // @ts-expect-error - not sure why this is not working
    xFunc: (_ctx, length) => {
      return nanoid(length);
    }
  });
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/file-queue/file-queue-process.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/file-queue/file-handlers.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
async function glob(args) {
  var _a8;
  const result = await sql`SELECT CASE WHEN ${args.path} GLOB ${args.glob} THEN 1 ELSE 0 END AS matches`.execute(args.lix.db);
  return ((_a8 = result.rows[0]) == null ? void 0 : _a8.matches) === 1;
}
async function handleFileInsert(args) {
  const detectedChanges = [];
  const plugins = await args.lix.plugin.getAll();
  const path2 = args.fileQueueEntry.path_after ?? args.fileQueueEntry.path_before;
  if (path2 === null) {
    throw new Error("Both before and after paths are null");
  }
  for (const plugin2 of plugins) {
    if (!plugin2.detectChangesGlob || !await glob({
      lix: args.lix,
      path: path2,
      glob: plugin2.detectChangesGlob
    })) {
      break;
    }
    if (plugin2.detectChanges === void 0) {
      const error = new Error("Plugin does not support detecting changes even though the glob matches.");
      console.error(error);
      throw error;
    }
    if (args.fileQueueEntry.data_after === null) {
      throw new Error("Data after is null");
    }
    for (const change of await plugin2.detectChanges({
      lix: args.lix,
      before: void 0,
      after: {
        id: args.fileQueueEntry.file_id,
        path: path2,
        metadata: args.fileQueueEntry.metadata_after,
        data: args.fileQueueEntry.data_after
      }
    })) {
      detectedChanges.push({
        ...change,
        pluginKey: plugin2.key
      });
    }
  }
  await args.lix.db.transaction().execute(async (trx) => {
    const currentAuthors = await trx.selectFrom("active_account").selectAll().execute();
    const currentVersion = await trx.selectFrom("current_version").innerJoin("version", "current_version.id", "version.id").selectAll().executeTakeFirstOrThrow();
    await Promise.all(detectedChanges.map(async (detectedChange) => {
      await createChange({
        lix: { ...args.lix, db: trx },
        authors: currentAuthors,
        version: currentVersion,
        entityId: detectedChange.entity_id,
        fileId: args.fileQueueEntry.file_id,
        pluginKey: detectedChange.pluginKey,
        schemaKey: detectedChange.schema.key,
        snapshotContent: detectedChange.snapshot
      });
    }));
    await trx.deleteFrom("file_queue").where("id", "=", args.fileQueueEntry.id).execute();
  });
}
async function handleFileUpdate(args) {
  const detectedChanges = [];
  const plugins = await args.lix.plugin.getAll();
  const path2 = args.fileQueueEntry.path_after ?? args.fileQueueEntry.path_before;
  if (path2 === null) {
    throw new Error("Both before and after paths are null");
  }
  for (const plugin2 of plugins) {
    if (!plugin2.detectChangesGlob || !await glob({
      lix: args.lix,
      path: path2,
      glob: plugin2.detectChangesGlob
    })) {
      break;
    }
    if (plugin2.detectChanges === void 0) {
      const error = new Error("Plugin does not support detecting changes even though the glob matches.");
      console.error(error);
      throw error;
    }
    for (const change of await plugin2.detectChanges({
      lix: args.lix,
      before: args.fileQueueEntry.data_before ? {
        id: args.fileQueueEntry.file_id,
        path: path2,
        metadata: args.fileQueueEntry.metadata_before,
        data: args.fileQueueEntry.data_before
      } : void 0,
      after: {
        id: args.fileQueueEntry.file_id,
        path: path2,
        metadata: args.fileQueueEntry.metadata_after,
        data: args.fileQueueEntry.data_after
      }
    })) {
      detectedChanges.push({
        ...change,
        pluginKey: plugin2.key
      });
    }
  }
  await args.lix.db.transaction().execute(async (trx) => {
    const currentAuthors = await trx.selectFrom("active_account").selectAll().execute();
    const currentVersion = await trx.selectFrom("current_version").innerJoin("version", "current_version.id", "version.id").selectAll().executeTakeFirstOrThrow();
    await Promise.all(detectedChanges.map(async (detectedChange) => {
      await createChange({
        lix: { ...args.lix, db: trx },
        authors: currentAuthors,
        version: currentVersion,
        entityId: detectedChange.entity_id,
        fileId: args.fileQueueEntry.file_id,
        pluginKey: detectedChange.pluginKey,
        schemaKey: detectedChange.schema.key,
        snapshotContent: detectedChange.snapshot
      });
    }));
    await trx.deleteFrom("file_queue").where("id", "=", args.fileQueueEntry.id).execute();
  });
}
async function handleFileDelete(args) {
  await args.lix.db.transaction().execute(async (trx) => {
    const currentVersion = await trx.selectFrom("current_version").innerJoin("version", "current_version.id", "version.id").selectAll().executeTakeFirstOrThrow();
    const toBeDeletedEntities = await trx.selectFrom("change").where("file_id", "=", args.fileQueueEntry.file_id).where(changeIsLeafInVersion(currentVersion)).select("entity_id").select("schema_key").select("plugin_key").execute();
    const currentAuthors = await trx.selectFrom("active_account").selectAll().execute();
    await Promise.all(toBeDeletedEntities.map(async (change) => {
      await createChange({
        lix: { ...args.lix, db: trx },
        authors: currentAuthors,
        version: currentVersion,
        entityId: change.entity_id,
        fileId: args.fileQueueEntry.file_id,
        pluginKey: change.plugin_key,
        schemaKey: change.schema_key,
        snapshotContent: null
        // Snapshot is null for deletions
      });
    }));
    await trx.deleteFrom("file_queue").where("id", "=", args.fileQueueEntry.id).execute();
  });
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/file-queue/file-queue-process.js
async function initFileQueueProcess(args) {
  args.lix.sqlite.createFunction({
    name: "triggerFileQueue",
    arity: 0,
    // @ts-expect-error - dynamic function
    xFunc: () => {
      queueWorker();
    }
  });
  let pending;
  let resolve2;
  let runNumber = 1;
  let hasMoreEntriesSince = void 0;
  async function queueWorker(trail = false) {
    try {
      if (args.lix.sqlite.isOpen() === false) {
        return;
      }
      if (pending && !trail) {
        hasMoreEntriesSince = runNumber;
        return;
      }
      runNumber++;
      if (!pending) {
        pending = new Promise((res) => {
          resolve2 = res;
        });
      }
      const entry = await args.lix.db.selectFrom("file_queue").selectAll().orderBy("id", "asc").limit(1).executeTakeFirst();
      if (entry) {
        if (entry.data_before && entry.data_after) {
          await handleFileUpdate({
            fileQueueEntry: entry,
            lix: args.lix
          });
        } else if (!entry.data_before && entry.data_after) {
          await handleFileInsert({
            fileQueueEntry: entry,
            lix: args.lix
          });
        } else {
          await handleFileDelete({
            fileQueueEntry: entry,
            lix: args.lix
          });
        }
      }
      const { numEntries } = await args.lix.db.selectFrom("file_queue").select((eb) => eb.fn.count("id").as("numEntries")).executeTakeFirstOrThrow();
      if (!hasMoreEntriesSince || numEntries === 0 && hasMoreEntriesSince < runNumber) {
        resolve2();
        hasMoreEntriesSince = void 0;
        pending = void 0;
      } else {
        queueWorker(true);
      }
    } catch (e2) {
      if (e2 instanceof Error && (e2.message.includes("DB has been closed") || e2.message.includes("driver has already been destroyed"))) {
        return;
      }
      console.error("file queue failed ", e2);
    }
  }
  queueWorker();
  return;
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/sync/sync-process.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/sync/push-to-server.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/sync/get-diffing-rows.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
async function getDiffingRows(args) {
  const upsertedRows = {};
  let state = [];
  const executeInTransaction = async (trx) => {
    state = await trx.selectFrom("mutation_log").select(({ fn }) => {
      return ["session", fn.max("session_time").as("time")];
    }).groupBy("session").execute();
    let operationsToPush = trx.selectFrom("mutation_log").selectAll("mutation_log");
    if (args.targetVectorClock.length > 0) {
      operationsToPush = operationsToPush.where((eb) => {
        const knownSessions = args.targetVectorClock.map((sessionTime) => sessionTime.session);
        const ors = [];
        ors.push(eb("session", "not in", knownSessions));
        for (const sessionTime of args.targetVectorClock) {
          ors.push(eb("session", "=", sessionTime.session).and("session_time", ">", sessionTime.time));
        }
        return eb.or(ors);
      });
    }
    upsertedRows["mutation_log"] = await operationsToPush.execute();
    for (const operation of upsertedRows["mutation_log"]) {
      const tableName = operation.table_name;
      if (upsertedRows[tableName] === void 0) {
        upsertedRows[tableName] = [];
      }
      if (tableName === "snapshot") {
        upsertedRows[tableName].push(await trx.selectFrom(tableName).selectAll().where("id", "=", operation.row_id["id"]).executeTakeFirstOrThrow());
      } else {
        let diffRow = trx.selectFrom(tableName).selectAll();
        for (const [key, value] of Object.entries(operation.row_id)) {
          diffRow = diffRow.where(key, "=", value);
        }
        upsertedRows[tableName].push(await diffRow.executeTakeFirstOrThrow());
      }
    }
  };
  if (args.lix.db.isTransaction) {
    await executeInTransaction(args.lix.db);
  } else {
    await args.lix.db.transaction().execute(executeInTransaction);
  }
  return {
    state,
    upsertedRows
  };
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/sync/push-to-server.js
async function pushToServer(args) {
  const { upsertedRows: tableRowsToPush, state } = await getDiffingRows({
    lix: args.lix,
    targetVectorClock: args.targetVectorClock
  });
  if (Object.keys(tableRowsToPush).length === 0) {
    return;
  }
  const response = await fetch(new Request(`${args.serverUrl}/lsp/push-v1`, {
    method: "POST",
    body: JSON.stringify({
      lix_id: args.id,
      vector_clock: state,
      data: tableRowsToPush
    }),
    headers: {
      "Content-Type": "application/json"
    }
  }));
  if (!response.ok) {
    const body = await response.json();
    throw new Error(`Failed to push to server: ${body.code} ${body.message}`);
  }
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/sync/pull-from-server.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/sync/merge-state.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
async function mergeTheirState(args) {
  const executeInTransaction = async (trx) => {
    var _a8;
    const myVectorClock = await trx.selectFrom("mutation_log").select(({ fn }) => {
      return ["session", fn.max("session_time").as("time")];
    }).where("mutation_log.table_name", "<>", "mutation_log").groupBy("session").execute();
    const unrecognizedSesionTicks = aheadSessions(myVectorClock, args.sourceVectorClock);
    const moreRecentRowUpdatesUnknownBySource = unrecognizedSesionTicks.length === 0 ? [] : await trx.selectFrom("mutation_log").select(({ fn }) => {
      return [
        "table_name",
        "row_id",
        fn.max("wall_clock").as("last_updated_wall_time")
      ];
    }).where((eb) => {
      return eb.or(unrecognizedSesionTicks.map(({ session, time }) => {
        return eb("session", "=", session).and("session_time", ">", time);
      }));
    }).where("mutation_log.table_name", "<>", "mutation_log").groupBy("row_id").execute();
    const rowsIUpdatedLast = moreRecentRowUpdatesUnknownBySource.reduce((acc, { table_name, row_id, last_updated_wall_time }) => {
      if (!acc[table_name]) {
        acc[table_name] = {};
      }
      acc[table_name][rowIdToString(table_name, row_id)] = last_updated_wall_time;
      return acc;
    }, {});
    const sourceMutationLog = args.sourceData["mutation_log"];
    if (sourceMutationLog === void 0) {
      throw new Error("Missing mutation log in source data");
    }
    for (let i2 = 0; i2 < sourceMutationLog.length; i2++) {
      const opertionInSource = sourceMutationLog[i2];
      const tableName = opertionInSource["table_name"];
      const time = opertionInSource["wall_clock"];
      const row_id = rowIdToString(tableName, opertionInSource["row_id"]);
      if (rowsIUpdatedLast[tableName] && rowsIUpdatedLast[tableName][row_id] && rowsIUpdatedLast[tableName][row_id] < time) {
        delete rowsIUpdatedLast[tableName][row_id];
      }
    }
    if (args.sourceData["mutation_log"]) {
      for (const row of args.sourceData["mutation_log"]) {
        await trx.insertInto("mutation_log").values(row).execute();
      }
    }
    await trx.insertInto("mutation_log").values({
      session: "mock",
      wall_clock: 0,
      session_time: 0,
      row_id: { ignored: "ignored" },
      table_name: "mutation_log",
      operation: "INSERT"
    }).execute();
    for (const tableName of tablesByDepencies) {
      const tableRows = args.sourceData[tableName];
      if (tableRows === void 0) {
        continue;
      }
      for (const row of tableRows) {
        if (((_a8 = rowsIUpdatedLast[tableName]) == null ? void 0 : _a8[rowIdToString(tableName, row)]) === void 0) {
          if (tableName === "snapshot") {
            delete row.id;
          }
          const statment = trx.insertInto(tableName).values(row).onConflict((oc) => {
            for (const idColumn of tableIdColumns[tableName]) {
              oc = oc.column(idColumn);
            }
            return oc.doUpdateSet(row);
          });
          await statment.execute();
        } else {
          console.log("Row skiped - " + tableName + " - " + rowIdToString(tableName, row));
        }
      }
    }
    await trx.deleteFrom("mutation_log").where("table_name", "=", "mutation_log").execute();
  };
  if (args.lix.db.isTransaction) {
    return await executeInTransaction(args.lix.db);
  } else {
    return await args.lix.db.transaction().execute(executeInTransaction);
  }
}
function aheadSessions(mine, theirs) {
  const mineSessionMap = new Map(mine.map(({ session, time }) => [session, time]));
  const theirSessionMap = new Map(theirs.map(({ session, time }) => [session, time]));
  const aheadSession = [];
  const allSessions = /* @__PURE__ */ new Set([
    ...mineSessionMap.keys(),
    ...theirSessionMap.keys()
  ]);
  allSessions.forEach((session) => {
    const myTime = mineSessionMap.get(session);
    const theirTime = theirSessionMap.get(session);
    if (myTime && (theirTime === void 0 || myTime > theirTime)) {
      aheadSession.push({ session, time: theirTime ?? 0 });
    }
  });
  return aheadSession;
}
function rowIdToString(tableName, rowId) {
  const idColumns = tableIdColumns[tableName];
  let rowIdString = tableName;
  for (const idColumn of idColumns) {
    if (!rowId[idColumn]) {
      throw new Error(`Missing id column ${idColumn} in row id`);
    }
    rowIdString += `_${rowId[idColumn]}`;
  }
  return rowIdString;
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/sync/pull-from-server.js
async function pullFromServer(args) {
  const sessionStatesClient = await args.lix.db.selectFrom("mutation_log").select(({ fn }) => {
    return ["session", fn.max("session_time").as("time")];
  }).groupBy("session").execute();
  const response = await fetch(new Request(`${args.serverUrl}/lsp/pull-v1`, {
    method: "POST",
    body: JSON.stringify({
      lix_id: args.id,
      vector_clock: sessionStatesClient
    }),
    headers: {
      "Content-Type": "application/json"
    }
  }));
  if (response.ok === false) {
    try {
      const body2 = await response.json();
      throw new Error(`Failed to pull from server: ${body2.code} ${body2.message}`);
    } catch {
      throw new Error(`Failed to pull from server: ${response.status} ${response.statusText}`);
    }
  }
  const body = await response.json();
  const data = body.data;
  const sessionStateServer = body.vector_clock;
  const changes = data["change"] ?? [];
  await args.lix.db.transaction().execute(async (trx) => {
    await trx.executeQuery(CompiledQuery.raw("PRAGMA defer_foreign_keys = ON;"));
    const currentVersion = await trx.selectFrom("current_version").select("id").executeTakeFirstOrThrow();
    const versionChanges = [];
    const versionChangeConflicts = [];
    const changesInCurrentVersion = [];
    for (const change of changes) {
      if (change.schema_key === "lix_version_change_table" || change.schema_key === "lix_version_change_conflict_table") {
        const [versionId] = change.entity_id.split(",");
        if (change.schema_key === "lix_version_change_table") {
          if (versionId === currentVersion.id) {
            const [, changeId] = change.entity_id.split(",");
            const matchingChange = changes.find((c3) => c3.id === changeId);
            if (!matchingChange) {
              throw new Error("Expected matching change");
            }
            changesInCurrentVersion.push(matchingChange);
          }
          versionChanges.push(change);
        } else if (change.schema_key === "lix_version_change_conflict_table") {
          versionChangeConflicts.push(change);
        } else {
          throw new Error("Unexpected schema key");
        }
      }
    }
    const changesToApply = [
      ...versionChanges,
      ...versionChangeConflicts,
      ...changesInCurrentVersion
    ];
    await mergeTheirState({
      lix: { ...args.lix, db: trx },
      sourceVectorClock: sessionStateServer,
      sourceData: data
    });
    if (changesToApply.length > 0) {
      await applyChanges({
        lix: { ...args.lix, db: trx },
        changes: changesToApply
      });
    }
  });
  return sessionStateServer;
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/lix/to-blob.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
async function toBlob(args) {
  return new Blob([contentFromDatabase(args.lix.sqlite)]);
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/sync/sync-process.js
async function initSyncProcess(args) {
  const lixId = await args.lix.db.selectFrom("key_value").where("key", "=", "lix_id").select("value").executeTakeFirstOrThrow();
  const pullAndPush = async () => {
    const shouldSync = await args.lix.db.selectFrom("key_value").where("key", "=", "lix_sync").select("value").executeTakeFirst();
    if ((shouldSync == null ? void 0 : shouldSync.value) !== "true") {
      return;
    }
    const url = await args.lix.db.selectFrom("key_value").where("key", "=", "lix_server_url").select("value").executeTakeFirst();
    if (!url) {
      return;
    }
    try {
      const serverState = await pullFromServer({
        serverUrl: url.value,
        lix: args.lix,
        id: lixId.value
      });
      await pushToServer({
        serverUrl: url.value,
        lix: args.lix,
        id: lixId.value,
        targetVectorClock: serverState
      });
    } catch (e2) {
      const response = await fetch(new Request(`${url.value}/lsp/new-v1`, {
        method: "POST",
        body: await toBlob({ lix: args.lix })
      }));
      if (!response.ok && response.status !== 409) {
        throw e2;
      }
    }
  };
  function schedulePullAndPush() {
    if (args.lix.sqlite.isOpen() === false) {
      return;
    }
    pullAndPush().catch((e2) => {
      if (e2 instanceof Error && e2.message.includes("DB has been closed.")) {
        return;
      }
      console.error("Error in sync process", e2);
    });
    setTimeout(() => {
      schedulePullAndPush();
    }, 750);
  }
  schedulePullAndPush();
  return;
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/lix/open-lix.js
async function openLix(args) {
  const db = initDb({ sqlite: args.database });
  if (args.keyValues && args.keyValues.length > 0) {
    await db.insertInto("key_value").values(args.keyValues).onConflict((oc) => oc.doUpdateSet((eb) => ({ value: eb.ref("excluded.value") }))).execute();
  }
  if (args.account) {
    await db.transaction().execute(async (trx) => {
      await trx.deleteFrom("active_account").execute();
      await trx.insertInto("active_account").values(args.account).onConflict((oc) => oc.doUpdateSet(() => ({ ...args.account }))).execute();
    });
  }
  const plugins = [];
  if (args.providePlugins && args.providePlugins.length > 0) {
    plugins.push(...args.providePlugins);
  }
  const plugin2 = {
    getAll: async () => plugins
  };
  await initFileQueueProcess({ lix: { db, plugin: plugin2, sqlite: args.database } });
  await initSyncProcess({ lix: { db, plugin: plugin2, sqlite: args.database } });
  return {
    db,
    sqlite: args.database,
    plugin: plugin2
  };
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/lix/open-lix-in-memory.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
async function openLixInMemory(args) {
  const database = await createInMemoryDatabase({
    readOnly: false
  });
  if (args.blob) {
    importDatabase({
      db: database,
      content: new Uint8Array(await args.blob.arrayBuffer())
    });
  }
  return openLix({ ...args, database });
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/lix/new-lix.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/lix/close-lix.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
async function closeLix(args) {
  await args.lix.db.destroy();
}

// ../../node_modules/.pnpm/@lix-js+sdk@0.4.10_babel-plugin-macros@3.1.0/node_modules/@lix-js/sdk/dist/lix/new-lix.js
async function newLixFile() {
  const sqlite2 = await createInMemoryDatabase({
    readOnly: false
  });
  const db = initDb({ sqlite: sqlite2 });
  try {
    return new Blob([contentFromDatabase(sqlite2)]);
  } catch (e2) {
    throw new Error(`Failed to create new Lix file: ${e2}`, { cause: e2 });
  } finally {
    closeLix({ lix: { db } });
  }
}

// ../sdk/dist/database/initDb.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../sdk/dist/database/schema.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function applySchema2(args) {
  const foreignKeyActivated = args.sqlite.exec("PRAGMA foreign_keys", {
    returnValue: "resultRows"
  });
  if (
    // first row that is returned
    // first column of the first row
    // is equal to 0, then foreign keys are disabled
    foreignKeyActivated[0][0] === 0
  ) {
    args.sqlite.exec("PRAGMA foreign_keys = ON", {
      returnValue: "resultRows"
    });
  }
  args.sqlite.exec(`
CREATE TABLE IF NOT EXISTS bundle (
  id TEXT PRIMARY KEY DEFAULT (human_id()),
	declarations BLOB NOT NULL DEFAULT (jsonb('[]'))
) strict;

CREATE TABLE IF NOT EXISTS message (
  id TEXT PRIMARY KEY DEFAULT (uuid_v7()), 
  bundle_id TEXT NOT NULL,
  locale TEXT NOT NULL,
  selectors BLOB NOT NULL DEFAULT (jsonb('[]')),
  FOREIGN KEY (bundle_id) REFERENCES bundle(id) ON DELETE CASCADE
) strict;


CREATE TABLE IF NOT EXISTS variant (
  id TEXT PRIMARY KEY DEFAULT (uuid_v7()), 
  message_id TEXT NOT NULL,
  matches BLOB NOT NULL DEFAULT (jsonb('[]')),
  pattern BLOB NOT NULL DEFAULT (jsonb('[]')),
  FOREIGN KEY (message_id) REFERENCES message(id) ON DELETE CASCADE
) strict;
  
CREATE INDEX IF NOT EXISTS idx_message_bundle_id ON message (bundle_id);
CREATE INDEX IF NOT EXISTS idx_variant_message_id ON variant (message_id);
		`);
}

// ../sdk/dist/human-id/human-id.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../sdk/dist/human-id/words.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var animals = [
  "albatross",
  "alligator",
  "alpaca",
  "anaconda",
  "angelfish",
  "ant",
  "anteater",
  "antelope",
  "ape",
  "baboon",
  "badger",
  "barbel",
  "bat",
  "bear",
  "beaver",
  "bee",
  "beetle",
  "bird",
  "bison",
  "blackbird",
  "boar",
  "bobcat",
  "bulldog",
  "bullock",
  "bumblebee",
  "butterfly",
  "buzzard",
  "camel",
  "canary",
  "capybara",
  "carp",
  "cat",
  "cheetah",
  "chicken",
  "chipmunk",
  "clownfish",
  "cobra",
  "cockroach",
  "cod",
  "cougar",
  "cow",
  "cowfish",
  "coyote",
  "crab",
  "crocodile",
  "crossbill",
  "crow",
  "cuckoo",
  "dachshund",
  "deer",
  "dingo",
  "dog",
  "dolphin",
  "donkey",
  "dove",
  "dragonfly",
  "duck",
  "eagle",
  "earthworm",
  "eel",
  "elephant",
  "elk",
  "emu",
  "falcon",
  "felix",
  "finch",
  "fireant",
  "firefox",
  "fish",
  "flamingo",
  "flea",
  "florian",
  "fly",
  "fox",
  "frog",
  "gadfly",
  "gazelle",
  "gecko",
  "gibbon",
  "giraffe",
  "goat",
  "goldfish",
  "goose",
  "gopher",
  "gorilla",
  "grebe",
  "grizzly",
  "gull",
  "guppy",
  "haddock",
  "halibut",
  "hamster",
  "hare",
  "hawk",
  "hedgehog",
  "herring",
  "hornet",
  "horse",
  "hound",
  "husky",
  "hyena",
  "ibex",
  "iguana",
  "impala",
  "insect",
  "jackal",
  "jackdaw",
  "jaguar",
  "jan",
  "jannes",
  "javelina",
  "jay",
  "jellyfish",
  "jurgen",
  "kangaroo",
  "kestrel",
  "kitten",
  "koala",
  "kudu",
  "ladybug",
  "lamb",
  "lark",
  "larva",
  "lemming",
  "lemur",
  "leopard",
  "liger",
  "lion",
  "lionfish",
  "lizard",
  "llama",
  "lobster",
  "loris",
  "lynx",
  "macaw",
  "maggot",
  "mallard",
  "mammoth",
  "manatee",
  "mantis",
  "mare",
  "marlin",
  "marmot",
  "marten",
  "martin",
  "mayfly",
  "meerkat",
  "midge",
  "millipede",
  "mink",
  "mole",
  "mongoose",
  "monkey",
  "moose",
  "moth",
  "mouse",
  "mule",
  "myna",
  "newt",
  "niklas",
  "nils",
  "nuthatch",
  "ocelot",
  "octopus",
  "okapi",
  "opossum",
  "orangutan",
  "oryx",
  "osprey",
  "ostrich",
  "otter",
  "owl",
  "ox",
  "panda",
  "panther",
  "parakeet",
  "parrot",
  "peacock",
  "pelican",
  "penguin",
  "pig",
  "pigeon",
  "piranha",
  "platypus",
  "polecat",
  "pony",
  "poodle",
  "porpoise",
  "puffin",
  "pug",
  "puma",
  "quail",
  "rabbit",
  "racoon",
  "rat",
  "raven",
  "ray",
  "reindeer",
  "robin",
  "rook",
  "rooster",
  "salmon",
  "samuel",
  "sawfish",
  "scallop",
  "seahorse",
  "seal",
  "shad",
  "shark",
  "sheep",
  "shell",
  "shrike",
  "shrimp",
  "skate",
  "skunk",
  "sloth",
  "slug",
  "snail",
  "snake",
  "sparrow",
  "spider",
  "squid",
  "squirrel",
  "starfish",
  "stingray",
  "stork",
  "swallow",
  "swan",
  "tadpole",
  "tapir",
  "termite",
  "tern",
  "thrush",
  "tiger",
  "toad",
  "tortoise",
  "toucan",
  "trout",
  "tuna",
  "turkey",
  "turtle",
  "vole",
  "vulture",
  "wallaby",
  "walrus",
  "warbler",
  "warthog",
  "wasp",
  "weasel",
  "whale",
  "wolf",
  "wombat",
  "worm",
  "wren",
  "yak",
  "zebra"
];
var adjectives = [
  "acidic",
  "active",
  "actual",
  "agent",
  "ago",
  "alert",
  "alive",
  "aloof",
  "antsy",
  "any",
  "aqua",
  "arable",
  "awake",
  "aware",
  "away",
  "awful",
  "bad",
  "bald",
  "basic",
  "best",
  "big",
  "bland",
  "blue",
  "bold",
  "born",
  "brave",
  "brief",
  "bright",
  "broad",
  "busy",
  "calm",
  "candid",
  "careful",
  "caring",
  "chunky",
  "civil",
  "clean",
  "clear",
  "close",
  "cool",
  "cozy",
  "crazy",
  "crisp",
  "cuddly",
  "curly",
  "cute",
  "dark",
  "day",
  "deft",
  "direct",
  "dirty",
  "dizzy",
  "drab",
  "dry",
  "due",
  "dull",
  "each",
  "early",
  "east",
  "elegant",
  "empty",
  "equal",
  "even",
  "every",
  "extra",
  "factual",
  "fair",
  "fancy",
  "few",
  "fine",
  "fit",
  "flaky",
  "flat",
  "fluffy",
  "formal",
  "frail",
  "free",
  "fresh",
  "front",
  "full",
  "fun",
  "funny",
  "fuzzy",
  "game",
  "gaudy",
  "giant",
  "glad",
  "good",
  "grand",
  "grassy",
  "gray",
  "great",
  "green",
  "gross",
  "happy",
  "heavy",
  "helpful",
  "heroic",
  "home",
  "honest",
  "hour",
  "house",
  "icy",
  "ideal",
  "inclusive",
  "inner",
  "jolly",
  "jumpy",
  "just",
  "keen",
  "key",
  "kind",
  "knotty",
  "known",
  "large",
  "last",
  "late",
  "lazy",
  "least",
  "left",
  "legal",
  "less",
  "level",
  "light",
  "lime",
  "livid",
  "lofty",
  "long",
  "loose",
  "lost",
  "loud",
  "loved",
  "low",
  "lower",
  "lucky",
  "mad",
  "main",
  "major",
  "male",
  "many",
  "maroon",
  "mealy",
  "mean",
  "mellow",
  "merry",
  "mild",
  "minor",
  "misty",
  "moving",
  "muddy",
  "mushy",
  "neat",
  "new",
  "next",
  "nice",
  "nimble",
  "noble",
  "noisy",
  "north",
  "novel",
  "odd",
  "ok",
  "only",
  "orange",
  "ornate",
  "patchy",
  "patient",
  "petty",
  "pink",
  "plain",
  "plane",
  "polite",
  "pretty",
  "proof",
  "proud",
  "quaint",
  "quick",
  "quiet",
  "raw",
  "real",
  "red",
  "round",
  "royal",
  "sad",
  "safe",
  "salty",
  "same",
  "sea",
  "seemly",
  "sharp",
  "short",
  "shy",
  "silly",
  "simple",
  "sleek",
  "slimy",
  "slow",
  "small",
  "smart",
  "smug",
  "soft",
  "solid",
  "sound",
  "sour",
  "spare",
  "spicy",
  "spry",
  "stale",
  "steep",
  "still",
  "stock",
  "stout",
  "strong",
  "suave",
  "such",
  "sunny",
  "super",
  "sweet",
  "swift",
  "tame",
  "tangy",
  "tasty",
  "teal",
  "teary",
  "tense",
  "that",
  "these",
  "this",
  "tidy",
  "tiny",
  "tired",
  "top",
  "topical",
  "tough",
  "trick",
  "trite",
  "true",
  "upper",
  "vexed",
  "vivid",
  "wacky",
  "warm",
  "watery",
  "weak",
  "weary",
  "weird",
  "white",
  "whole",
  "wide",
  "wild",
  "wise",
  "witty",
  "yummy",
  "zany",
  "zesty",
  "zippy"
];
var verbs = [
  "absorb",
  "accept",
  "achieve",
  "adapt",
  "adore",
  "advise",
  "affirm",
  "agree",
  "aid",
  "aim",
  "amaze",
  "amuse",
  "animate",
  "approve",
  "arise",
  "arrive",
  "ascend",
  "ask",
  "aspire",
  "assure",
  "attend",
  "bake",
  "bask",
  "beam",
  "believe",
  "belong",
  "bend",
  "blend",
  "bless",
  "blink",
  "bloom",
  "boil",
  "boost",
  "borrow",
  "breathe",
  "bubble",
  "build",
  "bump",
  "burn",
  "buy",
  "buzz",
  "care",
  "catch",
  "charm",
  "cheer",
  "cherish",
  "chop",
  "clap",
  "clasp",
  "climb",
  "clip",
  "coax",
  "comfort",
  "commend",
  "compose",
  "conquer",
  "cook",
  "create",
  "cry",
  "cuddle",
  "cure",
  "cut",
  "dance",
  "dare",
  "dart",
  "dash",
  "dazzle",
  "delight",
  "devour",
  "dial",
  "dig",
  "dine",
  "dream",
  "drip",
  "drop",
  "drum",
  "dust",
  "earn",
  "edit",
  "embrace",
  "emerge",
  "empower",
  "enchant",
  "endure",
  "engage",
  "enjoy",
  "enrich",
  "evoke",
  "exhale",
  "expand",
  "explore",
  "express",
  "fade",
  "fall",
  "favor",
  "fear",
  "feast",
  "feel",
  "fetch",
  "file",
  "find",
  "flip",
  "flop",
  "flow",
  "fold",
  "fond",
  "forgive",
  "foster",
  "fry",
  "fulfill",
  "gasp",
  "gaze",
  "gleam",
  "glow",
  "grace",
  "grasp",
  "greet",
  "grin",
  "grip",
  "grow",
  "gulp",
  "hack",
  "harbor",
  "heal",
  "heart",
  "hike",
  "hint",
  "honor",
  "hope",
  "hug",
  "hunt",
  "hurl",
  "hush",
  "imagine",
  "inspire",
  "intend",
  "jest",
  "jolt",
  "jump",
  "kick",
  "kiss",
  "laugh",
  "launch",
  "lead",
  "leap",
  "learn",
  "lend",
  "lift",
  "link",
  "list",
  "lock",
  "loop",
  "love",
  "mend",
  "mix",
  "mop",
  "nail",
  "nourish",
  "nudge",
  "nurture",
  "offer",
  "pat",
  "pause",
  "pave",
  "peek",
  "peel",
  "persist",
  "pet",
  "pick",
  "pinch",
  "play",
  "pop",
  "pout",
  "praise",
  "pray",
  "pride",
  "promise",
  "propel",
  "prosper",
  "pull",
  "push",
  "quell",
  "quiz",
  "race",
  "radiate",
  "read",
  "reap",
  "relish",
  "renew",
  "reside",
  "rest",
  "revive",
  "ripple",
  "rise",
  "roam",
  "roar",
  "rush",
  "sail",
  "savor",
  "scold",
  "scoop",
  "seek",
  "sew",
  "shine",
  "sing",
  "skip",
  "slide",
  "slurp",
  "smile",
  "snap",
  "snip",
  "soar",
  "spark",
  "spin",
  "splash",
  "sprout",
  "spur",
  "stab",
  "startle",
  "stir",
  "stop",
  "strive",
  "succeed",
  "support",
  "surge",
  "sway",
  "swim",
  "talk",
  "tap",
  "taste",
  "tear",
  "tend",
  "thrive",
  "tickle",
  "transform",
  "treasure",
  "treat",
  "trim",
  "trip",
  "trust",
  "twirl",
  "twist",
  "type",
  "urge",
  "value",
  "vent",
  "view",
  "walk",
  "wave",
  "win",
  "wish",
  "work",
  "yell",
  "zap",
  "zip",
  "zoom"
];

// ../sdk/dist/human-id/human-id.js
function humanId3() {
  return `${adjectives[Math.floor(Math.random() * 256)]}_${adjectives[Math.floor(Math.random() * 256)]}_${animals[Math.floor(Math.random() * 256)]}_${verbs[Math.floor(Math.random() * 256)]}`;
}

// ../sdk/dist/database/jsonbPlugin.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var JsonbPlugin = class {
  #serializeJsonTransformer = new SerializeJsonbTransformer2();
  #database;
  constructor(args) {
    this.#database = args.database;
  }
  /**
   * For an outgoing query like insert or update, the JSON
   * values are transformed into `jsonb` function calls when
   * executed against the database.
   */
  transformQuery(args) {
    if (args.node.kind === "InsertQueryNode" || args.node.kind === "UpdateQueryNode") {
      const result = this.#serializeJsonTransformer.transformNode(args.node);
      return result;
    }
    return args.node;
  }
  /**
   * For incoming query results, the JSON binaries are parsed
   * into JSON objects.
   */
  async transformResult(args) {
    for (const row of args.result.rows) {
      for (const key in row) {
        const value = row[key];
        if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
          try {
            const res = this.#database.exec(`SELECT json(?)`, {
              returnValue: "resultRows",
              bind: [value]
            });
            row[key] = JSON.parse(res[0]);
          } catch {
          }
          continue;
        }
        if (JSON_COLUMNS.has(key) && typeof value === "string") {
          try {
            row[key] = JSON.parse(value);
          } catch {
          }
        }
        if (key === "messages" && Array.isArray(row[key])) {
          row[key] = normalizeMessages(row[key]);
        } else if (key === "variants" && Array.isArray(row[key])) {
          row[key] = normalizeVariants(row[key]);
        }
      }
    }
    return args.result;
  }
};
var JSON_COLUMNS = /* @__PURE__ */ new Set([
  "declarations",
  "selectors",
  "matches",
  "pattern",
  // jsonArrayFrom results in nested bundle queries
  "messages",
  "variants"
]);
function parseJsonIfString(value) {
  if (typeof value !== "string") {
    return value;
  }
  try {
    return JSON.parse(value);
  } catch {
    return value;
  }
}
function normalizeVariants(variants) {
  return variants.map((variant) => {
    if (variant && typeof variant === "object") {
      return {
        ...variant,
        matches: parseJsonIfString(variant.matches),
        pattern: parseJsonIfString(variant.pattern)
      };
    }
    return variant;
  });
}
function normalizeMessages(messages) {
  return messages.map((message) => {
    if (message && typeof message === "object") {
      const rawVariants = Array.isArray(message.variants) ? message.variants : parseJsonIfString(message.variants);
      const normalizedVariants = Array.isArray(rawVariants) ? normalizeVariants(rawVariants) : rawVariants;
      return {
        ...message,
        selectors: parseJsonIfString(message.selectors),
        variants: normalizedVariants
      };
    }
    return message;
  });
}
var SerializeJsonbTransformer2 = class extends OperationNodeTransformer {
  transformOnConflict(node) {
    var _a8;
    return super.transformOnConflict({
      ...node,
      updates: (_a8 = node.updates) == null ? void 0 : _a8.map((updateItem) => {
        if (updateItem.kind !== "ColumnUpdateNode") {
          return updateItem;
        }
        return {
          kind: "ColumnUpdateNode",
          column: updateItem.column,
          // @ts-expect-error - we know that the value is a ValueNode
          value: this.transformValue(updateItem.value)
        };
      })
    });
  }
  transformValue(node) {
    const { value } = node;
    const serializedValue = maybeSerializeJson2(value);
    if (value === serializedValue) {
      return node;
    }
    return sql`jsonb(${serializedValue})`.toOperationNode();
  }
  /**
   * Transforms the value list node by replacing all JSON objects with `jsonb` function calls.
   */
  transformValueList(node) {
    return super.transformValueList({
      ...node,
      values: node.values.map((listNodeItem) => {
        if (listNodeItem.kind !== "ValueNode") {
          return listNodeItem;
        }
        const { value } = listNodeItem;
        const serializedValue = maybeSerializeJson2(value);
        if (value === serializedValue) {
          return listNodeItem;
        }
        return sql`jsonb(${serializedValue})`.toOperationNode();
      })
    });
  }
  /**
   * Why this function is needed or why this works remains a mystery.
   */
  transformValues(node) {
    return super.transformValues({
      ...node,
      values: node.values.map((valueItemNode) => {
        if (valueItemNode.kind !== "PrimitiveValueListNode") {
          return valueItemNode;
        }
        return {
          kind: "ValueListNode",
          values: valueItemNode.values.map((value) => ({
            kind: "ValueNode",
            value
          }))
        };
      })
    });
  }
};
function maybeSerializeJson2(value) {
  if (
    // binary data
    value instanceof ArrayBuffer || // uint8array, etc
    ArrayBuffer.isView(value) || value === null || value === void 0
  ) {
    return value;
  } else if (typeof value === "object" || Array.isArray(value)) {
    return JSON.stringify(value);
  }
  return value;
}

// ../sdk/dist/database/initDb.js
function initDb2(args) {
  initDefaultValueFunctions({ sqlite: args.sqlite });
  applySchema2({ sqlite: args.sqlite });
  const db = new Kysely({
    dialect: createDialect({
      database: args.sqlite
    }),
    plugins: [
      new CamelCasePlugin(),
      new JsonbPlugin({ database: args.sqlite })
    ]
  });
  return db;
}
function initDefaultValueFunctions(args) {
  args.sqlite.createFunction({
    name: "uuid_v7",
    arity: 0,
    xFunc: () => v7_default()
  });
  args.sqlite.createFunction({
    name: "human_id",
    arity: 0,
    xFunc: () => humanId3()
  });
}

// ../sdk/dist/project/newProject.js
async function newProject(args) {
  const sqlite2 = await createInMemoryDatabase({
    readOnly: false
  });
  initDb2({ sqlite: sqlite2 });
  try {
    const inlangDbContent = contentFromDatabase(sqlite2);
    const lix = await openLixInMemory({ blob: await newLixFile() });
    const { value: lixId } = await lix.db.selectFrom("key_value").select("value").where("key", "=", "lix_id").executeTakeFirstOrThrow();
    await lix.db.insertInto("file").values([
      {
        path: "/db.sqlite",
        data: inlangDbContent
      },
      {
        path: "/settings.json",
        data: new TextEncoder().encode(JSON.stringify((args == null ? void 0 : args.settings) ?? defaultProjectSettings, void 0, 2))
      },
      {
        path: "/project_id",
        data: new TextEncoder().encode(lixId)
      }
    ]).execute();
    const blob = toBlob({ lix });
    lix.sqlite.close();
    return blob;
  } catch (e2) {
    const error = new Error(`Failed to create new inlang project: ${e2}`, {
      cause: e2
    });
    throw error;
  } finally {
    sqlite2.close();
  }
}
var defaultProjectSettings = {
  $schema: "https://inlang.com/schema/project-settings",
  baseLocale: "en",
  locales: ["en"],
  modules: [
    // for instant gratification, we're adding common rules
    // "https://cdn.jsdelivr.net/npm/@inlang/message-lint-rule-empty-pattern@latest/dist/index.js",
    // "https://cdn.jsdelivr.net/npm/@inlang/message-lint-rule-missing-translation@latest/dist/index.js",
    // "https://cdn.jsdelivr.net/npm/@inlang/message-lint-rule-without-source@latest/dist/index.js",
    // default to the message format plugin because it supports all features
    // "https://cdn.jsdelivr.net/npm/@inlang/plugin-message-format@latest/dist/index.js",
    // the m function matcher should be installed by default in case Sherlock (VS Code extension) is adopted
    // "https://cdn.jsdelivr.net/npm/@inlang/plugin-m-function-matcher@latest/dist/index.js",
  ]
};

// ../sdk/dist/project/loadProjectInMemory.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../sdk/dist/project/loadProject.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../sdk/dist/plugin/importPlugins.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../sdk/dist/plugin/errors.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var PluginError = class extends Error {
  plugin;
  constructor(message, options) {
    super(message);
    this.name = "PluginError";
    this.plugin = options.plugin;
    this.cause = options.cause;
  }
};
var PluginImportError = class extends PluginError {
  constructor(options) {
    super(`Couldn't import the plugin "${options.plugin}":

${options.cause}`, options);
    this.name = "PluginImportError";
  }
};
var PluginDoesNotImplementFunctionError = class extends PluginError {
  constructor(options) {
    super(`The plugin "${options.plugin}" does not implement the "${options.function}" function.`, options);
    this.name = "PluginDoesNotImplementFunction";
  }
};
var PluginMissingError = class extends PluginError {
  constructor(options) {
    super(`The plugin "${options.plugin}" does not exist`, options);
    this.name = "PluginMissingError";
  }
};

// ../sdk/dist/plugin/cache.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function escape(url) {
  const bytes = new TextEncoder().encode(url);
  const hash = bytes.reduce((hash2, byte) => BigInt.asUintN(64, (hash2 ^ BigInt(byte)) * 1099511628211n), 14695981039346656037n);
  return hash.toString(36);
}
async function readModuleFromCache(moduleURI, lix) {
  const moduleHash = escape(moduleURI);
  const filePath = `/cache/plugins/${moduleHash}`;
  const file = await lix.db.selectFrom("file").where("path", "=", filePath).selectAll().executeTakeFirst();
  if (file) {
    return new TextDecoder().decode(file.data);
  }
  return void 0;
}
async function writeModuleToCache(moduleURI, moduleContent, lix) {
  const moduleHash = escape(moduleURI);
  const filePath = `/cache/plugins/${moduleHash}`;
  await lix.db.insertInto("file").values({
    path: filePath,
    data: new TextEncoder().encode(moduleContent)
  }).onConflict((oc) => oc.doUpdateSet({ data: new TextEncoder().encode(moduleContent) })).execute();
}
function withCache(moduleLoader, lix) {
  return async (uri) => {
    try {
      const moduleAsText = await moduleLoader(uri);
      await writeModuleToCache(uri, moduleAsText, lix);
      return moduleAsText;
    } catch (e2) {
      const cacheResult = await readModuleFromCache(uri, lix);
      if (cacheResult) {
        return cacheResult;
      } else {
        throw e2;
      }
    }
  };
}

// ../sdk/dist/plugin/importPlugins.js
async function importPlugins(args) {
  var _a8;
  const plugins = [];
  const errors = [];
  for (const uri of args.settings.modules ?? []) {
    try {
      let moduleAsText = await withCache(fetchPlugin, args.lix)(uri);
      if (args.preprocessPluginBeforeImport) {
        moduleAsText = await args.preprocessPluginBeforeImport(moduleAsText);
      }
      let moduleAsURL;
      if (process.versions.bun) {
        moduleAsURL = URL.createObjectURL(new Blob([moduleAsText], { type: "text/javascript" }));
      } else {
        moduleAsURL = "data:text/javascript;base64," + btoa(moduleAsText);
      }
      const { default: module } = await import(
        /* @vite-ignore */
        moduleAsURL
      );
      if ((_a8 = module.id) == null ? void 0 : _a8.includes("messageLintRule")) {
        continue;
      }
      plugins.push(module);
    } catch (e2) {
      errors.push(new PluginImportError({ plugin: uri, cause: e2 }));
    }
  }
  return { plugins, errors };
}
async function fetchPlugin(uri) {
  try {
    const response = await fetch(uri);
    return await response.text();
  } catch (error) {
    throw new PluginImportError({
      plugin: uri,
      cause: error
    });
  }
}

// ../sdk/dist/migrations/v2/withLanguageTagToLocaleMigration.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function withLanguageTagToLocaleMigration(settings) {
  if (settings.sourceLanguageTag === void 0) {
    settings.sourceLanguageTag = settings.baseLocale;
  }
  if (settings.languageTags === void 0) {
    settings.languageTags = settings.locales;
  }
  if (settings.baseLocale === void 0) {
    settings.baseLocale = settings.sourceLanguageTag;
  }
  if (settings.locales === void 0) {
    settings.locales = settings.languageTags;
  }
  if (settings.sourceLanguageTag !== settings.baseLocale) {
    settings.sourceLanguageTag = settings.baseLocale;
  }
  if (settings.languageTags !== settings.locales) {
    settings.languageTags = settings.locales;
  }
  return settings;
}

// ../sdk/dist/import-export/importFiles.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
async function importFiles(args) {
  const plugin2 = args.plugins.find((p3) => p3.key === args.pluginKey);
  if (!plugin2)
    throw new PluginMissingError({ plugin: args.pluginKey });
  if (!plugin2.importFiles) {
    throw new PluginDoesNotImplementFunctionError({
      plugin: args.pluginKey,
      function: "importFiles"
    });
  }
  const imported = await plugin2.importFiles({
    files: args.files,
    settings: structuredClone(args.settings)
  });
  await args.db.transaction().execute(async (trx) => {
    for (const bundle of imported.bundles) {
      await trx.insertInto("bundle").values(bundle).onConflict((oc) => oc.column("id").doUpdateSet(bundle)).execute();
    }
    for (const message of imported.messages) {
      if (message.id === void 0) {
        const exisingMessage = await trx.selectFrom("message").where("bundleId", "=", message.bundleId).where("locale", "=", message.locale).select("id").executeTakeFirst();
        message.id = exisingMessage == null ? void 0 : exisingMessage.id;
      }
      try {
        await trx.insertInto("message").values(message).onConflict((oc) => oc.column("id").doUpdateSet(message)).execute();
      } catch (e2) {
        if ((e2 == null ? void 0 : e2.resultCode) === 787) {
          await trx.insertInto("bundle").values({ id: message.bundleId }).execute();
          await trx.insertInto("message").values(message).execute();
        } else {
          throw e2;
        }
      }
    }
    for (const variant of imported.variants) {
      if (variant.id === void 0) {
        let existingMessage = await trx.selectFrom("message").where("bundleId", "=", variant.messageBundleId).where("locale", "=", variant.messageLocale).select("id").executeTakeFirst();
        if (existingMessage === void 0) {
          const existingBundle = await trx.selectFrom("bundle").where("id", "=", variant.messageBundleId).select("id").executeTakeFirst();
          if (existingBundle === void 0) {
            await trx.insertInto("bundle").values({ id: variant.messageBundleId }).execute();
          }
          existingMessage = await trx.insertInto("message").values({
            bundleId: variant.messageBundleId,
            locale: variant.messageLocale
          }).returningAll().executeTakeFirstOrThrow();
        }
        const existingVariants = await trx.selectFrom("variant").where("messageId", "=", existingMessage.id).selectAll().execute();
        const existingVariant = existingVariants.find((v3) => JSON.stringify(v3.matches) === JSON.stringify(variant.matches));
        variant.id = existingVariant == null ? void 0 : existingVariant.id;
        variant.messageId = existingMessage.id;
      }
      const toBeInsertedVariant = {
        ...variant,
        // @ts-expect-error - bundle id is provided by VariantImport but not needed when inserting
        messageBundleId: void 0,
        messageLocale: void 0
      };
      await trx.insertInto("variant").values(toBeInsertedVariant).onConflict((oc) => oc.column("id").doUpdateSet(toBeInsertedVariant)).execute();
    }
  });
}

// ../sdk/dist/import-export/exportFiles.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
async function exportFiles(opts) {
  const plugin2 = opts.plugins.find((p3) => p3.key === opts.pluginKey);
  if (!plugin2)
    throw new PluginMissingError({ plugin: opts.pluginKey });
  if (!plugin2.exportFiles) {
    throw new PluginDoesNotImplementFunctionError({
      plugin: opts.pluginKey,
      function: "exportFiles"
    });
  }
  const bundles = await opts.db.selectFrom("bundle").selectAll().execute();
  const messages = await opts.db.selectFrom("message").selectAll().execute();
  const variants = await opts.db.selectFrom("variant").selectAll().execute();
  const files = await plugin2.exportFiles({
    settings: structuredClone(opts.settings),
    bundles,
    messages,
    variants
  });
  return files;
}

// ../sdk/dist/project/loadProject.js
async function loadProject(args) {
  const db = initDb2({ sqlite: args.sqlite });
  await maybeMigrateFirstProjectId({ lix: args.lix });
  const settingsFile = await args.lix.db.selectFrom("file").select("data").where("path", "=", "/settings.json").executeTakeFirstOrThrow();
  const settings = withLanguageTagToLocaleMigration(JSON.parse(new TextDecoder().decode(settingsFile.data)));
  const importedPlugins = await importPlugins({
    settings,
    lix: args.lix,
    preprocessPluginBeforeImport: args.preprocessPluginBeforeImport
  });
  const plugins = [...args.providePlugins ?? [], ...importedPlugins.plugins];
  return {
    db,
    id: {
      get: async () => {
        const file = await args.lix.db.selectFrom("file").where("path", "=", "/project_id").select("file.data").executeTakeFirstOrThrow();
        return new TextDecoder().decode(file.data);
      }
    },
    settings: {
      get: async () => {
        const file = await args.lix.db.selectFrom("file").where("path", "=", "/settings.json").select("file.data").executeTakeFirstOrThrow();
        return withLanguageTagToLocaleMigration(JSON.parse(new TextDecoder().decode(file.data)));
      },
      set: async (newSettings) => {
        const cloned = JSON.parse(JSON.stringify(newSettings));
        cloned.languageTags = cloned.locales;
        cloned.sourceLanguageTag = cloned.baseLocale;
        await args.lix.db.updateTable("file").where("path", "=", "/settings.json").set({
          data: new TextEncoder().encode(JSON.stringify(cloned, void 0, 2))
        }).execute();
      }
    },
    plugins: {
      get: async () => plugins
    },
    errors: {
      get: async () => [...importedPlugins.errors]
    },
    // errors: state.errors,
    importFiles: async ({ files, pluginKey }) => {
      const settingsFile2 = await args.lix.db.selectFrom("file").where("path", "=", "/settings.json").select("file.data").executeTakeFirstOrThrow();
      const settings2 = JSON.parse(new TextDecoder().decode(settingsFile2.data));
      return await importFiles({
        files,
        pluginKey,
        settings: settings2,
        // TODO don't use global state, might be stale
        plugins,
        db
      });
    },
    exportFiles: async ({ pluginKey }) => {
      const settingsFile2 = await args.lix.db.selectFrom("file").where("path", "=", "/settings.json").select("file.data").executeTakeFirstOrThrow();
      const settings2 = JSON.parse(new TextDecoder().decode(settingsFile2.data));
      return (await exportFiles({
        pluginKey,
        db,
        settings: settings2,
        // TODO don't use global state, might be stale
        plugins
      })).map((output) => ({ ...output, pluginKey }));
    },
    close: async () => {
      await saveDbToLix({ sqlite: args.sqlite, lix: args.lix });
      await db.destroy();
      await args.lix.db.destroy();
    },
    _sqlite: args.sqlite,
    toBlob: async () => {
      await saveDbToLix({ sqlite: args.sqlite, lix: args.lix });
      return await toBlob({ lix: args.lix });
    },
    lix: args.lix
  };
}
async function saveDbToLix(args) {
  const data = contentFromDatabase(args.sqlite);
  await args.lix.db.updateTable("file").set("data", data).where("path", "=", "/db.sqlite").execute();
}
async function maybeMigrateFirstProjectId(args) {
  const firstProjectIdFile = await args.lix.db.selectFrom("file").select("data").where("path", "=", "/project_id").executeTakeFirst();
  if (!firstProjectIdFile) {
    await args.lix.db.insertInto("file").values({
      path: "/project_id",
      data: new TextEncoder().encode(v4_default())
    }).execute();
  }
}

// ../sdk/dist/project/loadProjectInMemory.js
async function loadProjectInMemory(args) {
  const lix = await openLixInMemory({
    blob: args.blob,
    account: args.account,
    keyValues: args.lixKeyValues,
    providePlugins: [
      // inlangLixPluginV1
    ]
  });
  const dbFile = await lix.db.selectFrom("file").select("data").where("path", "=", "/db.sqlite").executeTakeFirstOrThrow();
  const sqlite2 = await createInMemoryDatabase({});
  importDatabase({ db: sqlite2, content: new Uint8Array(dbFile.data) });
  return await loadProject({
    // pass common arguments to loadProject
    ...args,
    sqlite: sqlite2,
    lix
  });
}

// ../sdk/dist/project/loadProjectFromDirectory.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
import nodePath3 from "node:path";

// ../sdk/dist/json-schema/old-v1-message/fromMessageV1.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function fromMessageV1(messageV1) {
  const bundleId = messageV1.id;
  const languages = [
    ...new Set(messageV1.variants.map((variant) => variant.languageTag))
  ];
  const declarations = /* @__PURE__ */ new Set();
  const messages = languages.map((language) => {
    const messageId = bundleId + "_" + language;
    const v1Variants = messageV1.variants.filter((variant) => variant.languageTag === language);
    const selectorNames = /* @__PURE__ */ new Set();
    for (const v1Selector of messageV1.selectors ?? []) {
      selectorNames.add(v1Selector.name);
    }
    const variableNames = new Set(selectorNames);
    const variants = [];
    let variantIndex = 1;
    for (const v1Variant of v1Variants) {
      for (const element of v1Variant.pattern) {
        if (element.type === "VariableReference") {
          variableNames.add(element.name);
        }
      }
      variants.push({
        // matching was not supported. no problem should arise
        matches: [],
        pattern: fromPatternV1(v1Variant.pattern),
        id: messageId + "_" + variantIndex,
        messageId
      });
      variantIndex += 1;
    }
    for (const variable of variableNames) {
      declarations.add({
        type: "input-variable",
        name: variable
      });
    }
    return {
      id: messageId,
      bundleId,
      locale: language,
      selectors: [],
      variants
    };
  });
  return {
    id: bundleId,
    declarations: [...declarations],
    messages
  };
}
function fromPatternV1(pattern) {
  return pattern.map((element) => {
    switch (element.type) {
      case "Text": {
        return {
          type: "text",
          value: element.value
        };
      }
      case "VariableReference":
        return {
          type: "expression",
          arg: {
            type: "variable-reference",
            name: element.name
          }
        };
    }
  });
}

// ../sdk/dist/import-export/upsertBundleNestedMatchByProperties.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var upsertBundleNestedMatchByProperties = async (db, bundle) => {
  if (bundle.id === void 0) {
    throw new Error("upsert expets a bundle id for matching");
  }
  const bundleToInsert = { ...bundle, messages: void 0 };
  await db.transaction().execute(async (trx) => {
    const insertedBundle = await trx.insertInto("bundle").values(bundleToInsert).onConflict((oc) => oc.column("id").doUpdateSet(bundleToInsert)).returning("id").executeTakeFirstOrThrow();
    const existingMessages = await trx.selectFrom("message").where("bundleId", "=", insertedBundle.id).selectAll().execute();
    for (const message of bundle.messages) {
      const existingMessage = existingMessages.find((m2) => m2.locale === message.locale);
      const messageToInsert = {
        ...message,
        id: existingMessage == null ? void 0 : existingMessage.id,
        bundleId: insertedBundle.id,
        variants: void 0
      };
      const insertedMessage = await trx.insertInto("message").values(messageToInsert).onConflict((oc) => oc.column("id").doUpdateSet(messageToInsert)).returning("id").executeTakeFirstOrThrow();
      const existingVariants = await trx.selectFrom("variant").where("messageId", "=", insertedMessage.id).selectAll().execute();
      for (const variant of message.variants) {
        const existingVariant = existingVariants.find((v3) => JSON.stringify(v3.matches) === JSON.stringify(variant.matches));
        const variantToInsert = {
          ...variant,
          id: existingVariant == null ? void 0 : existingVariant.id,
          messageId: insertedMessage.id
        };
        await trx.insertInto("variant").values(variantToInsert).onConflict((oc) => oc.column("id").doUpdateSet(variantToInsert)).execute();
      }
    }
  });
};

// ../sdk/dist/project/path-helpers.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
import nodePath from "node:path";
function withAbsolutePaths(fs3, projectPath) {
  return {
    // @ts-expect-error - node type mismatch
    readFile: (path2, options) => {
      return fs3.readFile(absolutePathFromProject(projectPath, path2), options);
    },
    writeFile: (path2, data) => {
      return fs3.writeFile(absolutePathFromProject(projectPath, path2), data);
    },
    mkdir: (path2) => {
      return fs3.mkdir(absolutePathFromProject(projectPath, path2));
    },
    readdir: (path2) => {
      return fs3.readdir(absolutePathFromProject(projectPath, path2));
    }
  };
}
function absolutePathFromProject(projectPath, filePath) {
  const normalizedProjectPath = nodePath.normalize(projectPath).replace(/\\/g, "/");
  const normalizedFilePath = nodePath.normalize(filePath).replace(/\\/g, "/");
  const projectRoot = nodePath.dirname(normalizedProjectPath);
  if (nodePath.isAbsolute(normalizedFilePath)) {
    return normalizedFilePath;
  }
  const resolvedPath = nodePath.resolve(projectRoot, normalizedFilePath);
  return resolvedPath.replace(/\\/g, "/");
}

// ../sdk/dist/project/saveProjectToDirectory.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
import path from "node:path";

// ../sdk/dist/json-schema/old-v1-message/toMessageV1.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
function toMessageV1(bundle) {
  const variants = [];
  const selectorNames = /* @__PURE__ */ new Set();
  for (const message of bundle.messages) {
    for (const selector of message.selectors.map((s2) => ({
      type: "variable-reference",
      name: s2.name
    }))) {
      selectorNames.add(selector.name);
    }
    for (const variant of message.variants) {
      variants.push({
        languageTag: message.locale,
        match: [],
        pattern: toV1Pattern(variant.pattern)
      });
    }
  }
  const selectors = [...selectorNames].map((name) => ({
    type: "VariableReference",
    name
  }));
  return {
    id: bundle.id,
    alias: {},
    variants,
    selectors
  };
}
function toV1Pattern(pattern) {
  return pattern.map((element) => {
    switch (element.type) {
      case "text": {
        return {
          type: "Text",
          value: element.value
        };
      }
      case "expression": {
        if (element.arg.type === "variable-reference") {
          return {
            type: "VariableReference",
            name: element.arg.name
          };
        }
        throw new Error(`Unsupported expression argument type`);
      }
      case "markup-start":
      case "markup-end":
      case "markup-standalone": {
        throw new Error("Markup placeholders are not supported in MessageV1 conversion");
      }
      default: {
        throw new Error(`Unsupported pattern element type`);
      }
    }
  });
}

// ../sdk/dist/utilities/detectJsonFormatting.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var detectJsonFormatting = (file) => {
  const endsWithNewLine = file.endsWith("\n");
  const spacing = guessJsonIndent(file);
  return (value, replacer) => JSON.stringify(value, replacer, spacing) + (endsWithNewLine ? "\n" : "");
};
var guessJsonIndent = (jsonString) => {
  const firstIndex = skipWhitespaces(jsonString, 0);
  if (firstIndex === void 0 || !isJsonObjectOrArray(jsonString[firstIndex])) {
    return;
  }
  const secondIndex = skipWhitespaces(jsonString, firstIndex + 1);
  if (secondIndex === void 0) {
    return;
  }
  return getIndent(jsonString, firstIndex, secondIndex);
};
var skipWhitespaces = (jsonString, startIndex) => {
  for (let index = startIndex; index < jsonString.length; index += 1) {
    const character = jsonString[index];
    if (!isJsonWhitespace(character)) {
      return index;
    }
  }
  return;
};
var isJsonWhitespace = (character) => character === " " || character === "	" || character === "\n" || character === "\r";
var isJsonObjectOrArray = (character) => character === "{" || character === "[";
var getIndent = (jsonString, firstIndex, secondIndex) => {
  let indent;
  for (let index = secondIndex - 1; index > firstIndex; index -= 1) {
    const character = jsonString[index];
    if (character === "\r") {
      return;
    }
    if (character === "\n") {
      return normalizeIndent(indent);
    }
    if (indent === void 0) {
      indent = character;
    } else if (indent[0] === character) {
      indent += character;
    } else {
      return;
    }
  }
};
var normalizeIndent = (indent) => {
  if (indent === void 0) {
    return 0;
  }
  return indent[0] === " " ? indent.length : indent;
};

// ../sdk/dist/query-utilities/selectBundleNested.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var selectBundleNested = (db) => {
  return db.selectFrom("bundle").select((eb) => [
    // select all columns from bundle
    "id",
    "declarations",
    // select all columns from messages as "messages"
    jsonArrayFrom(eb.selectFrom("message").select((eb2) => [
      // select all columns from message
      "id",
      "bundleId",
      "locale",
      "selectors",
      // select all columns from variants as "variants"
      jsonArrayFrom(eb2.selectFrom("variant").select(["id", "messageId", "matches", "pattern"]).whereRef("variant.messageId", "=", "message.id")).as("variants")
    ]).whereRef("message.bundleId", "=", "bundle.id")).as("messages")
  ]);
};

// ../sdk/dist/project/README_CONTENT.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var README_CONTENT = `
## What is this folder?

This is an [unpacked (git-friendly)](https://inlang.com/docs/unpacked-project) inlang project.

## At a glance

Purpose:
- This folder is the Git-friendly representation of an \`.inlang\` project.
- The canonical \`.inlang\` format is a single binary file; this directory is the unpacked version for Git.
- This folder stores project configuration and plugin cache data.
- Translation files live outside this folder and are referenced from \`settings.json\`.

Safe to edit:
- \`settings.json\`

Do not edit:
- \`cache/\`
- \`.gitignore\`

Key files:
- \`settings.json\` \u2014 locales, plugins, file patterns
- \`cache/\` \u2014 plugin caches (safe to delete)
- \`.gitignore\` \u2014 generated
- \`README.md\` \u2014 generated, explains this folder
- \`.meta.json\` \u2014 generated SDK metadata

\`\`\`
*.inlang/
\u251C\u2500\u2500 settings.json    # Locales, plugins, and file patterns; kept in Git
\u251C\u2500\u2500 .gitignore       # Ignores everything except settings.json
\u251C\u2500\u2500 README.md        # Generated, explains this folder
\u251C\u2500\u2500 .meta.json       # Generated SDK metadata
\u2514\u2500\u2500 cache/           # Plugin caches, usually cache/plugins/
\`\`\`

Translation files (like \`messages/en.json\`) live **outside** this folder and are referenced via plugins in \`settings.json\`.

## What is inlang?

[Inlang](https://inlang.com) is an open project file format for localization. An \`.inlang\` project is canonically a single binary file: a SQLite database with version control via [lix](https://lix.dev). Like \`.sqlite\` for relational data, \`.inlang\` packages localization data into one file that tools can share.

For Git repositories, that binary file can be unpacked into a directory of plain files. The packed file is the canonical format; this directory is the Git-friendly representation.

Use inlang when multiple tools, teams, automations, or agents need to use the same localization data. The \`@inlang/sdk\` is the reference implementation for reading and writing \`.inlang\` projects.

\`.inlang\` is the canonical project format. Plugins import and export external translation files for compatibility with existing runtimes and workflows. Messages, variants, and locale data live in the \`.inlang\` database; translation files such as \`messages/en.json\` live outside this folder and are connected through plugins. Version control via lix adds file-level history, merging, and change proposals to \`.inlang\` projects.

It provides:

- **CRUD API** \u2014 Read and write translations programmatically via SQL
- **Plugin system** \u2014 Import/export external translation files (JSON, XLIFF, etc.)
- **Version control** \u2014 Version control via [lix](https://lix.dev)

Core data model:

- **Bundle** \u2014 one translatable unit across locales
- **Message** \u2014 locale-specific translation for a bundle
- **Variant** \u2014 text pattern plus selector matches

\`\`\`
\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510        \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510         \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
\u2502 i18n lib \u2502        \u2502Translation\u2502         \u2502   CI/CD    \u2502
\u2502          \u2502        \u2502   Tool    \u2502         \u2502 Automation \u2502
\u2514\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2518        \u2514\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2518         \u2514\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2518
     \u2502                    \u2502                     \u2502
     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510          \u2502          \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
               \u25BC          \u25BC          \u25BC
           \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
           \u2502          *.inlang file           \u2502
           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
\`\`\`

## Quick start

\`\`\`bash
npm install @inlang/sdk
\`\`\`

\`\`\`ts
import { loadProjectFromDirectory, saveProjectToDirectory } from "@inlang/sdk";
import fs from "node:fs";

const project = await loadProjectFromDirectory({
  path: "./project.inlang",
  fs,
});
// Query messages with the SDK.
const messages = await project.db.selectFrom("message").selectAll().execute();

// Use project.db to update messages.
await saveProjectToDirectory({
  path: "./project.inlang",
  fs,
  project,
});

await project.close();
\`\`\`

\`loadProjectFromDirectory()\` and \`saveProjectToDirectory()\` both accept \`node:fs\`. \`saveProjectToDirectory()\` writes translation files through import/export plugins. If no exporter plugin is configured, save the canonical packed file with \`project.toBlob()\` instead.

## For coding agents and tool builders

Target \`.inlang\` instead of inventing a custom JSON schema.

Why target \`.inlang\`?

- One file gives every tool the same data model for bundles, messages, variants, locales, metadata, and settings.
- CRUD operations are available through the SDK instead of custom parsing and rewriting.
- Version control via [lix](https://lix.dev) keeps localization changes reviewable and mergeable.
- Plugins handle JSON, ICU, i18next, XLIFF, and other formats for compatibility.

Do not:

- Invent a custom \`locales/en.json\` schema as the project format.
- Create a new localization config when a \`.inlang\` project already exists.
- Edit generated or cached files in this directory.
- Bypass \`@inlang/sdk\` when reading or writing \`.inlang\`.

## Ideas for custom tooling

- Translation health dashboard (missing/empty/stale messages)
- Locale coverage report in CI
- Auto-PR for new keys with placeholders
- Migration tool between file formats via plugins
- Glossary/term consistency checker

## Data model ([docs](https://inlang.com/docs/data-model))

\`\`\`
bundle (a concept, e.g., "welcome_header")
  \u2514\u2500\u2500 message (per locale, e.g., "en", "de")
        \u2514\u2500\u2500 variant (plural forms, gender, etc.)
\`\`\`

- **bundle**: Groups messages by ID (e.g., \`welcome_header\`)
- **message**: A translation for a specific locale
- **variant**: Handles pluralization/selectors (most messages have one variant)

## Common tasks

- List bundles: \`project.db.selectFrom("bundle").selectAll().execute()\`
- List messages for locale: \`project.db.selectFrom("message").where("locale", "=", "en").selectAll().execute()\`
- Find missing translations: compare message counts across locales
- Update a message: \`project.db.updateTable("message").set({ ... }).where("id", "=", "...").execute()\`

## Links

- [SDK documentation](https://inlang.com/docs)
- [inlang.com](https://inlang.com)
- [List of plugins](https://inlang.com/c/plugins)
- [List of tools](https://inlang.com/c/tools)
`;

// ../sdk/dist/services/env-variables/index.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ENV_VARIABLES = {
  PUBLIC_INLANG_SDK_SENTRY_DSN: void 0,
  SDK_VERSION: "2.10.2"
};

// ../sdk/dist/project/meta.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
import nodePath2 from "node:path";
async function readProjectMeta(args) {
  try {
    const raw = await args.fs.readFile(nodePath2.join(args.projectPath, ".meta.json"), "utf8");
    const parsed = JSON.parse(raw);
    return parsed && typeof parsed === "object" ? parsed : void 0;
  } catch {
    return void 0;
  }
}
function pickHighestVersion(versions) {
  let highest;
  for (const version2 of versions) {
    if (!version2 || parseSemver(version2) === null) {
      continue;
    }
    if (!highest) {
      highest = version2;
      continue;
    }
    const comparison = compareSemver(highest, version2);
    if (comparison !== null && comparison < 0) {
      highest = version2;
    }
  }
  return highest;
}
function compareSemver(left, right) {
  const leftParts = parseSemver(left);
  const rightParts = parseSemver(right);
  if (!leftParts || !rightParts) {
    return null;
  }
  const deltaMajor = leftParts.major - rightParts.major;
  if (deltaMajor !== 0)
    return deltaMajor;
  const deltaMinor = leftParts.minor - rightParts.minor;
  if (deltaMinor !== 0)
    return deltaMinor;
  const deltaPatch = leftParts.patch - rightParts.patch;
  if (deltaPatch !== 0)
    return deltaPatch;
  const leftPre = leftParts.prerelease;
  const rightPre = rightParts.prerelease;
  if (!leftPre && !rightPre) {
    return 0;
  }
  if (!leftPre) {
    return 1;
  }
  if (!rightPre) {
    return -1;
  }
  const max = Math.max(leftPre.length, rightPre.length);
  for (let i2 = 0; i2 < max; i2 += 1) {
    const leftId = leftPre[i2];
    const rightId = rightPre[i2];
    if (leftId === void 0) {
      return -1;
    }
    if (rightId === void 0) {
      return 1;
    }
    if (leftId === rightId) {
      continue;
    }
    const leftNum = isNumericIdentifier(leftId);
    const rightNum = isNumericIdentifier(rightId);
    if (leftNum && rightNum) {
      const delta = Number(leftId) - Number(rightId);
      if (delta !== 0)
        return delta;
      continue;
    }
    if (leftNum) {
      return -1;
    }
    if (rightNum) {
      return 1;
    }
    if (leftId < rightId)
      return -1;
    if (leftId > rightId)
      return 1;
  }
  return 0;
}
function parseSemver(version2) {
  if (!version2) {
    return null;
  }
  const [core, prereleaseRaw] = version2.split("-", 2);
  if (!core) {
    return null;
  }
  const parts = core.split(".");
  if (!parts[0]) {
    return null;
  }
  const major = Number(parts[0]);
  const minor = Number(parts[1] ?? "0");
  const patch = Number(parts[2] ?? "0");
  if (Number.isNaN(major) || Number.isNaN(minor) || Number.isNaN(patch)) {
    return null;
  }
  const prerelease = parsePrerelease(prereleaseRaw);
  if (prerelease === null && prereleaseRaw !== void 0) {
    return null;
  }
  return { major, minor, patch, prerelease };
}
function parsePrerelease(raw) {
  if (raw === void 0) {
    return null;
  }
  if (raw.length === 0) {
    return null;
  }
  const parts = raw.split(".");
  if (parts.some((part) => part.length === 0)) {
    return null;
  }
  return parts;
}
function isNumericIdentifier(value) {
  return /^[0-9]+$/.test(value);
}

// ../sdk/dist/project/saveProjectToDirectory.js
async function fileExists(fsModule, filePath) {
  try {
    await fsModule.stat(filePath);
    return true;
  } catch {
    return false;
  }
}
function getPromisesFs(fsModule) {
  return "promises" in fsModule ? fsModule.promises : fsModule;
}
async function assertTranslationDataCanBeExported(project) {
  const plugins = await project.plugins.get();
  const hasExporter = plugins.some((plugin2) => plugin2.exportFiles || plugin2.saveMessages);
  if (hasExporter) {
    return;
  }
  const [bundle, message, variant] = await Promise.all([
    project.db.selectFrom("bundle").select("id").limit(1).executeTakeFirst(),
    project.db.selectFrom("message").select("id").limit(1).executeTakeFirst(),
    project.db.selectFrom("variant").select("id").limit(1).executeTakeFirst()
  ]);
  if (bundle || message || variant) {
    throw new Error("saveProjectToDirectory cannot write bundles, messages, or variants without an import/export plugin. Add a plugin to settings.modules/providePlugins, or save the canonical .inlang file with project.toBlob().");
  }
}
async function saveProjectToDirectory(args) {
  var _a8, _b5, _c;
  if (args.path.endsWith(".inlang") === false) {
    throw new Error("The path must end with .inlang");
  }
  if (!args.skipExporting) {
    await assertTranslationDataCanBeExported(args.project);
  }
  const fsModule = getPromisesFs(args.fs);
  const files = await args.project.lix.db.selectFrom("file").selectAll().execute();
  const gitignoreContent = new TextEncoder().encode(`# IF GIT SHOWED THAT THIS FILE CHANGED
#
# 1. RUN THE FOLLOWING COMMAND
#
# ---
# git rm --cached '**/*.inlang/.gitignore'
# ---
#
# 2. COMMIT THE CHANGE
#
# ---
# git commit -m "fix: remove tracked .gitignore from inlang project"
# ---
#
# Inlang handles the gitignore itself starting with version ^2.5.
#
# everything is ignored except settings.json
*
!settings.json`);
  const existingMeta = await readProjectMeta({
    fs: fsModule,
    projectPath: args.path
  });
  const highestSdkVersion = pickHighestVersion([
    existingMeta == null ? void 0 : existingMeta.highestSdkVersion,
    ENV_VARIABLES.SDK_VERSION
  ]) ?? ENV_VARIABLES.SDK_VERSION;
  const shouldWriteMetadata = (() => {
    const comparison = compareSemver(highestSdkVersion, ENV_VARIABLES.SDK_VERSION);
    return comparison === null || comparison <= 0;
  })();
  const readmePath = path.join(args.path, "README.md");
  const gitignorePath = path.join(args.path, ".gitignore");
  const shouldWriteReadme = shouldWriteMetadata || !await fileExists(fsModule, readmePath);
  const shouldWriteGitignore = shouldWriteMetadata || !await fileExists(fsModule, gitignorePath);
  for (const file of files) {
    if (file.path.endsWith("db.sqlite") || file.path === "/project_id") {
      continue;
    }
    const p3 = path.join(args.path, file.path);
    await fsModule.mkdir(path.dirname(p3), { recursive: true });
    await fsModule.writeFile(p3, new Uint8Array(file.data));
  }
  if (shouldWriteGitignore) {
    await fsModule.writeFile(gitignorePath, gitignoreContent);
  }
  if (shouldWriteReadme) {
    await fsModule.writeFile(readmePath, new TextEncoder().encode(README_CONTENT));
  }
  if (shouldWriteMetadata) {
    const metaContent = JSON.stringify({ highestSdkVersion }, null, 2);
    await fsModule.writeFile(path.join(args.path, ".meta.json"), new TextEncoder().encode(metaContent));
  }
  if (args.skipExporting) {
    return;
  }
  const plugins = await args.project.plugins.get();
  const settings = await args.project.settings.get();
  for (const plugin2 of plugins) {
    if (plugin2.exportFiles) {
      const bundles = await args.project.db.selectFrom("bundle").selectAll().execute();
      const messages = await args.project.db.selectFrom("message").selectAll().execute();
      const variants = await args.project.db.selectFrom("variant").selectAll().execute();
      const files2 = await plugin2.exportFiles({
        bundles,
        messages,
        variants,
        settings
      });
      for (const file of files2) {
        const pathPattern = (_a8 = settings[plugin2.key]) == null ? void 0 : _a8.pathPattern;
        const resolvePattern = (pattern) => absolutePathFromProject(args.path, pattern.replace(/\{(languageTag|locale)\}/g, file.locale));
        let targetPaths;
        if (typeof ((_b5 = file.metadata) == null ? void 0 : _b5["pathPattern"]) === "string") {
          targetPaths = [resolvePattern(file.metadata["pathPattern"])];
        } else if (typeof pathPattern === "string") {
          targetPaths = [resolvePattern(pathPattern)];
        } else if (Array.isArray(pathPattern)) {
          targetPaths = pathPattern.map(resolvePattern);
        } else if (typeof pathPattern === "object" && pathPattern !== null) {
          const namespace = (_c = file.metadata) == null ? void 0 : _c["namespace"];
          const namespacePattern = namespace ? pathPattern[namespace] : void 0;
          targetPaths = typeof namespacePattern === "string" ? [resolvePattern(namespacePattern)] : [absolutePathFromProject(args.path, file.name)];
        } else {
          targetPaths = [absolutePathFromProject(args.path, file.name)];
        }
        for (const p3 of targetPaths) {
          await fsModule.mkdir(path.dirname(p3), { recursive: true });
          if (p3.endsWith(".json")) {
            try {
              const existing = await fsModule.readFile(p3, "utf-8");
              const stringify = detectJsonFormatting(existing);
              await fsModule.writeFile(p3, new TextEncoder().encode(stringify(JSON.parse(new TextDecoder().decode(file.content)))));
            } catch {
              await fsModule.writeFile(p3, new Uint8Array(file.content));
            }
          } else {
            await fsModule.writeFile(p3, new Uint8Array(file.content));
          }
        }
      }
    } else if (plugin2.saveMessages) {
      const bundlesNested = await selectBundleNested(args.project.db).execute();
      await plugin2.saveMessages({
        messages: bundlesNested.map((b) => toMessageV1(b)),
        // @ts-expect-error - legacy
        nodeishFs: withAbsolutePaths(fsModule, args.path),
        settings
      });
    }
  }
}

// ../sdk/dist/project/loadProjectFromDirectory.js
async function loadProjectFromDirectory(args) {
  const settingsPath = nodePath3.join(args.path, "settings.json");
  const settings = JSON.parse(await args.fs.promises.readFile(settingsPath, "utf8"));
  let inlangId = void 0;
  try {
    inlangId = await args.fs.promises.readFile(nodePath3.join(args.path, "project_id"), "utf8");
  } catch {
  }
  const localImport = await importLocalPlugins({
    fs: args.fs,
    settings,
    path: args.path
  });
  const providePluginsWithLocalPlugins = [
    ...args.providePlugins ?? [],
    ...localImport.locallyImportedPlugins
  ];
  const newLix = await newProject({
    settings
  });
  const tempLix = await openLixInMemory({ blob: newLix });
  await syncLixFsFiles({
    fs: args.fs,
    path: args.path,
    lix: tempLix,
    syncInterval: void 0
  });
  const project = await loadProjectInMemory({
    ...args,
    providePlugins: providePluginsWithLocalPlugins,
    lixKeyValues: inlangId ? (
      // reversing the id to have distinguishable lix ids from inlang ids
      [{ key: "lix_id", value: inlangId }]
    ) : void 0,
    blob: await toBlob({ lix: tempLix })
  });
  await closeLix({ lix: tempLix });
  await syncLixFsFiles({
    fs: args.fs,
    path: args.path,
    lix: project.lix,
    syncInterval: args.syncInterval
  });
  const allPlugins = await project.plugins.get();
  const { loadSavePlugins, importExportPlugins } = categorizePlugins(allPlugins);
  if (loadSavePlugins.length > 1) {
    throw new Error("Max one loadMessages (found: " + loadSavePlugins.length + ") and one saveMessages plugins (found: " + loadSavePlugins.length + ") are allowed ");
  }
  const importedResourceFileErrors = [];
  for (const plugin2 of importExportPlugins) {
    const files = [];
    if (plugin2.toBeImportedFiles) {
      const toBeImportedFiles = await plugin2.toBeImportedFiles({
        settings: await project.settings.get()
      });
      for (const toBeImported of toBeImportedFiles) {
        const absolute = absolutePathFromProject(args.path, toBeImported.path);
        try {
          const data = await args.fs.promises.readFile(absolute);
          files.push({
            locale: toBeImported.locale,
            content: data,
            toBeImportedFilesMetadata: toBeImported.metadata
          });
        } catch (e2) {
          if ((e2 == null ? void 0 : e2.code) === "ENOENT") {
            continue;
          }
          importedResourceFileErrors.push(new ResourceFileImportError({
            cause: e2,
            path: toBeImported.path
          }));
        }
      }
    }
    await project.importFiles({
      pluginKey: plugin2.key,
      files
    });
  }
  for (const plugin2 of loadSavePlugins) {
    await loadLegacyMessages({
      project,
      pluginKey: plugin2.key ?? plugin2.id,
      loadMessagesFn: plugin2.loadMessages,
      projectPath: args.path,
      fs: args.fs
    });
  }
  const shouldUpdateMeta = await shouldUpdateProjectMeta({
    fs: args.fs.promises,
    projectPath: args.path,
    currentSdkVersion: ENV_VARIABLES.SDK_VERSION
  });
  if (shouldUpdateMeta) {
    await saveProjectToDirectory({
      fs: args.fs.promises,
      project,
      path: args.path,
      skipExporting: true
    });
  }
  return {
    ...project,
    errors: {
      get: async () => {
        return [
          ...filterLocalPluginImportErrors(await project.errors.get()),
          ...localImport.errors,
          ...importedResourceFileErrors
        ];
      }
      // subscribe: (
      // 	callback: Parameters<InlangProject["errors"]["subscribe"]>[0]
      // ) => {
      // 	return project.errors.subscribe((value) => {
      // 		callback([
      // 			...withLocallyImportedPluginWarning(value),
      // 			...localImport.errors,
      // 			...importedResourceFileErrors,
      // 		]);
      // 	});
      // },
    }
  };
}
async function loadLegacyMessages(args) {
  const loadedLegacyMessages = await args.loadMessagesFn({
    settings: await args.project.settings.get(),
    // @ts-expect-error - type mismatch
    nodeishFs: withAbsolutePaths(args.fs.promises, args.projectPath)
  });
  const upsertQueries = [];
  for (const legacyMessage of loadedLegacyMessages) {
    const messageBundle = fromMessageV1(legacyMessage);
    upsertQueries.push(upsertBundleNestedMatchByProperties(args.project.db, messageBundle));
  }
  return await Promise.all(upsertQueries);
}
function arrayBuffersEqual(a3, b) {
  if (a3.byteLength !== b.byteLength)
    return false;
  const view1 = new Uint8Array(a3);
  const view2 = new Uint8Array(b);
  for (const [i2, element] of view1.entries()) {
    if (element !== view2[i2]) {
      return false;
    }
  }
  return true;
}
function filterLocalPluginImportErrors(errors) {
  return errors.filter((error) => {
    if (error instanceof PluginImportError && error.plugin.startsWith("http") === false) {
      return false;
    }
    return true;
  });
}
async function syncLixFsFiles(args) {
  function shouldSyncPath(filePath) {
    return filePath !== "/project_id" && !filePath.endsWith("/project_id");
  }
  async function checkFsStateRecursive(dirPath, currentState) {
    const entries = args.fs.readdirSync(dirPath, { withFileTypes: true });
    for (const entry of entries) {
      const fullPath = nodePath3.join(dirPath, entry.name);
      if (entry.isDirectory()) {
        checkFsStateRecursive(fullPath, currentState);
      } else {
        const data = args.fs.readFileSync(fullPath);
        const relativePath = "/" + nodePath3.relative(args.path, fullPath).split(nodePath3.win32.sep).join(nodePath3.posix.sep);
        if (!shouldSyncPath(relativePath)) {
          continue;
        }
        if (!currentState[relativePath]) {
          currentState[relativePath] = {
            content: data,
            state: "unknown"
          };
        } else {
          if (arrayBuffersEqual(currentState[relativePath].content, data)) {
            currentState[relativePath].state = "known";
          } else {
            currentState[relativePath].state = "updated";
            currentState[relativePath].content = data;
          }
        }
      }
    }
  }
  async function checkLixState(currentLixState) {
    const filesInLix = await args.lix.db.selectFrom("file").where("path", "not like", "%db.sqlite").selectAll().execute();
    for (const fileInLix of filesInLix) {
      if (!shouldSyncPath(fileInLix.path)) {
        continue;
      }
      const currentStateOfFileInLix = currentLixState[fileInLix.path];
      if (!currentStateOfFileInLix) {
        currentLixState[fileInLix.path] = {
          content: new Uint8Array(fileInLix.data).buffer,
          state: "unknown"
        };
      } else {
        if (arrayBuffersEqual(currentStateOfFileInLix.content, fileInLix.data.buffer)) {
          currentStateOfFileInLix.state = "known";
        } else {
          currentStateOfFileInLix.state = "updated";
          currentStateOfFileInLix.content = fileInLix.data.buffer;
        }
      }
    }
  }
  async function syncUpFsAndLixFiles(statesToSync) {
    for (const [path2, fsState] of Object.entries(statesToSync.fsFileStates)) {
      if (!statesToSync.lixFileStates[path2]) {
        if (fsState.state === "unknown") {
          await upsertFileInLix(args, path2, fsState.content);
          statesToSync.lixFileStates[path2] = {
            state: "known",
            content: fsState.content
          };
          fsState.state = "known";
        } else {
          throw new Error("Illeagal lix<->fs sync state. The file [" + path2 + "] that was " + fsState.state + " on disc did not exit in lix");
        }
      } else {
        const lixState = statesToSync.lixFileStates[path2];
        if (fsState.state === "unknown") {
          if (lixState.state === "unknown") {
            if (arrayBuffersEqual(lixState.content, fsState.content)) {
              lixState.state = "known";
              fsState.state = "known";
            } else {
              await upsertFileInLix(args, path2, fsState.content);
              lixState.content = fsState.content;
              lixState.state = "known";
              fsState.state = "known";
            }
          } else {
            throw new Error("Illeagal lix<->fs sync state. The file [" + path2 + "] that was " + fsState.state + " but did exist in lix already");
          }
        } else if (fsState.state === "known") {
          if (lixState.state === "known") {
          } else if (lixState.state === "updated") {
            args.fs.writeFileSync(
              // TODO check platform dependent folder separator
              args.path + path2,
              Buffer.from(lixState.content)
            );
            fsState.content = lixState.content;
            fsState.state = "known";
            lixState.state = "known";
          } else if (lixState.state === "gone") {
            args.fs.unlinkSync(args.path + path2);
            fsState.state = "gone";
            lixState.state = "gone";
          }
        } else if (fsState.state === "updated") {
          if (lixState.state === "unknown") {
            throw new Error("Illeagal lix<->fs sync state. The file [" + path2 + "] that was " + fsState.state + " but it was not known by lix yet?");
          } else if (lixState.state === "known") {
            await upsertFileInLix(args, path2, fsState.content);
            lixState.content = fsState.content;
            fsState.state = "known";
          } else if (lixState.state === "updated") {
            await upsertFileInLix(args, path2, fsState.content);
            lixState.content = fsState.content;
            lixState.state = "known";
            fsState.state = "known";
          } else if (lixState.state === "gone") {
            lixState.content = fsState.content;
            lixState.state = "known";
            fsState.state = "known";
          }
        } else if (fsState.state === "gone") {
          if (lixState.state === "unknown") {
            throw new Error("Illeagal lix<->fs sync state. The file [" + path2 + "] that was " + fsState.state + " but it was not known by lix yet?");
          } else if (lixState.state === "known") {
            await args.lix.db.deleteFrom("file").where("path", "=", path2).execute();
            lixState.state = "gone";
          } else if (lixState.state === "updated") {
            await args.lix.db.deleteFrom("file").where("path", "=", path2).execute();
            lixState.state = "gone";
            fsState.state = "gone";
          } else if (lixState.state === "gone") {
            lixState.state = "gone";
            fsState.state = "gone";
          }
        }
      }
    }
    for (const [path2, lixState] of Object.entries(statesToSync.lixFileStates)) {
      if (!statesToSync.fsFileStates[path2]) {
        if (lixState.state == "unknown") {
          try {
            args.fs.mkdirSync(nodePath3.dirname(nodePath3.join(args.path, path2)), {
              recursive: true
            });
          } catch (e2) {
            if ((e2 == null ? void 0 : e2.code) !== "EEXIST") {
              throw e2;
            }
          }
          args.fs.writeFileSync(nodePath3.join(args.path, path2), Buffer.from(lixState.content));
          statesToSync.fsFileStates[path2] = {
            state: "known",
            content: lixState.content
          };
        } else {
          throw new Error("Illeagal lix<->fs sync state. The file [" + path2 + "] that was in the state" + lixState.state + " for lix did not exist on disk");
        }
      } else {
        if (lixState.state === "gone" && statesToSync.fsFileStates[path2].state === "gone") {
          delete statesToSync.lixFileStates[path2];
          delete statesToSync.fsFileStates[path2];
        } else if (lixState.state !== statesToSync.fsFileStates[path2].state) {
          throw new Error("At this stage both states should be in sync lix state " + lixState.state + " fs state " + statesToSync.fsFileStates[path2].state);
        }
      }
    }
  }
  async function syncFiles(dirPath, fileStates, interval) {
    for (const fsState of Object.values(fileStates.fsFileStates)) {
      fsState.state = "gone";
    }
    for (const lixState of Object.values(fileStates.lixFileStates)) {
      lixState.state = "gone";
    }
    await checkFsStateRecursive(dirPath, fileStates.fsFileStates);
    await checkLixState(fileStates.lixFileStates);
    await syncUpFsAndLixFiles(fileStates);
    if (interval) {
      setTimeout(() => {
        syncFiles(dirPath, fileStates, interval);
      }, interval);
    }
    return;
  }
  await syncFiles(args.path, { fsFileStates: {}, lixFileStates: {} }, args.syncInterval);
  return;
}
async function upsertFileInLix(args, path2, data) {
  let posixPath = path2.split(nodePath3.win32.sep).join(nodePath3.posix.sep);
  if (posixPath.startsWith("/") === false) {
    posixPath = "/" + posixPath;
  }
  await args.lix.db.insertInto("file").values({
    path: posixPath,
    data: new Uint8Array(data)
  }).onConflict((oc) => oc.column("path").doUpdateSet({ data: new Uint8Array(data) })).execute();
}
function categorizePlugins(plugins) {
  const loadSavePlugins = [];
  const importExportPlugins = [];
  for (const plugin2 of plugins) {
    if (plugin2.loadMessages && plugin2.saveMessages && !(plugin2.importFiles && plugin2.exportFiles)) {
      loadSavePlugins.push(plugin2);
    } else if (plugin2.importFiles || plugin2.exportFiles) {
      importExportPlugins.push(plugin2);
    }
  }
  return { loadSavePlugins, importExportPlugins };
}
async function importLocalPlugins(args) {
  const errors = [];
  const locallyImportedPlugins = [];
  for (const module of args.settings.modules ?? []) {
    if (module.startsWith("http")) {
      continue;
    }
    const modulePath = absolutePathFromProject(args.path, module);
    try {
      let moduleAsText = await args.fs.promises.readFile(modulePath, "utf8");
      if (moduleAsText.includes("messageLintRule")) {
        errors.push(new WarningDeprecatedLintRule(module));
        continue;
      }
      if (args.preprocessPluginBeforeImport) {
        moduleAsText = await args.preprocessPluginBeforeImport(moduleAsText);
      }
      const pluginAsUrl = process.versions.bun ? URL.createObjectURL(new Blob([moduleAsText], { type: "text/javascript" })) : "data:application/javascript," + encodeURIComponent(moduleAsText);
      const { default: plugin2 } = await import(
        /* @vite-ignore */
        pluginAsUrl
      );
      locallyImportedPlugins.push(plugin2);
      if (process.versions.bun)
        URL.revokeObjectURL(pluginAsUrl);
    } catch (e2) {
      errors.push(new PluginImportError({ plugin: module, cause: e2 }));
      continue;
    }
  }
  return {
    errors,
    locallyImportedPlugins
  };
}
var WarningDeprecatedLintRule = class extends Error {
  constructor(module) {
    super(`The lint rule ${module} is deprecated. Please remove the lint rule from the settings. Lint rules are interim built into apps and will be succeeded by more generilizable lix validation rules.`);
    this.name = "WarningDeprecatedLintRule";
  }
};
async function shouldUpdateProjectMeta(args) {
  const readmePath = nodePath3.join(args.projectPath, "README.md");
  const gitignorePath = nodePath3.join(args.projectPath, ".gitignore");
  const shouldRepairGeneratedFiles = !await fileExists2(args.fs, readmePath) || !await fileExists2(args.fs, gitignorePath);
  if (shouldRepairGeneratedFiles) {
    return true;
  }
  const meta = await readProjectMeta({
    fs: args.fs,
    projectPath: args.projectPath
  });
  const storedSdkVersion = pickHighestVersion([meta == null ? void 0 : meta.highestSdkVersion]);
  if (!storedSdkVersion) {
    return true;
  }
  const comparison = compareSemver(storedSdkVersion, args.currentSdkVersion);
  if (comparison === null) {
    return true;
  }
  return comparison < 0;
}
async function fileExists2(fsModule, filePath) {
  try {
    await fsModule.stat(filePath);
    return true;
  } catch {
    return false;
  }
}
var ResourceFileImportError = class extends Error {
  path;
  constructor(args) {
    super("Could not import a resource file");
    this.name = "ResourceFileImportError";
    this.cause = args.cause;
    this.path = args.path;
  }
};

// ../sdk/dist/query-utilities/index.js
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../sdk/dist/query-utilities/upsertBundleNested.js
init_define_ENV_DEFINED_IN_BUILD_STEP();
var upsertBundleNested = async (db, bundle) => {
  await db.transaction().execute(async (trx) => {
    const insertedBundle = await trx.insertInto("bundle").values({
      id: bundle.id,
      declarations: bundle.declarations
    }).returning("id").onConflict((oc) => oc.column("id").doUpdateSet({
      ...bundle,
      // @ts-expect-error - undefined
      messages: void 0
    })).executeTakeFirstOrThrow();
    for (const message of bundle.messages) {
      const insertedMessage = await trx.insertInto("message").values({
        id: message.id,
        bundleId: insertedBundle.id,
        locale: message.locale,
        selectors: message.selectors
      }).onConflict((oc) => oc.column("id").doUpdateSet({
        ...message,
        // @ts-expect-error - undefined
        variants: void 0
      })).returning("id").executeTakeFirstOrThrow();
      for (const variant of message.variants) {
        await trx.insertInto("variant").values({
          id: variant.id,
          messageId: insertedMessage.id,
          matches: variant.matches,
          pattern: variant.pattern
        }).onConflict((oc) => oc.column("id").doUpdateSet(variant)).execute();
      }
    }
  });
};

// src/utilities/getInlangProject.ts
import { resolve } from "node:path";
var lastUsedProject;
async function getInlangProject(args) {
  try {
    const baseDirectory = process.cwd();
    const projectPath = resolve(baseDirectory, args.projectPath);
    const project = await loadProjectFromDirectory({
      path: projectPath,
      fs
    });
    lastUsedProject = project;
    return project;
  } catch (err) {
    console.error(`Error opening inlang project at ${args.projectPath}`, err);
    process.exit(1);
  }
}

// src/utilities/log.ts
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/consola@3.4.0/node_modules/consola/dist/index.mjs
init_define_ENV_DEFINED_IN_BUILD_STEP();

// ../../node_modules/.pnpm/consola@3.4.0/node_modules/consola/dist/core.mjs
init_define_ENV_DEFINED_IN_BUILD_STEP();
var LogLevels = {
  silent: Number.NEGATIVE_INFINITY,
  fatal: 0,
  error: 0,
  warn: 1,
  log: 2,
  info: 3,
  success: 3,
  fail: 3,
  ready: 3,
  start: 3,
  box: 3,
  debug: 4,
  trace: 5,
  verbose: Number.POSITIVE_INFINITY
};
var LogTypes = {
  // Silent
  silent: {
    level: -1
  },
  // Level 0
  fatal: {
    level: LogLevels.fatal
  },
  error: {
    level: LogLevels.error
  },
  // Level 1
  warn: {
    level: LogLevels.warn
  },
  // Level 2
  log: {
    level: LogLevels.log
  },
  // Level 3
  info: {
    level: LogLevels.info
  },
  success: {
    level: LogLevels.success
  },
  fail: {
    level: LogLevels.fail
  },
  ready: {
    level: LogLevels.info
  },
  start: {
    level: LogLevels.info
  },
  box: {
    level: LogLevels.info
  },
  // Level 4
  debug: {
    level: LogLevels.debug
  },
  // Level 5
  trace: {
    level: LogLevels.trace
  },
  // Verbose
  verbose: {
    level: LogLevels.verbose
  }
};
function isPlainObject$1(value) {
  if (value === null || typeof value !== "object") {
    return false;
  }
  const prototype = Object.getPrototypeOf(value);
  if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {
    return false;
  }
  if (Symbol.iterator in value) {
    return false;
  }
  if (Symbol.toStringTag in value) {
    return Object.prototype.toString.call(value) === "[object Module]";
  }
  return true;
}
function _defu(baseObject, defaults, namespace = ".", merger) {
  if (!isPlainObject$1(defaults)) {
    return _defu(baseObject, {}, namespace, merger);
  }
  const object = Object.assign({}, defaults);
  for (const key in baseObject) {
    if (key === "__proto__" || key === "constructor") {
      continue;
    }
    const value = baseObject[key];
    if (value === null || value === void 0) {
      continue;
    }
    if (merger && merger(object, key, value, namespace)) {
      continue;
    }
    if (Array.isArray(value) && Array.isArray(object[key])) {
      object[key] = [...value, ...object[key]];
    } else if (isPlainObject$1(value) && isPlainObject$1(object[key])) {
      object[key] = _defu(
        value,
        object[key],
        (namespace ? `${namespace}.` : "") + key.toString(),
        merger
      );
    } else {
      object[key] = value;
    }
  }
  return object;
}
function createDefu(merger) {
  return (...arguments_) => (
    // eslint-disable-next-line unicorn/no-array-reduce
    arguments_.reduce((p3, c3) => _defu(p3, c3, "", merger), {})
  );
}
var defu = createDefu();
function isPlainObject2(obj) {
  return Object.prototype.toString.call(obj) === "[object Object]";
}
function isLogObj(arg) {
  if (!isPlainObject2(arg)) {
    return false;
  }
  if (!arg.message && !arg.args) {
    return false;
  }
  if (arg.stack) {
    return false;
  }
  return true;
}
var paused = false;
var queue = [];
var Consola = class _Consola {
  options;
  _lastLog;
  _mockFn;
  /**
   * Creates an instance of Consola with specified options or defaults.
   *
   * @param {Partial<ConsolaOptions>} [options={}] - Configuration options for the Consola instance.
   */
  constructor(options = {}) {
    const types = options.types || LogTypes;
    this.options = defu(
      {
        ...options,
        defaults: { ...options.defaults },
        level: _normalizeLogLevel(options.level, types),
        reporters: [...options.reporters || []]
      },
      {
        types: LogTypes,
        throttle: 1e3,
        throttleMin: 5,
        formatOptions: {
          date: true,
          colors: false,
          compact: true
        }
      }
    );
    for (const type in types) {
      const defaults = {
        type,
        ...this.options.defaults,
        ...types[type]
      };
      this[type] = this._wrapLogFn(defaults);
      this[type].raw = this._wrapLogFn(
        defaults,
        true
      );
    }
    if (this.options.mockFn) {
      this.mockTypes();
    }
    this._lastLog = {};
  }
  /**
   * Gets the current log level of the Consola instance.
   *
   * @returns {number} The current log level.
   */
  get level() {
    return this.options.level;
  }
  /**
   * Sets the minimum log level that will be output by the instance.
   *
   * @param {number} level - The new log level to set.
   */
  set level(level) {
    this.options.level = _normalizeLogLevel(
      level,
      this.options.types,
      this.options.level
    );
  }
  /**
   * Displays a prompt to the user and returns the response.
   * Throw an error if `prompt` is not supported by the current configuration.
   *
   * @template T
   * @param {string} message - The message to display in the prompt.
   * @param {T} [opts] - Optional options for the prompt. See {@link PromptOptions}.
   * @returns {promise<T>} A promise that infer with the prompt options. See {@link PromptOptions}.
   */
  prompt(message, opts) {
    if (!this.options.prompt) {
      throw new Error("prompt is not supported!");
    }
    return this.options.prompt(message, opts);
  }
  /**
   * Creates a new instance of Consola, inheriting options from the current instance, with possible overrides.
   *
   * @param {Partial<ConsolaOptions>} options - Optional overrides for the new instance. See {@link ConsolaOptions}.
   * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
   */
  create(options) {
    const instance = new _Consola({
      ...this.options,
      ...options
    });
    if (this._mockFn) {
      instance.mockTypes(this._mockFn);
    }
    return instance;
  }
  /**
   * Creates a new Consola instance with the specified default log object properties.
   *
   * @param {InputLogObject} defaults - Default properties to include in any log from the new instance. See {@link InputLogObject}.
   * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
   */
  withDefaults(defaults) {
    return this.create({
      ...this.options,
      defaults: {
        ...this.options.defaults,
        ...defaults
      }
    });
  }
  /**
   * Creates a new Consola instance with a specified tag, which will be included in every log.
   *
   * @param {string} tag - The tag to include in each log of the new instance.
   * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
   */
  withTag(tag) {
    return this.withDefaults({
      tag: this.options.defaults.tag ? this.options.defaults.tag + ":" + tag : tag
    });
  }
  /**
   * Adds a custom reporter to the Consola instance.
   * Reporters will be called for each log message, depending on their implementation and log level.
   *
   * @param {ConsolaReporter} reporter - The reporter to add. See {@link ConsolaReporter}.
   * @returns {Consola} The current Consola instance.
   */
  addReporter(reporter) {
    this.options.reporters.push(reporter);
    return this;
  }
  /**
   * Removes a custom reporter from the Consola instance.
   * If no reporter is specified, all reporters will be removed.
   *
   * @param {ConsolaReporter} reporter - The reporter to remove. See {@link ConsolaReporter}.
   * @returns {Consola} The current Consola instance.
   */
  removeReporter(reporter) {
    if (reporter) {
      const i2 = this.options.reporters.indexOf(reporter);
      if (i2 !== -1) {
        return this.options.reporters.splice(i2, 1);
      }
    } else {
      this.options.reporters.splice(0);
    }
    return this;
  }
  /**
   * Replaces all reporters of the Consola instance with the specified array of reporters.
   *
   * @param {ConsolaReporter[]} reporters - The new reporters to set. See {@link ConsolaReporter}.
   * @returns {Consola} The current Consola instance.
   */
  setReporters(reporters) {
    this.options.reporters = Array.isArray(reporters) ? reporters : [reporters];
    return this;
  }
  wrapAll() {
    this.wrapConsole();
    this.wrapStd();
  }
  restoreAll() {
    this.restoreConsole();
    this.restoreStd();
  }
  /**
   * Overrides console methods with Consola logging methods for consistent logging.
   */
  wrapConsole() {
    for (const type in this.options.types) {
      if (!console["__" + type]) {
        console["__" + type] = console[type];
      }
      console[type] = this[type].raw;
    }
  }
  /**
   * Restores the original console methods, removing Consola overrides.
   */
  restoreConsole() {
    for (const type in this.options.types) {
      if (console["__" + type]) {
        console[type] = console["__" + type];
        delete console["__" + type];
      }
    }
  }
  /**
   * Overrides standard output and error streams to redirect them through Consola.
   */
  wrapStd() {
    this._wrapStream(this.options.stdout, "log");
    this._wrapStream(this.options.stderr, "log");
  }
  _wrapStream(stream, type) {
    if (!stream) {
      return;
    }
    if (!stream.__write) {
      stream.__write = stream.write;
    }
    stream.write = (data) => {
      this[type].raw(String(data).trim());
    };
  }
  /**
   * Restores the original standard output and error streams, removing the Consola redirection.
   */
  restoreStd() {
    this._restoreStream(this.options.stdout);
    this._restoreStream(this.options.stderr);
  }
  _restoreStream(stream) {
    if (!stream) {
      return;
    }
    if (stream.__write) {
      stream.write = stream.__write;
      delete stream.__write;
    }
  }
  /**
   * Pauses logging, queues incoming logs until resumed.
   */
  pauseLogs() {
    paused = true;
  }
  /**
   * Resumes logging, processing any queued logs.
   */
  resumeLogs() {
    paused = false;
    const _queue = queue.splice(0);
    for (const item of _queue) {
      item[0]._logFn(item[1], item[2]);
    }
  }
  /**
   * Replaces logging methods with mocks if a mock function is provided.
   *
   * @param {ConsolaOptions["mockFn"]} mockFn - The function to use for mocking logging methods. See {@link ConsolaOptions["mockFn"]}.
   */
  mockTypes(mockFn) {
    const _mockFn = mockFn || this.options.mockFn;
    this._mockFn = _mockFn;
    if (typeof _mockFn !== "function") {
      return;
    }
    for (const type in this.options.types) {
      this[type] = _mockFn(type, this.options.types[type]) || this[type];
      this[type].raw = this[type];
    }
  }
  _wrapLogFn(defaults, isRaw) {
    return (...args) => {
      if (paused) {
        queue.push([this, defaults, args, isRaw]);
        return;
      }
      return this._logFn(defaults, args, isRaw);
    };
  }
  _logFn(defaults, args, isRaw) {
    if ((defaults.level || 0) > this.level) {
      return false;
    }
    const logObj = {
      date: /* @__PURE__ */ new Date(),
      args: [],
      ...defaults,
      level: _normalizeLogLevel(defaults.level, this.options.types)
    };
    if (!isRaw && args.length === 1 && isLogObj(args[0])) {
      Object.assign(logObj, args[0]);
    } else {
      logObj.args = [...args];
    }
    if (logObj.message) {
      logObj.args.unshift(logObj.message);
      delete logObj.message;
    }
    if (logObj.additional) {
      if (!Array.isArray(logObj.additional)) {
        logObj.additional = logObj.additional.split("\n");
      }
      logObj.args.push("\n" + logObj.additional.join("\n"));
      delete logObj.additional;
    }
    logObj.type = typeof logObj.type === "string" ? logObj.type.toLowerCase() : "log";
    logObj.tag = typeof logObj.tag === "string" ? logObj.tag : "";
    const resolveLog = (newLog = false) => {
      const repeated = (this._lastLog.count || 0) - this.options.throttleMin;
      if (this._lastLog.object && repeated > 0) {
        const args2 = [...this._lastLog.object.args];
        if (repeated > 1) {
          args2.push(`(repeated ${repeated} times)`);
        }
        this._log({ ...this._lastLog.object, args: args2 });
        this._lastLog.count = 1;
      }
      if (newLog) {
        this._lastLog.object = logObj;
        this._log(logObj);
      }
    };
    clearTimeout(this._lastLog.timeout);
    const diffTime = this._lastLog.time && logObj.date ? logObj.date.getTime() - this._lastLog.time.getTime() : 0;
    this._lastLog.time = logObj.date;
    if (diffTime < this.options.throttle) {
      try {
        const serializedLog = JSON.stringify([
          logObj.type,
          logObj.tag,
          logObj.args
        ]);
        const isSameLog = this._lastLog.serialized === serializedLog;
        this._lastLog.serialized = serializedLog;
        if (isSameLog) {
          this._lastLog.count = (this._lastLog.count || 0) + 1;
          if (this._lastLog.count > this.options.throttleMin) {
            this._lastLog.timeout = setTimeout(
              resolveLog,
              this.options.throttle
            );
            return;
          }
        }
      } catch {
      }
    }
    resolveLog(true);
  }
  _log(logObj) {
    for (const reporter of this.options.reporters) {
      reporter.log(logObj, {
        options: this.options
      });
    }
  }
};
function _normalizeLogLevel(input, types = {}, defaultLevel = 3) {
  if (input === void 0) {
    return defaultLevel;
  }
  if (typeof input === "number") {
    return input;
  }
  if (types[input] && types[input].level !== void 0) {
    return types[input].level;
  }
  return defaultLevel;
}
Consola.prototype.add = Consola.prototype.addReporter;
Consola.prototype.remove = Consola.prototype.removeReporter;
Consola.prototype.clear = Consola.prototype.removeReporter;
Consola.prototype.withScope = Consola.prototype.withTag;
Consola.prototype.mock = Consola.prototype.mockTypes;
Consola.prototype.pause = Consola.prototype.pauseLogs;
Consola.prototype.resume = Consola.prototype.resumeLogs;
function createConsola(options = {}) {
  return new Consola(options);
}

// ../../node_modules/.pnpm/consola@3.4.0/node_modules/consola/dist/shared/consola.Cs5FdtHD.mjs
init_define_ENV_DEFINED_IN_BUILD_STEP();
import { formatWithOptions } from "node:util";
import { sep } from "node:path";
function parseStack(stack) {
  const cwd = process.cwd() + sep;
  const lines = stack.split("\n").splice(1).map((l2) => l2.trim().replace("file://", "").replace(cwd, ""));
  return lines;
}
function writeStream(data, stream) {
  const write = stream.__write || stream.write;
  return write.call(stream, data);
}
var bracket = (x2) => x2 ? `[${x2}]` : "";
var BasicReporter = class {
  formatStack(stack, opts) {
    const indent = "  ".repeat(((opts == null ? void 0 : opts.errorLevel) || 0) + 1);
    return indent + parseStack(stack).join(`
${indent}`);
  }
  formatError(err, opts) {
    const message = err.message ?? formatWithOptions(opts, err);
    const stack = err.stack ? this.formatStack(err.stack, opts) : "";
    const level = (opts == null ? void 0 : opts.errorLevel) || 0;
    const causedPrefix = level > 0 ? `${"  ".repeat(level)}[cause]: ` : "";
    const causedError = err.cause ? "\n\n" + this.formatError(err.cause, { ...opts, errorLevel: level + 1 }) : "";
    return causedPrefix + message + "\n" + stack + causedError;
  }
  formatArgs(args, opts) {
    const _args = args.map((arg) => {
      if (arg && typeof arg.stack === "string") {
        return this.formatError(arg, opts);
      }
      return arg;
    });
    return formatWithOptions(opts, ..._args);
  }
  formatDate(date, opts) {
    return opts.date ? date.toLocaleTimeString() : "";
  }
  filterAndJoin(arr) {
    return arr.filter(Boolean).join(" ");
  }
  formatLogObj(logObj, opts) {
    const message = this.formatArgs(logObj.args, opts);
    if (logObj.type === "box") {
      return "\n" + [
        bracket(logObj.tag),
        logObj.title && logObj.title,
        ...message.split("\n")
      ].filter(Boolean).map((l2) => " > " + l2).join("\n") + "\n";
    }
    return this.filterAndJoin([
      bracket(logObj.type),
      bracket(logObj.tag),
      message
    ]);
  }
  log(logObj, ctx) {
    const line = this.formatLogObj(logObj, {
      columns: ctx.options.stdout.columns || 0,
      ...ctx.options.formatOptions
    });
    return writeStream(
      line + "\n",
      logObj.level < 2 ? ctx.options.stderr || process.stderr : ctx.options.stdout || process.stdout
    );
  }
};

// ../../node_modules/.pnpm/consola@3.4.0/node_modules/consola/dist/index.mjs
import p$1 from "node:process";

// ../../node_modules/.pnpm/consola@3.4.0/node_modules/consola/dist/shared/consola.lX6kr4n8.mjs
init_define_ENV_DEFINED_IN_BUILD_STEP();
import * as tty from "node:tty";
var {
  env = {},
  argv = [],
  platform = ""
} = typeof process === "undefined" ? {} : process;
var isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
var isForced = "FORCE_COLOR" in env || argv.includes("--color");
var isWindows = platform === "win32";
var isDumbTerminal = env.TERM === "dumb";
var isCompatibleTerminal = tty && tty.isatty && tty.isatty(1) && env.TERM && !isDumbTerminal;
var isCI = "CI" in env && ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
var isColorSupported = !isDisabled && (isForced || isWindows && !isDumbTerminal || isCompatibleTerminal || isCI);
function replaceClose(index, string, close, replace, head = string.slice(0, Math.max(0, index)) + replace, tail = string.slice(Math.max(0, index + close.length)), next = tail.indexOf(close)) {
  return head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
}
function clearBleed(index, string, open, close, replace) {
  return index < 0 ? open + string + close : open + replaceClose(index, string, close, replace) + close;
}
function filterEmpty(open, close, replace = open, at = open.length + 1) {
  return (string) => string || !(string === "" || string === void 0) ? clearBleed(
    ("" + string).indexOf(close, at),
    string,
    open,
    close,
    replace
  ) : "";
}
function init(open, close, replace) {
  return filterEmpty(`\x1B[${open}m`, `\x1B[${close}m`, replace);
}
var colorDefs = {
  reset: init(0, 0),
  bold: init(1, 22, "\x1B[22m\x1B[1m"),
  dim: init(2, 22, "\x1B[22m\x1B[2m"),
  italic: init(3, 23),
  underline: init(4, 24),
  inverse: init(7, 27),
  hidden: init(8, 28),
  strikethrough: init(9, 29),
  black: init(30, 39),
  red: init(31, 39),
  green: init(32, 39),
  yellow: init(33, 39),
  blue: init(34, 39),
  magenta: init(35, 39),
  cyan: init(36, 39),
  white: init(37, 39),
  gray: init(90, 39),
  bgBlack: init(40, 49),
  bgRed: init(41, 49),
  bgGreen: init(42, 49),
  bgYellow: init(43, 49),
  bgBlue: init(44, 49),
  bgMagenta: init(45, 49),
  bgCyan: init(46, 49),
  bgWhite: init(47, 49),
  blackBright: init(90, 39),
  redBright: init(91, 39),
  greenBright: init(92, 39),
  yellowBright: init(93, 39),
  blueBright: init(94, 39),
  magentaBright: init(95, 39),
  cyanBright: init(96, 39),
  whiteBright: init(97, 39),
  bgBlackBright: init(100, 49),
  bgRedBright: init(101, 49),
  bgGreenBright: init(102, 49),
  bgYellowBright: init(103, 49),
  bgBlueBright: init(104, 49),
  bgMagentaBright: init(105, 49),
  bgCyanBright: init(106, 49),
  bgWhiteBright: init(107, 49)
};
function createColors(useColor = isColorSupported) {
  return useColor ? colorDefs : Object.fromEntries(Object.keys(colorDefs).map((key) => [key, String]));
}
var colors = createColors();
function getColor(color, fallback = "reset") {
  return colors[color] || colors[fallback];
}
var ansiRegex = [
  String.raw`[\u001B\u009B][[\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\d\/#&.:=?%@~_]+)*|[a-zA-Z\d]+(?:;[-a-zA-Z\d\/#&.:=?%@~_]*)*)?\u0007)`,
  String.raw`(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))`
].join("|");
function stripAnsi(text) {
  return text.replace(new RegExp(ansiRegex, "g"), "");
}
var boxStylePresets = {
  solid: {
    tl: "\u250C",
    tr: "\u2510",
    bl: "\u2514",
    br: "\u2518",
    h: "\u2500",
    v: "\u2502"
  },
  double: {
    tl: "\u2554",
    tr: "\u2557",
    bl: "\u255A",
    br: "\u255D",
    h: "\u2550",
    v: "\u2551"
  },
  doubleSingle: {
    tl: "\u2553",
    tr: "\u2556",
    bl: "\u2559",
    br: "\u255C",
    h: "\u2500",
    v: "\u2551"
  },
  doubleSingleRounded: {
    tl: "\u256D",
    tr: "\u256E",
    bl: "\u2570",
    br: "\u256F",
    h: "\u2500",
    v: "\u2551"
  },
  singleThick: {
    tl: "\u250F",
    tr: "\u2513",
    bl: "\u2517",
    br: "\u251B",
    h: "\u2501",
    v: "\u2503"
  },
  singleDouble: {
    tl: "\u2552",
    tr: "\u2555",
    bl: "\u2558",
    br: "\u255B",
    h: "\u2550",
    v: "\u2502"
  },
  singleDoubleRounded: {
    tl: "\u256D",
    tr: "\u256E",
    bl: "\u2570",
    br: "\u256F",
    h: "\u2550",
    v: "\u2502"
  },
  rounded: {
    tl: "\u256D",
    tr: "\u256E",
    bl: "\u2570",
    br: "\u256F",
    h: "\u2500",
    v: "\u2502"
  }
};
var defaultStyle = {
  borderColor: "white",
  borderStyle: "rounded",
  valign: "center",
  padding: 2,
  marginLeft: 1,
  marginTop: 1,
  marginBottom: 1
};
function box(text, _opts = {}) {
  const opts = {
    ..._opts,
    style: {
      ...defaultStyle,
      ..._opts.style
    }
  };
  const textLines = text.split("\n");
  const boxLines = [];
  const _color = getColor(opts.style.borderColor);
  const borderStyle = {
    ...typeof opts.style.borderStyle === "string" ? boxStylePresets[opts.style.borderStyle] || boxStylePresets.solid : opts.style.borderStyle
  };
  if (_color) {
    for (const key in borderStyle) {
      borderStyle[key] = _color(
        borderStyle[key]
      );
    }
  }
  const paddingOffset = opts.style.padding % 2 === 0 ? opts.style.padding : opts.style.padding + 1;
  const height = textLines.length + paddingOffset;
  const width = Math.max(...textLines.map((line) => stripAnsi(line).length)) + paddingOffset;
  const widthOffset = width + paddingOffset;
  const leftSpace = opts.style.marginLeft > 0 ? " ".repeat(opts.style.marginLeft) : "";
  if (opts.style.marginTop > 0) {
    boxLines.push("".repeat(opts.style.marginTop));
  }
  if (opts.title) {
    const title = _color ? _color(opts.title) : opts.title;
    const left = borderStyle.h.repeat(
      Math.floor((width - stripAnsi(opts.title).length) / 2)
    );
    const right = borderStyle.h.repeat(
      width - stripAnsi(opts.title).length - stripAnsi(left).length + paddingOffset
    );
    boxLines.push(
      `${leftSpace}${borderStyle.tl}${left}${title}${right}${borderStyle.tr}`
    );
  } else {
    boxLines.push(
      `${leftSpace}${borderStyle.tl}${borderStyle.h.repeat(widthOffset)}${borderStyle.tr}`
    );
  }
  const valignOffset = opts.style.valign === "center" ? Math.floor((height - textLines.length) / 2) : opts.style.valign === "top" ? height - textLines.length - paddingOffset : height - textLines.length;
  for (let i2 = 0; i2 < height; i2++) {
    if (i2 < valignOffset || i2 >= valignOffset + textLines.length) {
      boxLines.push(
        `${leftSpace}${borderStyle.v}${" ".repeat(widthOffset)}${borderStyle.v}`
      );
    } else {
      const line = textLines[i2 - valignOffset];
      const left = " ".repeat(paddingOffset);
      const right = " ".repeat(width - stripAnsi(line).length);
      boxLines.push(
        `${leftSpace}${borderStyle.v}${left}${line}${right}${borderStyle.v}`
      );
    }
  }
  boxLines.push(
    `${leftSpace}${borderStyle.bl}${borderStyle.h.repeat(widthOffset)}${borderStyle.br}`
  );
  if (opts.style.marginBottom > 0) {
    boxLines.push("".repeat(opts.style.marginBottom));
  }
  return boxLines.join("\n");
}

// ../../node_modules/.pnpm/consola@3.4.0/node_modules/consola/dist/index.mjs
var r2 = /* @__PURE__ */ Object.create(null);
var i = (e2) => {
  var _a8, _b5;
  return ((_a8 = globalThis.process) == null ? void 0 : _a8.env) || import.meta.env || ((_b5 = globalThis.Deno) == null ? void 0 : _b5.env.toObject()) || globalThis.__env__ || (e2 ? r2 : globalThis);
};
var s$1 = new Proxy(r2, { get(e2, o) {
  return i()[o] ?? r2[o];
}, has(e2, o) {
  const E2 = i();
  return o in E2 || o in r2;
}, set(e2, o, E2) {
  const b = i(true);
  return b[o] = E2, true;
}, deleteProperty(e2, o) {
  if (!o)
    return false;
  const E2 = i(true);
  return delete E2[o], true;
}, ownKeys() {
  const e2 = i(true);
  return Object.keys(e2);
} });
var t = typeof process < "u" && process.env && process.env.NODE_ENV || "";
var B2 = [["APPVEYOR"], ["AWS_AMPLIFY", "AWS_APP_ID", { ci: true }], ["AZURE_PIPELINES", "SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"], ["AZURE_STATIC", "INPUT_AZURE_STATIC_WEB_APPS_API_TOKEN"], ["APPCIRCLE", "AC_APPCIRCLE"], ["BAMBOO", "bamboo_planKey"], ["BITBUCKET", "BITBUCKET_COMMIT"], ["BITRISE", "BITRISE_IO"], ["BUDDY", "BUDDY_WORKSPACE_ID"], ["BUILDKITE"], ["CIRCLE", "CIRCLECI"], ["CIRRUS", "CIRRUS_CI"], ["CLOUDFLARE_PAGES", "CF_PAGES", { ci: true }], ["CODEBUILD", "CODEBUILD_BUILD_ARN"], ["CODEFRESH", "CF_BUILD_ID"], ["DRONE"], ["DRONE", "DRONE_BUILD_EVENT"], ["DSARI"], ["GITHUB_ACTIONS"], ["GITLAB", "GITLAB_CI"], ["GITLAB", "CI_MERGE_REQUEST_ID"], ["GOCD", "GO_PIPELINE_LABEL"], ["LAYERCI"], ["HUDSON", "HUDSON_URL"], ["JENKINS", "JENKINS_URL"], ["MAGNUM"], ["NETLIFY"], ["NETLIFY", "NETLIFY_LOCAL", { ci: false }], ["NEVERCODE"], ["RENDER"], ["SAIL", "SAILCI"], ["SEMAPHORE"], ["SCREWDRIVER"], ["SHIPPABLE"], ["SOLANO", "TDDIUM"], ["STRIDER"], ["TEAMCITY", "TEAMCITY_VERSION"], ["TRAVIS"], ["VERCEL", "NOW_BUILDER"], ["VERCEL", "VERCEL", { ci: false }], ["VERCEL", "VERCEL_ENV", { ci: false }], ["APPCENTER", "APPCENTER_BUILD_ID"], ["CODESANDBOX", "CODESANDBOX_SSE", { ci: false }], ["STACKBLITZ"], ["STORMKIT"], ["CLEAVR"], ["ZEABUR"], ["CODESPHERE", "CODESPHERE_APP_ID", { ci: true }], ["RAILWAY", "RAILWAY_PROJECT_ID"], ["RAILWAY", "RAILWAY_SERVICE_ID"], ["DENO-DEPLOY", "DENO_DEPLOYMENT_ID"], ["FIREBASE_APP_HOSTING", "FIREBASE_APP_HOSTING", { ci: true }]];
function p2() {
  var _a8, _b5, _c, _d, _e, _f;
  if ((_a8 = globalThis.process) == null ? void 0 : _a8.env)
    for (const e2 of B2) {
      const o = e2[1] || e2[0];
      if ((_b5 = globalThis.process) == null ? void 0 : _b5.env[o])
        return { name: e2[0].toLowerCase(), ...e2[2] };
    }
  return ((_d = (_c = globalThis.process) == null ? void 0 : _c.env) == null ? void 0 : _d.SHELL) === "/bin/jsh" && ((_f = (_e = globalThis.process) == null ? void 0 : _e.versions) == null ? void 0 : _f.webcontainer) ? { name: "stackblitz", ci: false } : { name: "", ci: false };
}
var l = p2();
l.name;
function n(e2) {
  return e2 ? e2 !== "false" : false;
}
var _a;
var I2 = ((_a = globalThis.process) == null ? void 0 : _a.platform) || "";
var T2 = n(s$1.CI) || l.ci !== false;
var _a2, _b;
var R2 = n(((_a2 = globalThis.process) == null ? void 0 : _a2.stdout) && ((_b = globalThis.process) == null ? void 0 : _b.stdout.isTTY));
var U = n(s$1.DEBUG);
var A2 = t === "test" || n(s$1.TEST);
n(s$1.MINIMAL) || T2 || A2 || !R2;
var _2 = /^win/i.test(I2);
!n(s$1.NO_COLOR) && (n(s$1.FORCE_COLOR) || (R2 || _2) && s$1.TERM !== "dumb" || T2);
var _a3, _b2;
var C = (((_b2 = (_a3 = globalThis.process) == null ? void 0 : _a3.versions) == null ? void 0 : _b2.node) || "").replace(/^v/, "") || null;
Number(C == null ? void 0 : C.split(".")[0]) || null;
var y2 = globalThis.process || /* @__PURE__ */ Object.create(null);
var c2 = { versions: {} };
new Proxy(y2, { get(e2, o) {
  if (o === "env")
    return s$1;
  if (o in e2)
    return e2[o];
  if (o in c2)
    return c2[o];
} });
var _a4, _b3;
var L2 = ((_b3 = (_a4 = globalThis.process) == null ? void 0 : _a4.release) == null ? void 0 : _b3.name) === "node";
var _a5, _b4;
var a2 = !!globalThis.Bun || !!((_b4 = (_a5 = globalThis.process) == null ? void 0 : _a5.versions) == null ? void 0 : _b4.bun);
var D = !!globalThis.Deno;
var O2 = !!globalThis.fastly;
var S2 = !!globalThis.Netlify;
var N2 = !!globalThis.EdgeRuntime;
var _a6;
var P2 = ((_a6 = globalThis.navigator) == null ? void 0 : _a6.userAgent) === "Cloudflare-Workers";
var F = [[S2, "netlify"], [N2, "edge-light"], [P2, "workerd"], [O2, "fastly"], [D, "deno"], [a2, "bun"], [L2, "node"]];
function G2() {
  const e2 = F.find((o) => o[0]);
  if (e2)
    return { name: e2[1] };
}
var u2 = G2();
(u2 == null ? void 0 : u2.name) || "";
function ansiRegex2({ onlyFirst = false } = {}) {
  const ST = "(?:\\u0007|\\u001B\\u005C|\\u009C)";
  const pattern = [
    `[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?${ST})`,
    "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"
  ].join("|");
  return new RegExp(pattern, onlyFirst ? void 0 : "g");
}
var regex = ansiRegex2();
function stripAnsi2(string) {
  if (typeof string !== "string") {
    throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
  }
  return string.replace(regex, "");
}
function isAmbiguous(x2) {
  return x2 === 161 || x2 === 164 || x2 === 167 || x2 === 168 || x2 === 170 || x2 === 173 || x2 === 174 || x2 >= 176 && x2 <= 180 || x2 >= 182 && x2 <= 186 || x2 >= 188 && x2 <= 191 || x2 === 198 || x2 === 208 || x2 === 215 || x2 === 216 || x2 >= 222 && x2 <= 225 || x2 === 230 || x2 >= 232 && x2 <= 234 || x2 === 236 || x2 === 237 || x2 === 240 || x2 === 242 || x2 === 243 || x2 >= 247 && x2 <= 250 || x2 === 252 || x2 === 254 || x2 === 257 || x2 === 273 || x2 === 275 || x2 === 283 || x2 === 294 || x2 === 295 || x2 === 299 || x2 >= 305 && x2 <= 307 || x2 === 312 || x2 >= 319 && x2 <= 322 || x2 === 324 || x2 >= 328 && x2 <= 331 || x2 === 333 || x2 === 338 || x2 === 339 || x2 === 358 || x2 === 359 || x2 === 363 || x2 === 462 || x2 === 464 || x2 === 466 || x2 === 468 || x2 === 470 || x2 === 472 || x2 === 474 || x2 === 476 || x2 === 593 || x2 === 609 || x2 === 708 || x2 === 711 || x2 >= 713 && x2 <= 715 || x2 === 717 || x2 === 720 || x2 >= 728 && x2 <= 731 || x2 === 733 || x2 === 735 || x2 >= 768 && x2 <= 879 || x2 >= 913 && x2 <= 929 || x2 >= 931 && x2 <= 937 || x2 >= 945 && x2 <= 961 || x2 >= 963 && x2 <= 969 || x2 === 1025 || x2 >= 1040 && x2 <= 1103 || x2 === 1105 || x2 === 8208 || x2 >= 8211 && x2 <= 8214 || x2 === 8216 || x2 === 8217 || x2 === 8220 || x2 === 8221 || x2 >= 8224 && x2 <= 8226 || x2 >= 8228 && x2 <= 8231 || x2 === 8240 || x2 === 8242 || x2 === 8243 || x2 === 8245 || x2 === 8251 || x2 === 8254 || x2 === 8308 || x2 === 8319 || x2 >= 8321 && x2 <= 8324 || x2 === 8364 || x2 === 8451 || x2 === 8453 || x2 === 8457 || x2 === 8467 || x2 === 8470 || x2 === 8481 || x2 === 8482 || x2 === 8486 || x2 === 8491 || x2 === 8531 || x2 === 8532 || x2 >= 8539 && x2 <= 8542 || x2 >= 8544 && x2 <= 8555 || x2 >= 8560 && x2 <= 8569 || x2 === 8585 || x2 >= 8592 && x2 <= 8601 || x2 === 8632 || x2 === 8633 || x2 === 8658 || x2 === 8660 || x2 === 8679 || x2 === 8704 || x2 === 8706 || x2 === 8707 || x2 === 8711 || x2 === 8712 || x2 === 8715 || x2 === 8719 || x2 === 8721 || x2 === 8725 || x2 === 8730 || x2 >= 8733 && x2 <= 8736 || x2 === 8739 || x2 === 8741 || x2 >= 8743 && x2 <= 8748 || x2 === 8750 || x2 >= 8756 && x2 <= 8759 || x2 === 8764 || x2 === 8765 || x2 === 8776 || x2 === 8780 || x2 === 8786 || x2 === 8800 || x2 === 8801 || x2 >= 8804 && x2 <= 8807 || x2 === 8810 || x2 === 8811 || x2 === 8814 || x2 === 8815 || x2 === 8834 || x2 === 8835 || x2 === 8838 || x2 === 8839 || x2 === 8853 || x2 === 8857 || x2 === 8869 || x2 === 8895 || x2 === 8978 || x2 >= 9312 && x2 <= 9449 || x2 >= 9451 && x2 <= 9547 || x2 >= 9552 && x2 <= 9587 || x2 >= 9600 && x2 <= 9615 || x2 >= 9618 && x2 <= 9621 || x2 === 9632 || x2 === 9633 || x2 >= 9635 && x2 <= 9641 || x2 === 9650 || x2 === 9651 || x2 === 9654 || x2 === 9655 || x2 === 9660 || x2 === 9661 || x2 === 9664 || x2 === 9665 || x2 >= 9670 && x2 <= 9672 || x2 === 9675 || x2 >= 9678 && x2 <= 9681 || x2 >= 9698 && x2 <= 9701 || x2 === 9711 || x2 === 9733 || x2 === 9734 || x2 === 9737 || x2 === 9742 || x2 === 9743 || x2 === 9756 || x2 === 9758 || x2 === 9792 || x2 === 9794 || x2 === 9824 || x2 === 9825 || x2 >= 9827 && x2 <= 9829 || x2 >= 9831 && x2 <= 9834 || x2 === 9836 || x2 === 9837 || x2 === 9839 || x2 === 9886 || x2 === 9887 || x2 === 9919 || x2 >= 9926 && x2 <= 9933 || x2 >= 9935 && x2 <= 9939 || x2 >= 9941 && x2 <= 9953 || x2 === 9955 || x2 === 9960 || x2 === 9961 || x2 >= 9963 && x2 <= 9969 || x2 === 9972 || x2 >= 9974 && x2 <= 9977 || x2 === 9979 || x2 === 9980 || x2 === 9982 || x2 === 9983 || x2 === 10045 || x2 >= 10102 && x2 <= 10111 || x2 >= 11094 && x2 <= 11097 || x2 >= 12872 && x2 <= 12879 || x2 >= 57344 && x2 <= 63743 || x2 >= 65024 && x2 <= 65039 || x2 === 65533 || x2 >= 127232 && x2 <= 127242 || x2 >= 127248 && x2 <= 127277 || x2 >= 127280 && x2 <= 127337 || x2 >= 127344 && x2 <= 127373 || x2 === 127375 || x2 === 127376 || x2 >= 127387 && x2 <= 127404 || x2 >= 917760 && x2 <= 917999 || x2 >= 983040 && x2 <= 1048573 || x2 >= 1048576 && x2 <= 1114109;
}
function isFullWidth(x2) {
  return x2 === 12288 || x2 >= 65281 && x2 <= 65376 || x2 >= 65504 && x2 <= 65510;
}
function isWide(x2) {
  return x2 >= 4352 && x2 <= 4447 || x2 === 8986 || x2 === 8987 || x2 === 9001 || x2 === 9002 || x2 >= 9193 && x2 <= 9196 || x2 === 9200 || x2 === 9203 || x2 === 9725 || x2 === 9726 || x2 === 9748 || x2 === 9749 || x2 >= 9776 && x2 <= 9783 || x2 >= 9800 && x2 <= 9811 || x2 === 9855 || x2 >= 9866 && x2 <= 9871 || x2 === 9875 || x2 === 9889 || x2 === 9898 || x2 === 9899 || x2 === 9917 || x2 === 9918 || x2 === 9924 || x2 === 9925 || x2 === 9934 || x2 === 9940 || x2 === 9962 || x2 === 9970 || x2 === 9971 || x2 === 9973 || x2 === 9978 || x2 === 9981 || x2 === 9989 || x2 === 9994 || x2 === 9995 || x2 === 10024 || x2 === 10060 || x2 === 10062 || x2 >= 10067 && x2 <= 10069 || x2 === 10071 || x2 >= 10133 && x2 <= 10135 || x2 === 10160 || x2 === 10175 || x2 === 11035 || x2 === 11036 || x2 === 11088 || x2 === 11093 || x2 >= 11904 && x2 <= 11929 || x2 >= 11931 && x2 <= 12019 || x2 >= 12032 && x2 <= 12245 || x2 >= 12272 && x2 <= 12287 || x2 >= 12289 && x2 <= 12350 || x2 >= 12353 && x2 <= 12438 || x2 >= 12441 && x2 <= 12543 || x2 >= 12549 && x2 <= 12591 || x2 >= 12593 && x2 <= 12686 || x2 >= 12688 && x2 <= 12773 || x2 >= 12783 && x2 <= 12830 || x2 >= 12832 && x2 <= 12871 || x2 >= 12880 && x2 <= 42124 || x2 >= 42128 && x2 <= 42182 || x2 >= 43360 && x2 <= 43388 || x2 >= 44032 && x2 <= 55203 || x2 >= 63744 && x2 <= 64255 || x2 >= 65040 && x2 <= 65049 || x2 >= 65072 && x2 <= 65106 || x2 >= 65108 && x2 <= 65126 || x2 >= 65128 && x2 <= 65131 || x2 >= 94176 && x2 <= 94180 || x2 === 94192 || x2 === 94193 || x2 >= 94208 && x2 <= 100343 || x2 >= 100352 && x2 <= 101589 || x2 >= 101631 && x2 <= 101640 || x2 >= 110576 && x2 <= 110579 || x2 >= 110581 && x2 <= 110587 || x2 === 110589 || x2 === 110590 || x2 >= 110592 && x2 <= 110882 || x2 === 110898 || x2 >= 110928 && x2 <= 110930 || x2 === 110933 || x2 >= 110948 && x2 <= 110951 || x2 >= 110960 && x2 <= 111355 || x2 >= 119552 && x2 <= 119638 || x2 >= 119648 && x2 <= 119670 || x2 === 126980 || x2 === 127183 || x2 === 127374 || x2 >= 127377 && x2 <= 127386 || x2 >= 127488 && x2 <= 127490 || x2 >= 127504 && x2 <= 127547 || x2 >= 127552 && x2 <= 127560 || x2 === 127568 || x2 === 127569 || x2 >= 127584 && x2 <= 127589 || x2 >= 127744 && x2 <= 127776 || x2 >= 127789 && x2 <= 127797 || x2 >= 127799 && x2 <= 127868 || x2 >= 127870 && x2 <= 127891 || x2 >= 127904 && x2 <= 127946 || x2 >= 127951 && x2 <= 127955 || x2 >= 127968 && x2 <= 127984 || x2 === 127988 || x2 >= 127992 && x2 <= 128062 || x2 === 128064 || x2 >= 128066 && x2 <= 128252 || x2 >= 128255 && x2 <= 128317 || x2 >= 128331 && x2 <= 128334 || x2 >= 128336 && x2 <= 128359 || x2 === 128378 || x2 === 128405 || x2 === 128406 || x2 === 128420 || x2 >= 128507 && x2 <= 128591 || x2 >= 128640 && x2 <= 128709 || x2 === 128716 || x2 >= 128720 && x2 <= 128722 || x2 >= 128725 && x2 <= 128727 || x2 >= 128732 && x2 <= 128735 || x2 === 128747 || x2 === 128748 || x2 >= 128756 && x2 <= 128764 || x2 >= 128992 && x2 <= 129003 || x2 === 129008 || x2 >= 129292 && x2 <= 129338 || x2 >= 129340 && x2 <= 129349 || x2 >= 129351 && x2 <= 129535 || x2 >= 129648 && x2 <= 129660 || x2 >= 129664 && x2 <= 129673 || x2 >= 129679 && x2 <= 129734 || x2 >= 129742 && x2 <= 129756 || x2 >= 129759 && x2 <= 129769 || x2 >= 129776 && x2 <= 129784 || x2 >= 131072 && x2 <= 196605 || x2 >= 196608 && x2 <= 262141;
}
function validate(codePoint) {
  if (!Number.isSafeInteger(codePoint)) {
    throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
  }
}
function eastAsianWidth(codePoint, { ambiguousAsWide = false } = {}) {
  validate(codePoint);
  if (isFullWidth(codePoint) || isWide(codePoint) || ambiguousAsWide && isAmbiguous(codePoint)) {
    return 2;
  }
  return 1;
}
var emojiRegex = () => {
  return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g;
};
var _a7;
var segmenter = ((_a7 = globalThis.Intl) == null ? void 0 : _a7.Segmenter) ? new Intl.Segmenter() : { segment: (str) => str.split("") };
var defaultIgnorableCodePointRegex = new RegExp("^\\p{Default_Ignorable_Code_Point}$", "u");
function stringWidth$1(string, options = {}) {
  if (typeof string !== "string" || string.length === 0) {
    return 0;
  }
  const {
    ambiguousIsNarrow = true,
    countAnsiEscapeCodes = false
  } = options;
  if (!countAnsiEscapeCodes) {
    string = stripAnsi2(string);
  }
  if (string.length === 0) {
    return 0;
  }
  let width = 0;
  const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
  for (const { segment: character } of segmenter.segment(string)) {
    const codePoint = character.codePointAt(0);
    if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159) {
      continue;
    }
    if (codePoint >= 8203 && codePoint <= 8207 || codePoint === 65279) {
      continue;
    }
    if (codePoint >= 768 && codePoint <= 879 || codePoint >= 6832 && codePoint <= 6911 || codePoint >= 7616 && codePoint <= 7679 || codePoint >= 8400 && codePoint <= 8447 || codePoint >= 65056 && codePoint <= 65071) {
      continue;
    }
    if (codePoint >= 55296 && codePoint <= 57343) {
      continue;
    }
    if (codePoint >= 65024 && codePoint <= 65039) {
      continue;
    }
    if (defaultIgnorableCodePointRegex.test(character)) {
      continue;
    }
    if (emojiRegex().test(character)) {
      width += 2;
      continue;
    }
    width += eastAsianWidth(codePoint, eastAsianWidthOptions);
  }
  return width;
}
function isUnicodeSupported() {
  const { env: env2 } = p$1;
  const { TERM, TERM_PROGRAM } = env2;
  if (p$1.platform !== "win32") {
    return TERM !== "linux";
  }
  return Boolean(env2.WT_SESSION) || Boolean(env2.TERMINUS_SUBLIME) || env2.ConEmuTask === "{cmd::Cmder}" || TERM_PROGRAM === "Terminus-Sublime" || TERM_PROGRAM === "vscode" || TERM === "xterm-256color" || TERM === "alacritty" || TERM === "rxvt-unicode" || TERM === "rxvt-unicode-256color" || env2.TERMINAL_EMULATOR === "JetBrains-JediTerm";
}
var TYPE_COLOR_MAP = {
  info: "cyan",
  fail: "red",
  success: "green",
  ready: "green",
  start: "magenta"
};
var LEVEL_COLOR_MAP = {
  0: "red",
  1: "yellow"
};
var unicode = isUnicodeSupported();
var s = (c3, fallback) => unicode ? c3 : fallback;
var TYPE_ICONS = {
  error: s("\u2716", "\xD7"),
  fatal: s("\u2716", "\xD7"),
  ready: s("\u2714", "\u221A"),
  warn: s("\u26A0", "\u203C"),
  info: s("\u2139", "i"),
  success: s("\u2714", "\u221A"),
  debug: s("\u2699", "D"),
  trace: s("\u2192", "\u2192"),
  fail: s("\u2716", "\xD7"),
  start: s("\u25D0", "o"),
  log: ""
};
function stringWidth(str) {
  const hasICU = typeof Intl === "object";
  if (!hasICU || !Intl.Segmenter) {
    return stripAnsi(str).length;
  }
  return stringWidth$1(str);
}
var FancyReporter = class extends BasicReporter {
  formatStack(stack, opts) {
    const indent = "  ".repeat(((opts == null ? void 0 : opts.errorLevel) || 0) + 1);
    return `
${indent}` + parseStack(stack).map(
      (line) => "  " + line.replace(/^at +/, (m2) => colors.gray(m2)).replace(/\((.+)\)/, (_3, m2) => `(${colors.cyan(m2)})`)
    ).join(`
${indent}`);
  }
  formatType(logObj, isBadge, opts) {
    const typeColor = TYPE_COLOR_MAP[logObj.type] || LEVEL_COLOR_MAP[logObj.level] || "gray";
    if (isBadge) {
      return getBgColor(typeColor)(
        colors.black(` ${logObj.type.toUpperCase()} `)
      );
    }
    const _type = typeof TYPE_ICONS[logObj.type] === "string" ? TYPE_ICONS[logObj.type] : logObj.icon || logObj.type;
    return _type ? getColor2(typeColor)(_type) : "";
  }
  formatLogObj(logObj, opts) {
    const [message, ...additional] = this.formatArgs(logObj.args, opts).split(
      "\n"
    );
    if (logObj.type === "box") {
      return box(
        characterFormat(
          message + (additional.length > 0 ? "\n" + additional.join("\n") : "")
        ),
        {
          title: logObj.title ? characterFormat(logObj.title) : void 0,
          style: logObj.style
        }
      );
    }
    const date = this.formatDate(logObj.date, opts);
    const coloredDate = date && colors.gray(date);
    const isBadge = logObj.badge ?? logObj.level < 2;
    const type = this.formatType(logObj, isBadge, opts);
    const tag = logObj.tag ? colors.gray(logObj.tag) : "";
    let line;
    const left = this.filterAndJoin([type, characterFormat(message)]);
    const right = this.filterAndJoin(opts.columns ? [tag, coloredDate] : [tag]);
    const space = (opts.columns || 0) - stringWidth(left) - stringWidth(right) - 2;
    line = space > 0 && (opts.columns || 0) >= 80 ? left + " ".repeat(space) + right : (right ? `${colors.gray(`[${right}]`)} ` : "") + left;
    line += characterFormat(
      additional.length > 0 ? "\n" + additional.join("\n") : ""
    );
    if (logObj.type === "trace") {
      const _err = new Error("Trace: " + logObj.message);
      line += this.formatStack(_err.stack || "");
    }
    return isBadge ? "\n" + line + "\n" : line;
  }
};
function characterFormat(str) {
  return str.replace(/`([^`]+)`/gm, (_3, m2) => colors.cyan(m2)).replace(/\s+_([^_]+)_\s+/gm, (_3, m2) => ` ${colors.underline(m2)} `);
}
function getColor2(color = "white") {
  return colors[color] || colors.white;
}
function getBgColor(color = "bgWhite") {
  return colors[`bg${color[0].toUpperCase()}${color.slice(1)}`] || colors.bgWhite;
}
function createConsola2(options = {}) {
  let level = _getDefaultLogLevel();
  if (process.env.CONSOLA_LEVEL) {
    level = Number.parseInt(process.env.CONSOLA_LEVEL) ?? level;
  }
  const consola2 = createConsola({
    level,
    defaults: { level },
    stdout: process.stdout,
    stderr: process.stderr,
    prompt: (...args) => Promise.resolve().then(() => (init_prompt(), prompt_exports)).then((m2) => m2.prompt(...args)),
    reporters: options.reporters || [
      options.fancy ?? !(T2 || A2) ? new FancyReporter() : new BasicReporter()
    ],
    ...options
  });
  return consola2;
}
function _getDefaultLogLevel() {
  if (U) {
    return LogLevels.debug;
  }
  if (A2) {
    return LogLevels.warn;
  }
  return LogLevels.info;
}
var consola = createConsola2();

// src/utilities/log.ts
var log = consola;
function logError(error) {
  log.error(causeString(error), error);
}
function causeString(error) {
  var _a8;
  if (typeof error === "object" && error.cause) {
    if ((_a8 = error.cause.errors) == null ? void 0 : _a8.length)
      return error.cause.errors.join(", ");
    if (error.cause.code)
      return "" + error.cause.code;
    return JSON.stringify(error.cause);
  }
  return "";
}

// src/utilities/globalFlags.ts
init_define_ENV_DEFINED_IN_BUILD_STEP();
var projectOption = {
  flags: "--project <path>",
  description: "Path to the inlang project."
};

// src/commands/machine/translate.ts
var import_cli_progress = __toESM(require_cli_progress(), 1);
import fs2 from "node:fs/promises";

// src/commands/machine/machineTranslateBundle.ts
init_define_ENV_DEFINED_IN_BUILD_STEP();
import { randomUUID } from "node:crypto";
var PRIMARY_API_KEY_ENV = "INLANG_GOOGLE_TRANSLATE_API_KEY";
async function machineTranslateBundle(args) {
  var _a8, _b5;
  try {
    const apiKey = args.googleApiKey ?? process.env[PRIMARY_API_KEY_ENV];
    if (!apiKey) {
      return { error: `${PRIMARY_API_KEY_ENV} is not set` };
    }
    const copy = structuredClone(args.bundle);
    const sourceMessage = copy.messages.find(
      (message) => message.locale === args.sourceLocale
    );
    if (!sourceMessage) {
      return {
        error: `Source locale not found in the bundle: ${args.bundle.id}`
      };
    }
    for (const sourceVariant of sourceMessage.variants) {
      const sourcePattern = serializePattern(sourceVariant.pattern, {});
      for (const targetLocale of args.targetLocales) {
        if (targetLocale === args.sourceLocale) {
          continue;
        }
        const targetMessage = copy.messages.find(
          (message) => message.locale === targetLocale
        );
        if (targetMessage) {
          const existingVariant = findMatchingVariant(
            targetMessage.variants,
            sourceVariant.matches
          );
          if (existingVariant && !(existingVariant.pattern.length === 0 || existingVariant.pattern.length === 1 && ((_a8 = existingVariant.pattern[0]) == null ? void 0 : _a8.type) === "text" && existingVariant.pattern[0].value === "")) {
            continue;
          }
        }
        const response = await fetch(
          "https://translation.googleapis.com/language/translate/v2?" + new URLSearchParams({
            q: sourcePattern,
            target: targetLocale,
            source: args.sourceLocale,
            format: "html",
            key: apiKey
          }),
          { method: "POST" }
        );
        if (!response.ok) {
          const err = `${response.status} ${response.statusText}: translating from ${args.sourceLocale} to ${targetLocale}`;
          return { error: err };
        }
        const json = await response.json();
        const pattern = deserializePattern(
          json.data.translations[0].translatedText
        );
        if (targetMessage) {
          const existingVariant = findMatchingVariant(
            targetMessage.variants,
            sourceVariant.matches
          );
          if (existingVariant && (existingVariant.pattern.length === 0 || existingVariant.pattern.length === 1 && ((_b5 = existingVariant.pattern[0]) == null ? void 0 : _b5.type) === "text" && existingVariant.pattern[0].value === "")) {
            existingVariant.pattern = pattern;
          } else {
            targetMessage.variants.push({
              id: randomUUID(),
              messageId: targetMessage.id,
              matches: sourceVariant.matches,
              pattern
            });
          }
        } else {
          const newMessageId = randomUUID();
          copy.messages.push({
            ...sourceMessage,
            id: newMessageId,
            locale: targetLocale,
            variants: [
              {
                id: randomUUID(),
                messageId: newMessageId,
                matches: sourceVariant.matches,
                pattern
              }
            ]
          });
        }
      }
    }
    return { data: copy };
  } catch (error) {
    return { error: (error == null ? void 0 : error.toString()) ?? "unknown error" };
  }
}
function findMatchingVariant(variants, matches) {
  if (matches.length === 0) {
    return variants.find((variant) => variant.matches.length === 0);
  }
  return variants.find((variant) => {
    if (variant.matches.length !== matches.length) {
      return false;
    }
    return matches.every(
      (sourceMatch) => variant.matches.some((targetMatch) => {
        if (targetMatch.key !== sourceMatch.key || targetMatch.type !== sourceMatch.type) {
          return false;
        }
        if (sourceMatch.type === "literal-match" && targetMatch.type === "literal-match") {
          return sourceMatch.value === targetMatch.value;
        }
        return true;
      })
    );
  });
}
var escapeStart = `<span class="notranslate">`;
var escapeEnd = "</span>";
function serializePattern(pattern, placeholderMetadata) {
  var _a8;
  let result = "";
  for (const [index, element] of pattern.entries()) {
    if (element.type === "text") {
      result += element.value.replaceAll("\r", "<inlang-CarriageReturn>").replaceAll("\n", "<inlang-LineFeed>");
    } else {
      placeholderMetadata[element.name] = {
        leadingCharacter: result.at(-1) ?? void 0,
        trailingCharacter: ((_a8 = pattern[index + 1]) == null ? void 0 : _a8.type) === "text" ? pattern[index + 1].value[0] : void 0
      };
      result += `${escapeStart}${JSON.stringify(element)}${escapeEnd}`;
    }
  }
  return result;
}
function deserializePattern(text) {
  const result = [];
  const unescapedText = text.replaceAll("&quot;", '"').replaceAll("&#39;", "'").replaceAll("<inlang-CarriageReturn>", "\r").replaceAll("<inlang-LineFeed> ", "\n").replaceAll("<inlang-LineFeed>", "\n");
  let index = 0;
  while (index < unescapedText.length) {
    const start = unescapedText.indexOf(escapeStart, index);
    if (start === -1) {
      result.push({ type: "text", value: unescapedText.slice(index) });
      break;
    } else if (index < start) {
      result.push({ type: "text", value: unescapedText.slice(index, start) });
      index = start;
      continue;
    }
    const end = unescapedText.indexOf(escapeEnd, start);
    if (end === -1) {
      result.push({ type: "text", value: unescapedText.slice(index) });
      break;
    }
    const expressionAsText = unescapedText.slice(
      start + escapeStart.length,
      end
    );
    const expression = JSON.parse(expressionAsText);
    result.push(expression);
    index = end + escapeEnd.length;
  }
  return result;
}

// src/commands/machine/translate.ts
var translate = new Command().command("translate").requiredOption(projectOption.flags, projectOption.description).option("-q, --quiet", "don't log every tranlation.", false).option("--locale <source>", "Locales for translation.").option(
  "--targetLocales <targets...>",
  "Comma separated list of target locales for translation."
).option("-n, --nobar", "disable progress bar", false).description("Machine translate bundles.").action(async (args) => {
  let exitCode = 0;
  try {
    const project = await getInlangProject({ projectPath: args.project });
    await translateCommandAction({ project });
    await saveProjectToDirectory({ fs: fs2, path: args.project, project });
  } catch (error) {
    logError(error);
    exitCode = 1;
  } finally {
    process.exit(exitCode);
  }
});
async function translateCommandAction(args) {
  var _a8;
  const options = translate.opts();
  const googleApiKey = process.env.INLANG_GOOGLE_TRANSLATE_API_KEY;
  if (!googleApiKey) {
    throw new Error(
      [
        "INLANG_GOOGLE_TRANSLATE_API_KEY must be set to use machine translate.",
        "Create your own Google Cloud Translation API key and export it before running this command.",
        "See https://inlang.com/m/2qj2w8pu/app-inlang-cli/byok"
      ].join("\n")
    );
  }
  const bar = options.nobar ? void 0 : new import_cli_progress.default.SingleBar(
    {
      clearOnComplete: true,
      format: `\u{1F916} Machine translating bundles | {bar} | {percentage}% | {value}/{total} Bundles`
    },
    import_cli_progress.default.Presets.shades_grey
  );
  try {
    const settings = await args.project.settings.get();
    const targetLocales = options.targetLocales ? (_a8 = options.targetLocales[0]) == null ? void 0 : _a8.split(",") : settings.locales;
    const bundles = await selectBundleNested(args.project.db).selectAll().execute();
    if (bundles.length === 0) {
      log.warn(
        "No message bundles found to translate. Check your project setup with `inlang validate`"
      );
      return;
    }
    bar == null ? void 0 : bar.start(bundles.length, 0);
    const promises = [];
    const errors = [];
    for (const bundle of bundles) {
      const translationPromise = machineTranslateBundle({
        bundle,
        sourceLocale: settings.baseLocale,
        targetLocales,
        googleApiKey
      });
      const trackedPromise = translationPromise.then((result) => {
        bar == null ? void 0 : bar.increment();
        return result;
      });
      promises.push(trackedPromise);
    }
    const updatedBundles = await Promise.all(promises);
    for (const bundle of updatedBundles) {
      if (bundle.error) {
        errors.push(bundle.error);
        continue;
      } else if (bundle.data) {
        await upsertBundleNested(args.project.db, bundle.data);
      }
    }
    bar == null ? void 0 : bar.stop();
    log.success("Machine translate complete.");
    if (errors.length > 0) {
      log.warn("Some bundles could not be translated.");
      log.warn(errors.join("\n"));
    }
  } catch (error) {
    logError(error);
  }
}

// src/commands/machine/index.ts
var machine = new Command().command("machine").description("Commands for automating translations.").argument("[command]").addCommand(translate);

// src/commands/plugin/index.ts
init_define_ENV_DEFINED_IN_BUILD_STEP();

// src/commands/plugin/build/command.ts
init_define_ENV_DEFINED_IN_BUILD_STEP();

// src/commands/plugin/build/moduleBuildOptions.ts
init_define_ENV_DEFINED_IN_BUILD_STEP();
var moduleBuildOptions = (args) => {
  return {
    entryPoints: [args.entry],
    outdir: args.outdir,
    minify: args.minify,
    // ----------------------------------
    // allow top level await
    // https://caniuse.com/mdn-javascript_operators_await_top_level
    target: "es2022",
    // inlang does not support import maps
    bundle: true,
    // esm to work in the browser
    format: "esm",
    //! extremly important to be platform neutral
    //! to ensure that modules run in browser
    //! and server contexts.
    platform: "neutral",
    // sourcemaps are unused at the moment
    sourcemap: false,
    plugins: args.plugins
  };
};

// src/commands/plugin/build/command.ts
import { context } from "esbuild-wasm";
var build = new Command().command("build").description("build an inlang module.").requiredOption(
  "--entry <entry>",
  "The path to the entry of the module. Usually src/index.{js|ts}."
).option("--outdir <path>", "The output directory.", "./dist").option("--watch", "Watch for changes and rebuild.", false).option("--minify", "Minifies the plugin. Recommend for distribution.", false).action(buildCommandAction);
async function buildCommandAction(args) {
  try {
    const ctx = await context(
      moduleBuildOptions({
        ...args,
        plugins: [
          {
            name: "logger",
            setup: ({ onEnd }) => onEnd(() => console.info("\u{1F389} changes processed"))
          }
        ]
      })
    );
    if (args.watch) {
      await ctx.watch({});
      console.info("\u{1F440} watching for changes...");
    } else {
      await ctx.rebuild();
      console.info("\u2705 build complete");
      await ctx.dispose();
    }
  } catch (e2) {
    console.error("An error occurred while building the module:");
    console.error(e2);
    process.exit(1);
  }
}

// src/commands/plugin/index.ts
var plugin = new Command().command("plugin").description("Commands for inlang plugins.").argument("[command]").addCommand(build);

// package.json
var version = "3.1.15";

// src/services/error-monitoring/implementation.ts
init_define_ENV_DEFINED_IN_BUILD_STEP();
var Sentry = __toESM(require_cjs5(), 1);

// src/env-variables/index.ts
init_define_ENV_DEFINED_IN_BUILD_STEP();
var ENV_VARIABLES2 = (
  // @ts-expect-error - the env variables are set in the build step
  define_ENV_DEFINED_IN_BUILD_STEP_default
);

// src/services/error-monitoring/implementation.ts
function initErrorMonitoring() {
  Sentry.init({
    dsn: "https://b7a06c6d36454ef2bc5e2ca7e257bd5b@o4504345873285120.ingest.sentry.io/4505172745650176",
    release: version,
    // Not interested in performance data
    tracesSampleRate: 0,
    environment: ENV_VARIABLES2.IS_PRODUCTION ? "production" : "development"
  });
}

// src/services/error-monitoring/silenceKnownShutdownNoise.ts
init_define_ENV_DEFINED_IN_BUILD_STEP();
var FILE_QUEUE_CONTEXT_PATTERN = /(file queue|Error processing file queue entry)/i;
var DB_CLOSED_PATTERN = /(DB has been closed|driver has already been destroyed)/i;
function shouldSilenceConsoleError(args) {
  if (args.length === 0) {
    return false;
  }
  const text = args.map((arg) => {
    if (arg instanceof Error) {
      return `${arg.name}: ${arg.message}`;
    }
    return String(arg);
  }).join(" ");
  return FILE_QUEUE_CONTEXT_PATTERN.test(text) && DB_CLOSED_PATTERN.test(text);
}
function silenceKnownShutdownNoise() {
  const originalConsoleError = console.error.bind(console);
  console.error = (...args) => {
    if (shouldSilenceConsoleError(args)) {
      return;
    }
    originalConsoleError(...args);
  };
}

// src/commands/validate/index.ts
init_define_ENV_DEFINED_IN_BUILD_STEP();
var validate2 = new Command().command("validate").description("Validate the inlang project settings file.").requiredOption(projectOption.flags, projectOption.description).action(validateCommandAction);
async function validateCommandAction(args) {
  let exitCode = 0;
  try {
    log.info("\u{1F50E} Validating the inlang project...");
    const project = await getInlangProject({ projectPath: args.project });
    const errors = await project.errors.get();
    if (errors.length > 0) {
      log.info("The project contains errors:");
      for (const error of errors)
        log.error(error);
      exitCode = 1;
      return;
    }
    log.success("The project is valid!");
  } catch (error) {
    log.error(error);
    exitCode = 1;
  } finally {
    process.exit(exitCode);
  }
}

// src/telemetry/capture.ts
init_define_ENV_DEFINED_IN_BUILD_STEP();
var capture = async (args) => {
  if (ENV_VARIABLES2.PUBLIC_POSTHOG_TOKEN === void 0) {
    return;
  }
  try {
    await fetch("https://eu.posthog.com/capture/", {
      method: "POST",
      body: JSON.stringify({
        // @ts-expect-error - env variable is set in build step
        api_key: define_ENV_DEFINED_IN_BUILD_STEP_default.PUBLIC_POSTHOG_TOKEN,
        event: args.event,
        // id is "unknown" because no user information is available
        distinct_id: "unknown",
        properties: {
          $groups: args.projectId ? { project: args.projectId } : void 0,
          ...args.properties
        }
      })
    });
  } catch (e2) {
  }
};

// src/commands/lint/index.ts
init_define_ENV_DEFINED_IN_BUILD_STEP();
var lint = new Command().command("lint").description("Validate the inlang project settings file.").option("--project <path>", "Path to the inlang project.").option("--languageTags", "Fix linting errors.").action(lintCommandAction);
async function lintCommandAction(args) {
  log.warn(
    "Inlang lint rules have been removed for the CLI v3 after the major lix and inlang SDK update to be replaced by a new validation system that generalizes beyond inlang and to reduce the scope of the update."
  );
  log.info(
    "Upvote https://github.com/opral/lix/issues/239 to re-introduce linting."
  );
}

// src/main.ts
initErrorMonitoring();
silenceKnownShutdownNoise();
var cli = new Command().name("inlang").version(version).description("CLI for inlang.").addCommand(validate2).addCommand(machine).addCommand(plugin).addCommand(lint).hook("postAction", async (command) => {
  var _a8;
  const name = command.args.filter(
    // shouldn't start with a flag and the previous arg shouldn't be a flag
    (arg, i2) => {
      var _a9;
      return !arg.startsWith("-") && !((_a9 = command.args[i2 - 1]) == null ? void 0 : _a9.startsWith("-"));
    }
  );
  await capture({
    event: `CLI command executed`,
    projectId: await ((_a8 = lastUsedProject) == null ? void 0 : _a8.id.get()),
    properties: {
      name: name.join(" "),
      args: command.args.join(" "),
      node_version: process.versions.node,
      platform: process.platform,
      version
    }
  });
});
export {
  cli
};
/*! Bundled license information:

js-sha256/src/sha256.js:
  (**
   * [js-sha256]{@link https://github.com/emn178/js-sha256}
   *
   * @version 0.11.1
   * @author Chen, Yi-Cyuan [emn178@gmail.com]
   * @copyright Chen, Yi-Cyuan 2014-2025
   * @license MIT
   *)

@sentry/node/cjs/integrations/anr/worker-script.js:
  (*! @sentry/node 7.120.3 (5a833b4) | https://github.com/getsentry/sentry-javascript *)

localforage/dist/localforage.js:
  (*!
      localForage -- Offline Storage, Improved
      Version 1.10.0
      https://localforage.github.io/localForage
      (c) 2013-2017 Mozilla, Apache License 2.0
  *)
*/
